lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
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
//! Target-specific native layout metadata used at the Rust/JIT boundary.
//!
//! Most applications should prefer [`crate::LehitRegistration`] for concrete
//! structures. Manual [`NativeAbi`] implementations are an advanced unsafe API,
//! especially for enums whose tags, niches, and payload offsets depend on the
//! exact target and compiler.

use std::alloc::Layout;
use std::any::TypeId;
use std::num::*;
use std::sync::OnceLock;

/// Target- and compiler-specific runtime description of a native Rust value.
///
/// Registration compares this metadata with the physical facts currently
/// represented by the Lehit contract. Validation is not yet exhaustive for all
/// nested layouts and scalar register classes; incorrect metadata remains a
/// caller safety violation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeTypeLayout {
    pub rust_type_id: TypeId,
    pub size: usize,
    pub align: usize,
    pub kind: NativeTypeKind,
}

impl NativeTypeLayout {
    pub fn of<T: 'static>(size: usize, align: usize, kind: NativeTypeKind) -> Self {
        Self {
            rust_type_id: TypeId::of::<T>(),
            size,
            align,
            kind,
        }
    }

    pub fn for_type<T: 'static>(kind: NativeTypeKind) -> Self {
        Self::of::<T>(std::mem::size_of::<T>(), std::mem::align_of::<T>(), kind)
    }

    pub fn structure<T: 'static>(fields: Vec<NativeField>) -> Self {
        Self::for_type::<T>(NativeTypeKind::Structure { fields })
    }

    pub fn enum_type<T: 'static>(layout: NativeEnumLayout) -> Self {
        Self::for_type::<T>(NativeTypeKind::Enum(layout))
    }

    pub fn opaque<T: 'static>() -> Self {
        Self::for_type::<T>(NativeTypeKind::Opaque)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NativePassMode {
    Indirect,
    Registers(Vec<NativeRegisterChunk>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NativeRegisterChunk {
    pub offset: usize,
    pub class: NativeRegisterClass,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeRegisterClass {
    Integer { bits: u16 },
    Float { bits: u16 },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NativeTypeKind {
    Scalar {
        bits: u16,
        signed: bool,
    },
    /// Boundary representation for a type declared inside Lehit. Ownership is
    /// transferred as `[u8; size]`; borrowing uses a reference to that exact
    /// byte array and therefore does not copy or marshal the payload.
    Bytes,
    Structure {
        fields: Vec<NativeField>,
    },
    Enum(NativeEnumLayout),
    Opaque,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeField {
    pub index: u32,
    pub offset: usize,
    pub layout: &'static NativeTypeLayout,
}

impl NativeField {
    pub const fn new(index: u32, offset: usize, layout: &'static NativeTypeLayout) -> Self {
        Self {
            index,
            offset,
            layout,
        }
    }

    pub fn of<T: NativeAbi>(index: u32, offset: usize) -> Self {
        Self::new(index, offset, T::native_layout())
    }
}

/// Enum encoding is explicit because Rust may store a discriminant directly or
/// encode it in an invalid (niche) payload value such as the null pointer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeEnumLayout {
    pub variants: Vec<NativeEnumVariant>,
    pub tag: NativeEnumTag,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeEnumVariant {
    /// Semantic variant index; it need not equal the physical tag value.
    pub index: u32,
    pub payload: Option<&'static NativeTypeLayout>,
    /// Physical payload offset from the enum base. Unit variants use `None`.
    pub payload_offset: Option<usize>,
}

impl NativeEnumVariant {
    pub const fn unit(index: u32) -> Self {
        Self {
            index,
            payload: None,
            payload_offset: None,
        }
    }

    pub const fn payload(
        index: u32,
        payload: &'static NativeTypeLayout,
        payload_offset: usize,
    ) -> Self {
        Self {
            index,
            payload: Some(payload),
            payload_offset: Some(payload_offset),
        }
    }
}

impl NativeEnumLayout {
    pub fn direct(
        variants: Vec<NativeEnumVariant>,
        offset: usize,
        bits: u16,
        signed: bool,
        variant_tags: Vec<u128>,
    ) -> Self {
        Self {
            variants,
            tag: NativeEnumTag::Direct {
                offset,
                bits,
                signed,
                variant_tags,
            },
        }
    }

    pub fn niche(
        variants: Vec<NativeEnumVariant>,
        offset: usize,
        bits: u16,
        niche_start: u128,
        niche_variants: std::ops::RangeInclusive<u32>,
        data_variant: u32,
    ) -> Self {
        Self {
            variants,
            tag: NativeEnumTag::Niche {
                offset,
                bits,
                niche_start,
                niche_variants,
                data_variant,
            },
        }
    }

    pub fn single(variant: NativeEnumVariant) -> Self {
        Self {
            variants: vec![variant],
            tag: NativeEnumTag::SingleVariant,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NativeEnumTag {
    Direct {
        offset: usize,
        bits: u16,
        signed: bool,
        variant_tags: Vec<u128>,
    },
    Niche {
        offset: usize,
        bits: u16,
        niche_start: u128,
        niche_variants: std::ops::RangeInclusive<u32>,
        data_variant: u32,
    },
    SingleVariant,
}

/// Describes the physical ABI of one concrete Rust type.
///
/// # Safety
///
/// The returned metadata must describe the actual Rust layout of `Self` for the
/// current target and compiler. `rust_type_id`, size, non-zero power-of-two
/// alignment, field indices/offsets, enum tags, payload offsets, and register
/// pass mode must all agree with the real type. Metadata must remain immutable
/// for the process lifetime. Incorrect metadata can make generated reads,
/// writes, calls, or drops undefined behaviour.
///
/// Prefer `#[repr(C)]` or a fixed integer enum representation. Compiler-private
/// `repr(Rust)` niches require a layout probe tied to the exact toolchain.
pub unsafe trait NativeAbi: 'static {
    /// Returns immutable physical layout metadata for `Self`.
    fn native_layout() -> &'static NativeTypeLayout;

    /// Selects indirect or target-register passing for `Self`.
    fn native_pass_mode() -> NativePassMode {
        NativePassMode::Indirect
    }
}

/// Owned boundary value for a nominal type whose definition lives in Lehit.
///
/// The bytes are intentionally opaque to Rust. Field access remains the
/// responsibility of generated Lehit code and its registered type layout.
#[repr(transparent)]
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct LehitValue<const SIZE: usize> {
    bytes: [u8; SIZE],
}

impl<const SIZE: usize> LehitValue<SIZE> {
    /// Wraps opaque bytes without validating a nominal Lehit type.
    ///
    /// Use arbitrary bytes only for plain-data contracts. Resource-bearing
    /// values may contain pointers, enum validity constraints, or generated
    /// drop state that cannot be validated by this size-only container.
    pub const fn from_bytes(bytes: [u8; SIZE]) -> Self {
        Self { bytes }
    }

    /// Borrows the opaque boundary bytes.
    pub const fn as_bytes(&self) -> &[u8; SIZE] {
        &self.bytes
    }

    /// Mutably borrows opaque bytes without validating type invariants.
    ///
    /// Do not use this to modify pointer/tag/drop state of a resource-bearing
    /// value. A future API will distinguish proven plain data from typed
    /// resource values.
    pub fn as_bytes_mut(&mut self) -> &mut [u8; SIZE] {
        &mut self.bytes
    }

    /// Consumes the wrapper and returns its opaque bytes.
    pub const fn into_bytes(self) -> [u8; SIZE] {
        self.bytes
    }
}

impl<const SIZE: usize> std::fmt::Debug for LehitValue<SIZE> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_tuple("LehitValue")
            .field(&self.bytes)
            .finish()
    }
}

// SAFETY: `repr(transparent)` guarantees the same representation as the byte
// array. This describes only the boundary blob, not a Rust interpretation of
// fields stored inside it.
unsafe impl<const SIZE: usize> NativeAbi for LehitValue<SIZE> {
    fn native_layout() -> &'static NativeTypeLayout {
        static LAYOUTS: OnceLock<
            std::sync::Mutex<std::collections::HashMap<usize, &'static NativeTypeLayout>>,
        > = OnceLock::new();
        let layouts = LAYOUTS.get_or_init(Default::default);
        let mut layouts = layouts.lock().unwrap_or_else(|error| error.into_inner());
        *layouts.entry(SIZE).or_insert_with(|| {
            Box::leak(Box::new(NativeTypeLayout {
                rust_type_id: TypeId::of::<LehitValue<SIZE>>(),
                size: SIZE,
                align: 1,
                kind: NativeTypeKind::Bytes,
            }))
        })
    }
}

macro_rules! scalar_abi {
    ($type:ty, $signed:expr) => {
        unsafe impl NativeAbi for $type {
            fn native_layout() -> &'static NativeTypeLayout {
                static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
                LAYOUT.get_or_init(|| NativeTypeLayout {
                    rust_type_id: TypeId::of::<$type>(),
                    size: Layout::new::<$type>().size(),
                    align: Layout::new::<$type>().align(),
                    kind: NativeTypeKind::Scalar {
                        bits: (Layout::new::<$type>().size() * 8) as u16,
                        signed: $signed,
                    },
                })
            }
        }
    };
}

scalar_abi!(u8, false);
scalar_abi!(u16, false);
scalar_abi!(u32, false);
scalar_abi!(u64, false);
scalar_abi!(u128, false);
scalar_abi!(usize, false);
scalar_abi!(i8, true);
scalar_abi!(i16, true);
scalar_abi!(i32, true);
scalar_abi!(i64, true);
scalar_abi!(i128, true);
scalar_abi!(isize, true);
scalar_abi!(f32, true);
scalar_abi!(f64, true);

fn cached_native_layout<T: 'static>(
    create: impl FnOnce() -> NativeTypeLayout,
) -> &'static NativeTypeLayout {
    static LAYOUTS: OnceLock<
        std::sync::Mutex<std::collections::HashMap<TypeId, &'static NativeTypeLayout>>,
    > = OnceLock::new();
    let layouts = LAYOUTS.get_or_init(Default::default);
    let type_id = TypeId::of::<T>();
    if let Some(layout) = layouts
        .lock()
        .unwrap_or_else(|error| error.into_inner())
        .get(&type_id)
        .copied()
    {
        return layout;
    }

    // Do not hold the cache lock while constructing nested layouts: for
    // example `Option<Box<T>>` asks for `Box<T>` from its factory.
    let created = Box::leak(Box::new(create()));
    let mut cache = layouts.lock().unwrap_or_else(|error| error.into_inner());
    *cache.entry(type_id).or_insert(created)
}

unsafe impl<T: 'static> NativeAbi for *const T {
    fn native_layout() -> &'static NativeTypeLayout {
        cached_native_layout::<Self>(NativeTypeLayout::opaque::<Self>)
    }

    fn native_pass_mode() -> NativePassMode {
        integer_register_pass_mode(Layout::new::<Self>().size())
    }
}

unsafe impl<T: 'static> NativeAbi for *mut T {
    fn native_layout() -> &'static NativeTypeLayout {
        cached_native_layout::<Self>(NativeTypeLayout::opaque::<Self>)
    }

    fn native_pass_mode() -> NativePassMode {
        integer_register_pass_mode(Layout::new::<Self>().size())
    }
}

unsafe impl<T: 'static> NativeAbi for Box<T> {
    fn native_layout() -> &'static NativeTypeLayout {
        cached_native_layout::<Self>(|| {
            NativeTypeLayout::structure::<Self>(vec![NativeField::of::<*mut T>(0, 0)])
        })
    }

    fn native_pass_mode() -> NativePassMode {
        integer_register_pass_mode(Layout::new::<Self>().size())
    }
}

unsafe impl<T: 'static> NativeAbi for Option<Box<T>> {
    fn native_layout() -> &'static NativeTypeLayout {
        cached_native_layout::<Self>(|| {
            NativeTypeLayout::enum_type::<Self>(NativeEnumLayout::niche(
                vec![
                    NativeEnumVariant::unit(0),
                    NativeEnumVariant::payload(1, Box::<T>::native_layout(), 0),
                ],
                0,
                (Layout::new::<usize>().size() * 8) as u16,
                0,
                0..=0,
                1,
            ))
        })
    }

    fn native_pass_mode() -> NativePassMode {
        integer_register_pass_mode(Layout::new::<Self>().size())
    }
}

fn integer_register_pass_mode(size: usize) -> NativePassMode {
    if size <= 8 {
        NativePassMode::Registers(vec![NativeRegisterChunk {
            offset: 0,
            class: NativeRegisterClass::Integer {
                bits: (size * 8) as u16,
            },
        }])
    } else {
        NativePassMode::Indirect
    }
}

macro_rules! nonzero_abi {
    ($($type:ty => $inner:ty),* $(,)?) => {$(
        unsafe impl NativeAbi for $type {
            fn native_layout() -> &'static NativeTypeLayout {
                static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
                LAYOUT.get_or_init(|| NativeTypeLayout::structure::<$type>(vec![
                    NativeField::of::<$inner>(0, 0),
                ]))
            }

            fn native_pass_mode() -> NativePassMode {
                integer_register_pass_mode(Layout::new::<Self>().size())
            }
        }
    )*};
}

nonzero_abi!(
    NonZeroU8 => u8,
    NonZeroU16 => u16,
    NonZeroU32 => u32,
    NonZeroU64 => u64,
    NonZeroU128 => u128,
    NonZeroUsize => usize,
    NonZeroI8 => i8,
    NonZeroI16 => i16,
    NonZeroI32 => i32,
    NonZeroI64 => i64,
    NonZeroI128 => i128,
    NonZeroIsize => isize
);

macro_rules! option_nonzero_abi {
    ($($type:ty => $inner:ty),* $(,)?) => {$(
        unsafe impl NativeAbi for Option<$type> {
            fn native_layout() -> &'static NativeTypeLayout {
                static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
                LAYOUT.get_or_init(|| {
                    NativeTypeLayout::enum_type::<Option<$type>>(NativeEnumLayout::niche(
                        vec![
                            NativeEnumVariant::unit(0),
                            NativeEnumVariant::payload(1, <$type>::native_layout(), 0),
                        ],
                        0,
                        (Layout::new::<$inner>().size() * 8) as u16,
                        0,
                        0..=0,
                        1,
                    ))
                })
            }

            fn native_pass_mode() -> NativePassMode {
                integer_register_pass_mode(Layout::new::<Self>().size())
            }
        }
    )*};
}

option_nonzero_abi!(
    NonZeroU8 => u8,
    NonZeroU16 => u16,
    NonZeroU32 => u32,
    NonZeroU64 => u64,
    NonZeroUsize => usize,
    NonZeroI8 => i8,
    NonZeroI16 => i16,
    NonZeroI32 => i32,
    NonZeroI64 => i64,
    NonZeroIsize => isize
);

/// Checks both Rust identity and physical layout. This is done once while
/// linking a call site; the generated call itself needs no marshalling.
pub fn is_abi_compatible<T: NativeAbi>(expected: &NativeTypeLayout) -> bool {
    let actual = T::native_layout();
    actual.rust_type_id == expected.rust_type_id
        && actual.size == expected.size
        && actual.align == expected.align
        && actual.kind == expected.kind
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn box_and_non_zero_options_use_rust_zero_niches() {
        let boxed = Box::<u32>::native_layout();
        assert_eq!(boxed.size, std::mem::size_of::<Box<u32>>());
        assert_eq!(boxed.align, std::mem::align_of::<Box<u32>>());
        assert!(matches!(boxed.kind, NativeTypeKind::Structure { .. }));

        for layout in [
            Option::<Box<u32>>::native_layout(),
            Option::<NonZeroU32>::native_layout(),
        ] {
            assert_eq!(
                layout.size,
                match &layout.kind {
                    NativeTypeKind::Enum(enum_) => enum_
                        .variants
                        .iter()
                        .find_map(|variant| variant.payload.map(|payload| payload.size))
                        .unwrap(),
                    _ => panic!("niche option must be an enum"),
                }
            );
            assert!(matches!(
                &layout.kind,
                NativeTypeKind::Enum(NativeEnumLayout {
                    tag: NativeEnumTag::Niche {
                        niche_start: 0,
                        niche_variants,
                        data_variant: 1,
                        ..
                    },
                    ..
                }) if niche_variants == &(0..=0)
            ));
        }

        let non_zero = NonZeroU32::native_layout();
        assert_eq!((non_zero.size, non_zero.align), (4, 4));
        assert!(matches!(
            &non_zero.kind,
            NativeTypeKind::Structure { fields }
                if fields.len() == 1
                    && fields[0].offset == 0
                    && fields[0].layout.rust_type_id == TypeId::of::<u32>()
        ));
    }

    #[test]
    fn lehit_owned_values_are_transparent_byte_arrays() {
        let value = LehitValue::<4>::from_bytes([1, 2, 3, 4]);
        assert_eq!(value.as_bytes(), &[1, 2, 3, 4]);
        assert_eq!(value.into_bytes(), [1, 2, 3, 4]);
        assert_eq!(std::mem::size_of::<LehitValue<4>>(), 4);
        assert_eq!(std::mem::align_of::<LehitValue<4>>(), 1);
        let layout = LehitValue::<4>::native_layout();
        assert_eq!(layout.size, 4);
        assert_eq!(layout.align, 1);
        assert_eq!(layout.kind, NativeTypeKind::Bytes);
    }

    #[test]
    fn borrowing_a_lehit_value_borrows_the_same_bytes() {
        let value = LehitValue::<3>::from_bytes([7, 8, 9]);
        let borrowed: &[u8; 3] = value.as_bytes();
        assert!(std::ptr::eq(borrowed, value.as_bytes()));
    }
}