facet-format 0.44.6

Core Serializer/Deserializer traits for facet's next-generation format architecture with JIT compilation 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! Format-specific JIT code generation trait.
//!
//! This module defines the `JitFormat` trait that format crates implement
//! to provide Cranelift IR generation for format-specific parsing.

use cranelift::prelude::*;
use cranelift_module::Module;

/// How a format encodes struct fields.
///
/// This determines which compilation strategy the JIT uses for struct deserialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StructEncoding {
    /// Map-based encoding: fields are keyed by name.
    ///
    /// Used by text formats like JSON, YAML, TOML where struct fields appear as
    /// key-value pairs (e.g., `{"name": "Alice", "age": 30}`).
    ///
    /// The JIT compiler generates a key-dispatch loop that:
    /// 1. Reads field names via `emit_map_read_key`
    /// 2. Matches keys to fields via dispatch table
    /// 3. Handles missing/extra fields
    Map,

    /// Positional encoding: fields appear in declaration order without keys.
    ///
    /// Used by binary formats like postcard, msgpack (array mode) where struct
    /// fields are encoded back-to-back in schema order with no field names.
    ///
    /// The JIT compiler generates straight-line code that:
    /// 1. Parses each field in declaration order
    /// 2. Does NOT call `emit_map_*` methods
    /// 3. Requires all fields to be present (no missing field handling)
    ///
    /// Note: `#[facet(flatten)]` is not supported with positional encoding.
    Positional,
}

/// Cursor state during JIT code generation.
///
/// Represents the position within the input buffer during parsing.
pub struct JitCursor {
    /// Pointer to the start of the input buffer (*const u8)
    pub input_ptr: Value,
    /// Length of the input buffer
    pub len: Value,
    /// Current position (mutable variable)
    pub pos: Variable,
    /// Platform pointer type (i64 on 64-bit)
    pub ptr_type: Type,
    /// Pointer to JitScratch for error reporting and scratch space
    pub scratch_ptr: Value,
}

/// Represents a parsed string value during JIT codegen.
///
/// Strings can be either borrowed (pointing into input) or owned (heap allocated).
#[derive(Clone, Copy)]
pub struct JitStringValue {
    /// Pointer to string data (*const u8 or *mut u8)
    pub ptr: Value,
    /// Length in bytes
    pub len: Value,
    /// Capacity (only meaningful when owned)
    pub cap: Value,
    /// 1 if owned (needs drop), 0 if borrowed
    pub owned: Value,
}

/// Scratch space for error reporting from Tier-2 compiled functions.
#[repr(C)]
pub struct JitScratch {
    /// Error code (format-specific)
    pub error_code: i32,
    /// Byte position where error occurred
    pub error_pos: usize,
    /// Whether the output was initialized (used for cleanup on error)
    /// 0 = not initialized, 1 = initialized
    pub output_initialized: u8,
    /// Runtime max collection length used by format-specific Tier-2 guards.
    pub max_collection_elements: u64,

    // String scratch buffer for reuse during parsing.
    // This avoids allocating a new Vec for each escaped string.
    /// Pointer to string scratch buffer data
    pub string_scratch_ptr: *mut u8,
    /// Current length of data in the scratch buffer
    pub string_scratch_len: usize,
    /// Capacity of the scratch buffer
    pub string_scratch_cap: usize,
}

impl Default for JitScratch {
    fn default() -> Self {
        Self {
            error_code: 0,
            error_pos: 0,
            output_initialized: 0,
            max_collection_elements: u64::MAX,
            string_scratch_ptr: std::ptr::null_mut(),
            string_scratch_len: 0,
            string_scratch_cap: 0,
        }
    }
}

impl Drop for JitScratch {
    fn drop(&mut self) {
        // Free the string scratch buffer if allocated
        if !self.string_scratch_ptr.is_null() && self.string_scratch_cap > 0 {
            unsafe {
                let _ = Vec::from_raw_parts(
                    self.string_scratch_ptr,
                    self.string_scratch_len,
                    self.string_scratch_cap,
                );
            }
            // Vec drop will deallocate
        }
    }
}

/// Offset of `error_code` field in `JitScratch`.
pub const JIT_SCRATCH_ERROR_CODE_OFFSET: i32 = std::mem::offset_of!(JitScratch, error_code) as i32;

/// Offset of `error_pos` field in `JitScratch`.
pub const JIT_SCRATCH_ERROR_POS_OFFSET: i32 = std::mem::offset_of!(JitScratch, error_pos) as i32;

/// Offset of `output_initialized` field in `JitScratch`.
pub const JIT_SCRATCH_OUTPUT_INITIALIZED_OFFSET: i32 =
    std::mem::offset_of!(JitScratch, output_initialized) as i32;

/// Offset of `max_collection_elements` field in `JitScratch`.
pub const JIT_SCRATCH_MAX_COLLECTION_ELEMENTS_OFFSET: i32 =
    std::mem::offset_of!(JitScratch, max_collection_elements) as i32;

/// Offset of `string_scratch_ptr` field in `JitScratch`.
/// Reserved for future JIT code that directly accesses scratch buffer.
#[allow(dead_code)]
pub const JIT_SCRATCH_STRING_PTR_OFFSET: i32 =
    std::mem::offset_of!(JitScratch, string_scratch_ptr) as i32;

/// Offset of `string_scratch_len` field in `JitScratch`.
/// Reserved for future JIT code that directly accesses scratch buffer.
#[allow(dead_code)]
pub const JIT_SCRATCH_STRING_LEN_OFFSET: i32 =
    std::mem::offset_of!(JitScratch, string_scratch_len) as i32;

/// Offset of `string_scratch_cap` field in `JitScratch`.
/// Reserved for future JIT code that directly accesses scratch buffer.
#[allow(dead_code)]
pub const JIT_SCRATCH_STRING_CAP_OFFSET: i32 =
    std::mem::offset_of!(JitScratch, string_scratch_cap) as i32;

/// Format-specific JIT code generation trait.
///
/// Implemented by format crates (e.g., `facet-json`) to provide
/// Cranelift IR generation for parsing their specific syntax.
///
/// The trait methods emit Cranelift IR that:
/// - Reads from `(input_ptr, len)` at position `cursor.pos`
/// - Updates `cursor.pos` as parsing advances
/// - Returns error codes (0 = success, negative = error)
///
/// ## Helper-based implementation
///
/// For formats that use external helper functions (Option B approach),
/// override the `helper_*` methods to return symbol names. The default
/// `emit_*` implementations will then generate calls to those helpers.
/// If a `helper_*` method returns `None`, that operation is unsupported.
pub trait JitFormat: Default + Copy + 'static {
    /// Register format-specific helper functions with the JIT builder.
    /// Called before compilation to register all helper symbols.
    fn register_helpers(builder: &mut cranelift_jit::JITBuilder);

    // =========================================================================
    // Helper symbol names (Option B: formats provide helper function names)
    // =========================================================================
    // These return the symbol names for helper functions that the format
    // registers via `register_helpers`. The compiler will import and call these.
    // Return `None` if the operation is not supported.

    /// Symbol name for seq_begin helper: fn(input, len, pos) -> (new_pos, error)
    fn helper_seq_begin() -> Option<&'static str> {
        None
    }

    /// Symbol name for seq_is_end helper: fn(input, len, pos) -> (packed_pos_end, error)
    /// packed_pos_end = (is_end << 63) | new_pos
    fn helper_seq_is_end() -> Option<&'static str> {
        None
    }

    /// Symbol name for seq_next helper: fn(input, len, pos) -> (new_pos, error)
    fn helper_seq_next() -> Option<&'static str> {
        None
    }

    /// Symbol name for parse_bool helper: fn(input, len, pos) -> (packed_pos_value, error)
    /// packed_pos_value = (value << 63) | new_pos
    fn helper_parse_bool() -> Option<&'static str> {
        None
    }

    /// Symbol name for parse_i64 helper: fn(input, len, pos) -> (new_pos, value, error)
    fn helper_parse_i64() -> Option<&'static str> {
        None
    }

    /// Symbol name for parse_u64 helper: fn(input, len, pos) -> (new_pos, value, error)
    fn helper_parse_u64() -> Option<&'static str> {
        None
    }

    /// Symbol name for parse_f64 helper: fn(input, len, pos) -> (new_pos, value, error)
    fn helper_parse_f64() -> Option<&'static str> {
        None
    }

    /// Symbol name for parse_string helper (format-specific signature)
    fn helper_parse_string() -> Option<&'static str> {
        None
    }

    /// Stack slot size for sequence (array) state, 0 if no state needed.
    const SEQ_STATE_SIZE: u32 = 0;
    /// Stack slot alignment for sequence state.
    const SEQ_STATE_ALIGN: u32 = 1;

    /// Whether `emit_seq_begin` returns an accurate element count.
    ///
    /// - `true`: Format provides exact count (e.g., postcard with length prefix).
    ///   Enables direct-fill optimization where count=0 means empty array.
    /// - `false`: Format doesn't know count upfront (e.g., JSON with delimiters).
    ///   count=0 means "unknown", must use push-based loop.
    const PROVIDES_SEQ_COUNT: bool = false;

    /// Stack slot size for map (object) state, 0 if no state needed.
    const MAP_STATE_SIZE: u32 = 0;
    /// Stack slot alignment for map state.
    const MAP_STATE_ALIGN: u32 = 1;

    /// How this format encodes struct fields.
    ///
    /// - [`StructEncoding::Map`]: Fields are keyed by name (JSON, YAML, TOML).
    ///   The compiler uses `emit_map_*` methods and key dispatch.
    /// - [`StructEncoding::Positional`]: Fields are in declaration order (postcard, msgpack-array).
    ///   The compiler parses fields sequentially without key matching.
    ///
    /// Default is `Map` for backward compatibility with existing format implementations.
    const STRUCT_ENCODING: StructEncoding = StructEncoding::Map;

    // === Utility ===

    /// Emit code to skip whitespace/comments.
    /// Returns error code (0 = success).
    fn emit_skip_ws(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> Value;

    /// Emit code to skip an entire value (for unknown fields).
    /// Returns error code (0 = success).
    fn emit_skip_value(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> Value;

    // === Null / Option ===

    /// Emit code to peek whether the next value is null (without consuming).
    /// Returns (is_null: i8, error: i32).
    fn emit_peek_null(&self, b: &mut FunctionBuilder, c: &mut JitCursor) -> (Value, Value);

    /// Emit code to consume a null value (after peek_null returned true).
    /// Returns error code.
    fn emit_consume_null(&self, b: &mut FunctionBuilder, c: &mut JitCursor) -> Value;

    // === Scalars ===

    /// Emit code to parse a boolean.
    /// Returns (value: i8, error: i32).
    fn emit_parse_bool(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (Value, Value);

    /// Emit code to parse an unsigned 8-bit integer (raw byte).
    /// Returns (value: i8, error: i32).
    fn emit_parse_u8(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (Value, Value);

    /// Emit code to parse a signed 8-bit integer.
    /// Returns (value: i8 as i8, error: i32).
    ///
    /// Default implementation reads a single byte and reinterprets as signed.
    /// Text formats should override to parse text representation.
    fn emit_parse_i8(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (Value, Value) {
        // Default: read single byte as i8 (same as u8, reinterpreted)
        let (u8_val, err) = self.emit_parse_u8(_module, b, c);
        // u8 value is already in correct bit pattern for i8
        (u8_val, err)
    }

    /// Emit code to parse a signed 64-bit integer.
    /// Returns (value: i64, error: i32).
    fn emit_parse_i64(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (Value, Value);

    /// Emit code to parse an unsigned 64-bit integer.
    /// Returns (value: u64 as i64, error: i32).
    fn emit_parse_u64(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (Value, Value);

    /// Emit code to parse a 32-bit float.
    /// Returns (value: f32, error: i32).
    ///
    /// Default implementation calls `emit_parse_f64` and demotes to f32.
    /// Binary formats that encode f32 differently from f64 should override this.
    fn emit_parse_f32(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (Value, Value) {
        let (f64_val, err) = self.emit_parse_f64(module, b, c);
        let f32_val = b.ins().fdemote(types::F32, f64_val);
        (f32_val, err)
    }

    /// Emit code to parse a 64-bit float.
    /// Returns (value: f64, error: i32).
    fn emit_parse_f64(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (Value, Value);

    /// Emit code to parse a string.
    /// Returns (JitStringValue, error: i32).
    fn emit_parse_string(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (JitStringValue, Value);

    // === Sequences (arrays) ===

    /// Emit code to expect and consume sequence start delimiter (e.g., '[').
    /// `state_ptr` points to SEQ_STATE_SIZE bytes of stack space.
    ///
    /// Returns `(count, error)` where:
    /// - `count`: The number of elements if known (for length-prefixed formats like postcard),
    ///   or 0 if unknown (for delimiter formats like JSON). Used for Vec preallocation.
    /// - `error`: Error code (0 = success, negative = error)
    fn emit_seq_begin(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> (Value, Value);

    /// Emit code to check if we're at sequence end (e.g., ']').
    /// Does NOT consume the delimiter.
    /// Returns (is_end: i8, error: i32).
    fn emit_seq_is_end(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> (Value, Value);

    /// Emit code to advance to next sequence element.
    /// Called after parsing an element, handles separator (e.g., ',').
    /// Returns error code.
    fn emit_seq_next(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> Value;

    /// Optional: Emit code to bulk-copy a `Vec<u8>` sequence.
    ///
    /// For formats where byte sequences are stored contiguously without per-byte encoding
    /// (like postcard), this enables a memcpy fast-path instead of byte-by-byte parsing.
    ///
    /// Called AFTER `emit_seq_begin` has been called and returned `count > 0`.
    /// The cursor position is right after the length prefix.
    ///
    /// Parameters:
    /// - `count`: The number of bytes to copy (from `emit_seq_begin`)
    /// - `dest_ptr`: Destination buffer pointer (from `as_mut_ptr_typed`)
    ///
    /// Returns `Some(error_code)` if supported (0 = success, advances cursor by `count`),
    /// or `None` if this format doesn't support bulk byte copy.
    ///
    /// Default implementation returns `None` (not supported).
    fn emit_seq_bulk_copy_u8(
        &self,
        _b: &mut FunctionBuilder,
        _c: &mut JitCursor,
        _count: Value,
        _dest_ptr: Value,
    ) -> Option<Value> {
        None
    }

    /// Optional: Check for and consume an empty sequence (e.g., `[]` in JSON).
    ///
    /// This is a fast path optimization for empty arrays. If supported, it:
    /// 1. Checks if the current position has an empty sequence pattern
    /// 2. If yes: consumes it, skips trailing whitespace, returns (true, 0)
    /// 3. If no: leaves cursor unchanged and returns (false, 0)
    /// 4. On error: returns (false, error_code)
    ///
    /// Returns `Some((is_empty: i8, error: i32))` if the format supports this optimization,
    /// or `None` to use the normal seq_begin/seq_is_end path.
    ///
    /// Default implementation returns `None` (not supported).
    fn emit_try_empty_seq(
        &self,
        _b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> Option<(Value, Value)> {
        None
    }

    // === Maps (objects) ===

    /// Optional: Check for and consume an empty map (e.g., `{}` in JSON).
    ///
    /// This is a fast path optimization for empty maps. If supported, it:
    /// 1. Checks if the current position has an empty map pattern
    /// 2. If yes: consumes it, skips trailing whitespace, returns (true, 0)
    /// 3. If no: leaves cursor unchanged and returns (false, 0)
    /// 4. On error: returns (false, error_code)
    ///
    /// Returns `Some((is_empty: i8, error: i32))` if the format supports this optimization,
    /// or `None` to use the normal map_begin/map_is_end path.
    ///
    /// Default implementation returns `None` (not supported).
    fn emit_try_empty_map(
        &self,
        _b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> Option<(Value, Value)> {
        None
    }

    /// Emit code to expect and consume map start delimiter (e.g., '{').
    /// Returns error code.
    fn emit_map_begin(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> Value;

    /// Emit code to check if we're at map end (e.g., '}').
    /// Does NOT consume the delimiter.
    /// Returns (is_end: i8, error: i32).
    fn emit_map_is_end(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> (Value, Value);

    /// Emit code to read a map key.
    /// Returns (JitStringValue for key, error: i32).
    fn emit_map_read_key(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> (JitStringValue, Value);

    /// Emit code to consume key-value separator (e.g., ':').
    /// Returns error code.
    fn emit_map_kv_sep(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> Value;

    /// Emit code to advance to next map entry.
    /// Called after parsing a value, handles entry separator (e.g., ',').
    /// Returns error code.
    fn emit_map_next(
        &self,
        module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        state_ptr: Value,
    ) -> Value;

    /// Optional: normalize a key before field matching.
    /// Default is no-op. YAML/TOML may want case-folding.
    fn emit_key_normalize(&self, _b: &mut FunctionBuilder, _key: &mut JitStringValue) {}
}

/// Stub implementation for parsers that don't support format JIT.
#[derive(Default, Clone, Copy)]
pub struct NoFormatJit;

impl JitFormat for NoFormatJit {
    fn register_helpers(_builder: &mut cranelift_jit::JITBuilder) {}

    fn emit_skip_ws(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> Value {
        // Return error: unsupported
        b.ins().iconst(types::I32, -1)
    }

    fn emit_skip_value(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> Value {
        b.ins().iconst(types::I32, -1)
    }

    fn emit_peek_null(&self, b: &mut FunctionBuilder, _c: &mut JitCursor) -> (Value, Value) {
        let zero = b.ins().iconst(types::I8, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_consume_null(&self, b: &mut FunctionBuilder, _c: &mut JitCursor) -> Value {
        b.ins().iconst(types::I32, -1)
    }

    fn emit_parse_bool(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> (Value, Value) {
        let zero = b.ins().iconst(types::I8, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_parse_u8(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> (Value, Value) {
        let zero = b.ins().iconst(types::I8, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_parse_i64(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> (Value, Value) {
        let zero = b.ins().iconst(types::I64, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_parse_u64(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> (Value, Value) {
        let zero = b.ins().iconst(types::I64, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_parse_f64(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
    ) -> (Value, Value) {
        let zero = b.ins().f64const(0.0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_parse_string(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
    ) -> (JitStringValue, Value) {
        let null = b.ins().iconst(c.ptr_type, 0);
        let zero = b.ins().iconst(c.ptr_type, 0);
        let err = b.ins().iconst(types::I32, -1);
        (
            JitStringValue {
                ptr: null,
                len: zero,
                cap: zero,
                owned: b.ins().iconst(types::I8, 0),
            },
            err,
        )
    }

    fn emit_seq_begin(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        _state_ptr: Value,
    ) -> (Value, Value) {
        let zero_count = b.ins().iconst(c.ptr_type, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero_count, err)
    }

    fn emit_seq_is_end(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
        _state_ptr: Value,
    ) -> (Value, Value) {
        let zero = b.ins().iconst(types::I8, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_seq_next(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
        _state_ptr: Value,
    ) -> Value {
        b.ins().iconst(types::I32, -1)
    }

    fn emit_map_begin(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
        _state_ptr: Value,
    ) -> Value {
        b.ins().iconst(types::I32, -1)
    }

    fn emit_map_is_end(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
        _state_ptr: Value,
    ) -> (Value, Value) {
        let zero = b.ins().iconst(types::I8, 0);
        let err = b.ins().iconst(types::I32, -1);
        (zero, err)
    }

    fn emit_map_read_key(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        c: &mut JitCursor,
        _state_ptr: Value,
    ) -> (JitStringValue, Value) {
        let null = b.ins().iconst(c.ptr_type, 0);
        let zero = b.ins().iconst(c.ptr_type, 0);
        let err = b.ins().iconst(types::I32, -1);
        (
            JitStringValue {
                ptr: null,
                len: zero,
                cap: zero,
                owned: b.ins().iconst(types::I8, 0),
            },
            err,
        )
    }

    fn emit_map_kv_sep(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
        _state_ptr: Value,
    ) -> Value {
        b.ins().iconst(types::I32, -1)
    }

    fn emit_map_next(
        &self,
        _module: &mut cranelift_jit::JITModule,
        b: &mut FunctionBuilder,
        _c: &mut JitCursor,
        _state_ptr: Value,
    ) -> Value {
        b.ins().iconst(types::I32, -1)
    }
}

/// Returns the C ABI calling convention for the current platform.
///
/// This is necessary because Cranelift's `make_signature()` uses a default calling
/// convention that may not match `extern "C"` on all platforms. On Windows x64,
/// `extern "C"` uses the Microsoft x64 calling convention (WindowsFastcall),
/// while Cranelift may default to System V.
///
/// Use this when creating signatures for `call_indirect` to `extern "C"` helper functions.
#[inline]
pub const fn c_call_conv() -> cranelift::codegen::isa::CallConv {
    #[cfg(all(target_os = "windows", target_arch = "x86_64"))]
    {
        cranelift::codegen::isa::CallConv::WindowsFastcall
    }
    #[cfg(not(all(target_os = "windows", target_arch = "x86_64")))]
    {
        // On non-Windows platforms, System V is the standard C ABI for x86_64
        // For other architectures, Cranelift's default is usually correct
        #[cfg(target_arch = "x86_64")]
        {
            cranelift::codegen::isa::CallConv::SystemV
        }
        #[cfg(target_arch = "aarch64")]
        {
            cranelift::codegen::isa::CallConv::AppleAarch64
        }
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            // Fallback - let Cranelift decide
            cranelift::codegen::isa::CallConv::Fast
        }
    }
}

/// Creates a new signature with the correct C ABI calling convention for the current platform.
///
/// Use this instead of `module.make_signature()` when creating signatures for calls to
/// `extern "C"` functions. This ensures the correct calling convention is always set.
///
/// # Example
/// ```ignore
/// let sig = make_c_sig(module);
/// sig.params.push(AbiParam::new(pointer_type));
/// sig.returns.push(AbiParam::new(types::I32));
/// ```
#[inline]
pub fn make_c_sig(module: &cranelift_jit::JITModule) -> cranelift::codegen::ir::Signature {
    let mut sig = module.make_signature();
    sig.call_conv = c_call_conv();
    sig
}