oxeon 0.0.3

Rust-like scripting language for modding Bevy games, compiled to sandboxed WebAssembly.
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
//! Runs a mod's systems: copies the data each system asks for into the
//! mod's memory, calls it, and copies back what it may change. Values go
//! through reflection, laid out as the compiler's [`Layout`]s say.

use std::collections::HashMap;

use bevy_ecs::change_detection::Tick;
use bevy_ecs::component::ComponentId;
use bevy_ecs::prelude::*;
use bevy_ecs::reflect::{AppTypeRegistry, ReflectComponent};
use bevy_reflect::structs::DynamicStruct;
use bevy_reflect::tuple_struct::DynamicTupleStruct;
use bevy_reflect::{PartialReflect, ReflectMut, ReflectRef, TypeInfo, TypeRegistry};
use bevy_time::Time;
use oxeon_compiler::{Layout, SystemInfo, SystemParam};
use oxeon_runtime::{HostCall, ModInstance, PROVISIONAL, Value};

use crate::bindings::OxeonBindings;
use crate::components::{ComponentRef, insert_bytes, read_bytes, write_bytes};
use crate::messages::{Cursor, MessageFnsMap, ModMessages};

/// A compiled, running mod.
pub(crate) struct LoadedMod {
    pub path: String,
    pub instance: ModInstance,
    pub systems: Vec<SystemInfo>,
    pub layouts: HashMap<String, Layout>,
    /// The component types the mod's commands refer to, by index.
    pub command_components: Vec<String>,
    /// When each system last ran, for `Changed` and `Added` filters.
    pub last_run: HashMap<String, Tick>,
    /// Each message reader's position in the game's messages, by system
    /// and parameter.
    pub cursors: HashMap<(String, usize), Cursor>,
    /// Each message reader's last seen mod message, by system and parameter.
    pub messages_seen: HashMap<(String, usize), u64>,
    /// Startup systems have run.
    pub started: bool,
    /// Disabled after a failure (a trap, running out of fuel, ...).
    pub failed: bool,
}

/// One column of a query row.
enum Column {
    Entity {
        offset: usize,
    },
    Component {
        component: ComponentRef,
        layout: Layout,
        mutable: bool,
        offset: usize,
    },
}

/// A mutable component (or resource) to copy back after the call, if the
/// system changed it.
struct WriteBack {
    entity: Entity,
    component: ComponentRef,
    offset: usize,
    layout: Layout,
    /// The bytes before the call: unchanged values aren't written back, so
    /// they aren't marked as changed.
    before: Vec<u8>,
}

fn align(buf: &mut Vec<u8>, to: usize) -> usize {
    let at = buf.len().div_ceil(to) * to;
    buf.resize(at, 0);
    at
}

pub(crate) fn run_system(
    world: &mut World,
    bindings: &OxeonBindings,
    m: &mut LoadedMod,
    system: &SystemInfo,
) -> Result<(), String> {
    let registry = world.resource::<AppTypeRegistry>().clone();
    let registry = registry.read();
    // The data goes where the module says (after its stack); pointers
    // passed to the system are relative to that.
    let base = m.instance.global_i32("oxeon_data_base").unwrap_or(0) as usize;
    let mut buf: Vec<u8> = Vec::new();
    let mut args = Vec::new();
    let mut write_backs = Vec::new();
    // Each run gets its own change tick, as Bevy systems do.
    world.increment_change_tick();
    let this_run = world.change_tick();
    let last_run = m
        .last_run
        .get(&system.name)
        .copied()
        .unwrap_or(Tick::new(0));

    for (index, param) in system.params.iter().enumerate() {
        match param {
            SystemParam::Res { ty, .. } if ty == "Time" => {
                let time = world
                    .get_resource::<Time>()
                    .ok_or("the game has no `Time` resource (add Bevy's `TimePlugin`)")?;
                let (delta, elapsed) = (time.delta_secs(), time.elapsed_secs());
                let layout = m
                    .layouts
                    .get("Time")
                    .ok_or("the mod has no `Time` layout")?;
                let at = align(&mut buf, 8);
                buf.resize(at + layout.size as usize, 0);
                for field in &layout.fields {
                    let value = match field.name.as_str() {
                        "delta" => delta,
                        "elapsed" => elapsed,
                        _ => 0.0,
                    };
                    let o = at + field.offset as usize;
                    buf[o..o + 4].copy_from_slice(&value.to_le_bytes());
                }
                args.push(Value::I32((base + at) as i32));
            }
            SystemParam::Res { ty, mutable } => {
                // Other resources are exposed like components: in Bevy, a
                // resource is a component on its own entity.
                let type_id = *bindings
                    .components
                    .get(ty)
                    .ok_or_else(|| format!("the resource `{ty}` isn't exposed to mods"))?;
                let rc = registry
                    .get_type_data::<ReflectComponent>(type_id)
                    .ok_or_else(|| format!("`{ty}` isn't reflected as a resource"))?;
                let entity = world
                    .components()
                    .get_id(type_id)
                    .and_then(|id| world.resource_entities().get(id))
                    .ok_or_else(|| format!("the game has no `{ty}` resource"))?;
                let layout = m
                    .layouts
                    .get(ty)
                    .ok_or_else(|| format!("no layout for `{ty}`"))?
                    .clone();
                let at = align(&mut buf, 8);
                buf.resize(at + layout.size as usize, 0);
                let value = rc
                    .reflect(world.entity(entity))
                    .ok_or_else(|| format!("the `{ty}` resource disappeared"))?;
                write_fields(
                    value.as_partial_reflect(),
                    &layout,
                    &mut buf[at..at + layout.size as usize],
                )?;
                if *mutable {
                    write_backs.push(WriteBack {
                        entity,
                        component: ComponentRef::Host {
                            type_id,
                            reflect: rc.clone(),
                            id: None,
                        },
                        offset: at,
                        before: buf[at..at + layout.size as usize].to_vec(),
                        layout,
                    });
                }
                args.push(Value::I32((base + at) as i32));
            }
            SystemParam::Messages { ty, row_size } => {
                let layout = m
                    .layouts
                    .get(ty)
                    .ok_or_else(|| format!("no layout for `{ty}`"))?
                    .clone();
                let key = (system.name.clone(), index);
                let size = layout.size as usize;
                // Each message as the mod lays it out.
                let messages: Vec<Vec<u8>> = if let Some(&type_id) = bindings.messages.get(ty) {
                    let fns = *world
                        .resource::<MessageFnsMap>()
                        .0
                        .get(&type_id)
                        .ok_or_else(|| format!("`{ty}` isn't exposed as a message"))?;
                    let cursor = m.cursors.entry(key).or_insert_with(fns.new_cursor);
                    let mut out = Vec::new();
                    for value in (fns.read)(world, cursor) {
                        let mut bytes = vec![0; size];
                        write_fields(value.as_ref(), &layout, &mut bytes)?;
                        out.push(bytes);
                    }
                    out
                } else {
                    let last = m.messages_seen.get(&key).copied().unwrap_or(0);
                    let (out, newest) = world
                        .get_resource_or_init::<ModMessages>()
                        .read_since(&ModMessages::key(ty, &layout), last);
                    m.messages_seen.insert(key, newest);
                    out
                };
                let rows = align(&mut buf, 8);
                let row_size = *row_size as usize;
                buf.resize(rows + row_size * messages.len(), 0);
                for (i, bytes) in messages.iter().enumerate() {
                    let at = rows + i * row_size;
                    buf[at..at + size].copy_from_slice(bytes);
                }
                args.push(Value::I32((base + rows) as i32));
                args.push(Value::I32(messages.len() as i32));
            }
            SystemParam::Commands | SystemParam::MessageWriter { .. } => {
                // Commands and messages go through the `oxeon` imports; the
                // parameter itself is a placeholder.
                let at = align(&mut buf, 8);
                buf.resize(at + 8, 0);
                args.push(Value::I32((base + at) as i32));
            }
            SystemParam::Query {
                row_size,
                components,
                with,
                without,
                changed,
                added,
            } => {
                let mod_path = m.path.clone();
                let resolve = |world: &mut World, name: &String| {
                    ComponentRef::resolve(world, &registry, bindings, &mod_path, &m.layouts, name)
                };
                let mut parts = Vec::new();
                for c in components {
                    let offset = c.offset as usize;
                    if c.ty == "Entity" {
                        parts.push(Column::Entity { offset });
                        continue;
                    }
                    let component = resolve(world, &c.ty)?;
                    let layout = m
                        .layouts
                        .get(&c.ty)
                        .ok_or_else(|| format!("no layout for `{}`", c.ty))?
                        .clone();
                    parts.push(Column::Component {
                        component,
                        layout,
                        mutable: c.mutable,
                        offset,
                    });
                }
                let resolve_all =
                    |world: &mut World, names: &Vec<String>| -> Result<Vec<ComponentRef>, String> {
                        names.iter().map(|n| resolve(world, n)).collect()
                    };
                let with = resolve_all(world, with)?;
                let without = resolve_all(world, without)?;
                // `Changed<T>` / `Added<T>`: compared with this system's last run.
                let ids = |refs: Vec<ComponentRef>,
                           names: &Vec<String>|
                 -> Result<Vec<ComponentId>, String> {
                    refs.iter()
                        .zip(names)
                        .map(|(r, n)| {
                            r.id()
                                .ok_or_else(|| format!("`{n}` isn't a registered component"))
                        })
                        .collect()
                };
                let changed = ids(resolve_all(world, changed)?, changed)?;
                let added = ids(resolve_all(world, added)?, added)?;
                let mut all = world.query::<Entity>();
                let entities: Vec<Entity> = all
                    .iter(world)
                    .filter(|e| {
                        let e = world.entity(*e);
                        let ticks = |id: &ComponentId| e.get_change_ticks_by_id(*id);
                        parts.iter().all(|p| match p {
                            Column::Entity { .. } => true,
                            Column::Component { component, .. } => component.contains(e),
                        }) && with.iter().all(|c| c.contains(e))
                            && !without.iter().any(|c| c.contains(e))
                            && changed.iter().all(|id| {
                                ticks(id).is_some_and(|t| t.is_changed(last_run, this_run))
                            })
                            && added
                                .iter()
                                .all(|id| ticks(id).is_some_and(|t| t.is_added(last_run, this_run)))
                    })
                    .collect();
                let rows = align(&mut buf, 8);
                let row_size = *row_size as usize;
                buf.resize(rows + row_size * entities.len(), 0);
                for (i, entity) in entities.iter().enumerate() {
                    for part in &parts {
                        match part {
                            Column::Entity { offset } => {
                                let at = rows + i * row_size + offset;
                                buf[at..at + 8].copy_from_slice(&entity.to_bits().to_le_bytes());
                            }
                            Column::Component {
                                component,
                                layout,
                                mutable,
                                offset,
                            } => {
                                let at = rows + i * row_size + offset;
                                let size = layout.size as usize;
                                match component {
                                    ComponentRef::Host { reflect, .. } => {
                                        let value = reflect
                                            .reflect(world.entity(*entity))
                                            .ok_or("a component disappeared")?;
                                        write_fields(
                                            value.as_partial_reflect(),
                                            layout,
                                            &mut buf[at..at + size],
                                        )?;
                                    }
                                    ComponentRef::Mod { id, size } => {
                                        let bytes = read_bytes(world, *entity, *id, *size)
                                            .ok_or("a component disappeared")?;
                                        buf[at..at + size].copy_from_slice(&bytes);
                                    }
                                }
                                if *mutable {
                                    write_backs.push(WriteBack {
                                        entity: *entity,
                                        component: component.clone(),
                                        offset: at,
                                        layout: layout.clone(),
                                        before: buf[at..at + size].to_vec(),
                                    });
                                }
                            }
                        }
                    }
                }
                args.push(Value::I32((base + rows) as i32));
                args.push(Value::I32(entities.len() as i32));
            }
        }
    }

    let instance = &mut m.instance;
    if !buf.is_empty() {
        instance
            .write_memory(base, &buf)
            .map_err(|e| e.to_string())?;
    }
    instance.refuel().map_err(|e| e.to_string())?;
    // Commands left over from a call that failed are never applied.
    instance.take_host_calls();
    instance
        .call(&system.name, &args)
        .map_err(|e| e.to_string())?;

    for wb in write_backs {
        let bytes = instance
            .read_memory(base + wb.offset, wb.layout.size as usize)
            .map_err(|e| e.to_string())?;
        if bytes == wb.before {
            continue;
        }
        match &wb.component {
            ComponentRef::Host { reflect, .. } => {
                let mut entity = world.entity_mut(wb.entity);
                let mut value = reflect
                    .reflect_mut(&mut entity)
                    .ok_or("a component disappeared")?;
                read_fields(value.as_partial_reflect_mut(), &wb.layout, &bytes)?;
            }
            ComponentRef::Mod { id, .. } => {
                if !write_bytes(world, wb.entity, *id, &bytes) {
                    return Err("a component disappeared".to_owned());
                }
            }
        }
    }
    let calls = instance.take_host_calls();
    apply_commands(world, &registry, bindings, m, calls)?;
    m.last_run.insert(system.name.clone(), this_run);
    Ok(())
}

/// Applies a system's commands in order, after it returned. Entities it
/// spawned are known by provisional ids until now.
fn apply_commands(
    world: &mut World,
    registry: &TypeRegistry,
    bindings: &OxeonBindings,
    m: &LoadedMod,
    calls: Vec<HostCall>,
) -> Result<(), String> {
    let mut spawned: HashMap<u64, Entity> = HashMap::new();
    let resolve = |bits: u64, spawned: &HashMap<u64, Entity>, world: &World| -> Option<Entity> {
        let entity = if bits & PROVISIONAL != 0 {
            *spawned.get(&bits)?
        } else {
            Entity::try_from_bits(bits)?
        };
        world.get_entity(entity).is_ok().then_some(entity)
    };
    for call in calls {
        match call {
            HostCall::Spawn(id) => {
                let entity = world.spawn_empty().id();
                spawned.insert(id, entity);
            }
            HostCall::Insert {
                entity,
                component,
                bytes,
            } => {
                let name = m
                    .command_components
                    .get(component as usize)
                    .ok_or("a command names an unknown component")?;
                let layout = m
                    .layouts
                    .get(name)
                    .ok_or_else(|| format!("no layout for `{name}`"))?;
                let component =
                    ComponentRef::resolve(world, registry, bindings, &m.path, &m.layouts, name)?;
                // A command for an entity that's gone does nothing, as in Bevy.
                let Some(e) = resolve(entity, &spawned, world) else {
                    continue;
                };
                match component {
                    ComponentRef::Host {
                        type_id, reflect, ..
                    } => {
                        let registration = registry
                            .get(type_id)
                            .ok_or_else(|| format!("`{name}` isn't registered"))?;
                        let value = component_value(registration.type_info(), layout, &bytes)?;
                        reflect.insert(
                            &mut world.entity_mut(e),
                            value.as_partial_reflect(),
                            registry,
                        );
                    }
                    ComponentRef::Mod { id, .. } => insert_bytes(world, e, id, &bytes),
                }
            }
            HostCall::Write { ty, bytes } => {
                let name = m
                    .command_components
                    .get(ty as usize)
                    .ok_or("a message of an unknown type")?;
                let layout = m
                    .layouts
                    .get(name)
                    .ok_or_else(|| format!("no layout for `{name}`"))?;
                match bindings.messages.get(name) {
                    Some(&type_id) => {
                        let fns = *world
                            .resource::<MessageFnsMap>()
                            .0
                            .get(&type_id)
                            .ok_or_else(|| format!("`{name}` isn't exposed as a message"))?;
                        let registration = registry
                            .get(type_id)
                            .ok_or_else(|| format!("`{name}` isn't registered"))?;
                        let value = component_value(registration.type_info(), layout, &bytes)?;
                        if !(fns.write)(world, value.as_partial_reflect()) {
                            return Err(format!("couldn't build a `{name}` message"));
                        }
                    }
                    None => world
                        .get_resource_or_init::<ModMessages>()
                        .write(ModMessages::key(name, layout), bytes),
                }
            }
            HostCall::Despawn(bits) => {
                if let Some(e) = resolve(bits, &spawned, world) {
                    world.despawn(e);
                }
            }
        }
    }
    Ok(())
}

/// Builds a component from the bytes a mod wrote, laid out as `layout`.
fn component_value(
    info: &'static TypeInfo,
    layout: &Layout,
    bytes: &[u8],
) -> Result<Box<dyn PartialReflect>, String> {
    let field = |f: &oxeon_compiler::FieldLayout| -> Result<Box<dyn PartialReflect>, String> {
        let o = f.offset as usize;
        macro_rules! get {
            ($t:ty) => {{
                let size = std::mem::size_of::<$t>();
                let b = bytes.get(o..o + size).ok_or("a component is cut short")?;
                Box::new(<$t>::from_le_bytes(b.try_into().expect("sized slice")))
            }};
        }
        Ok(match f.ty.as_str() {
            "f32" => get!(f32),
            "f64" => get!(f64),
            "i8" => get!(i8),
            "i16" => get!(i16),
            "i32" => get!(i32),
            "i64" => get!(i64),
            "u8" => get!(u8),
            "u16" => get!(u16),
            "u32" => get!(u32),
            "u64" => get!(u64),
            "usize" => Box::new(u32::from_le_bytes(
                bytes
                    .get(o..o + 4)
                    .ok_or("a component is cut short")?
                    .try_into()
                    .expect("sized"),
            ) as usize),
            "isize" => Box::new(i32::from_le_bytes(
                bytes
                    .get(o..o + 4)
                    .ok_or("a component is cut short")?
                    .try_into()
                    .expect("sized"),
            ) as isize),
            "bool" => Box::new(*bytes.get(o).ok_or("a component is cut short")? != 0),
            "char" => Box::new(
                char::from_u32(u32::from_le_bytes(
                    bytes
                        .get(o..o + 4)
                        .ok_or("a component is cut short")?
                        .try_into()
                        .expect("sized"),
                ))
                .ok_or("invalid char")?,
            ),
            other => return Err(format!("can't build a `{other}` field")),
        })
    };
    match info {
        TypeInfo::Struct(_) => {
            let mut value = DynamicStruct::default();
            for f in &layout.fields {
                value.insert_boxed(f.name.clone(), field(f)?);
            }
            value.set_represented_type(Some(info));
            Ok(Box::new(value))
        }
        TypeInfo::TupleStruct(_) => {
            let mut value = DynamicTupleStruct::default();
            for f in &layout.fields {
                value.insert_boxed(field(f)?);
            }
            value.set_represented_type(Some(info));
            Ok(Box::new(value))
        }
        _ => Err(format!("`{}` isn't a struct", layout.name)),
    }
}

fn field<'a>(value: &'a dyn PartialReflect, name: &str) -> Option<&'a dyn PartialReflect> {
    match value.reflect_ref() {
        ReflectRef::Struct(s) => s.field(name),
        ReflectRef::TupleStruct(t) => t.field(name.parse().ok()?),
        _ => None,
    }
}

fn field_mut<'a>(
    value: &'a mut dyn PartialReflect,
    name: &str,
) -> Option<&'a mut dyn PartialReflect> {
    match value.reflect_mut() {
        ReflectMut::Struct(s) => s.field_mut(name),
        ReflectMut::TupleStruct(t) => t.field_mut(name.parse().ok()?),
        _ => None,
    }
}

/// Serializes a component's fields into `out`, at the layout's offsets.
fn write_fields(value: &dyn PartialReflect, layout: &Layout, out: &mut [u8]) -> Result<(), String> {
    for f in &layout.fields {
        let v = field(value, &f.name)
            .ok_or_else(|| format!("`{}` has no field `{}`", layout.name, f.name))?;
        let o = f.offset as usize;
        macro_rules! put {
            ($t:ty) => {{
                let x = v
                    .try_downcast_ref::<$t>()
                    .ok_or_else(|| format!("`{}.{}` isn't a `{}`", layout.name, f.name, f.ty))?;
                let bytes = x.to_le_bytes();
                out[o..o + bytes.len()].copy_from_slice(&bytes);
            }};
        }
        match f.ty.as_str() {
            "f32" => put!(f32),
            "f64" => put!(f64),
            "i8" => put!(i8),
            "i16" => put!(i16),
            "i32" => put!(i32),
            "i64" => put!(i64),
            "u8" => put!(u8),
            "u16" => put!(u16),
            "u32" => put!(u32),
            "u64" => put!(u64),
            // 32-bit in WebAssembly.
            "usize" => {
                let x = v.try_downcast_ref::<usize>().ok_or("not a usize")?;
                out[o..o + 4].copy_from_slice(&(*x as u32).to_le_bytes());
            }
            "isize" => {
                let x = v.try_downcast_ref::<isize>().ok_or("not an isize")?;
                out[o..o + 4].copy_from_slice(&(*x as i32).to_le_bytes());
            }
            "bool" => out[o] = u8::from(*v.try_downcast_ref::<bool>().ok_or("not a bool")?),
            "char" => {
                let c = v.try_downcast_ref::<char>().ok_or("not a char")?;
                out[o..o + 4].copy_from_slice(&(*c as u32).to_le_bytes());
            }
            other => return Err(format!("can't copy a `{other}` into a mod")),
        }
    }
    Ok(())
}

/// Updates a component's fields from the mod's memory.
fn read_fields(
    value: &mut dyn PartialReflect,
    layout: &Layout,
    bytes: &[u8],
) -> Result<(), String> {
    for f in &layout.fields {
        let name = layout.name.clone();
        let v = field_mut(value, &f.name)
            .ok_or_else(|| format!("`{name}` has no field `{}`", f.name))?;
        let o = f.offset as usize;
        macro_rules! get {
            ($t:ty) => {{
                let size = std::mem::size_of::<$t>();
                let x = <$t>::from_le_bytes(bytes[o..o + size].try_into().expect("sized slice"));
                *v.try_downcast_mut::<$t>()
                    .ok_or_else(|| format!("`{name}.{}` isn't a `{}`", f.name, f.ty))? = x;
            }};
        }
        match f.ty.as_str() {
            "f32" => get!(f32),
            "f64" => get!(f64),
            "i8" => get!(i8),
            "i16" => get!(i16),
            "i32" => get!(i32),
            "i64" => get!(i64),
            "u8" => get!(u8),
            "u16" => get!(u16),
            "u32" => get!(u32),
            "u64" => get!(u64),
            "usize" => {
                let x = u32::from_le_bytes(bytes[o..o + 4].try_into().expect("sized slice"));
                *v.try_downcast_mut::<usize>().ok_or("not a usize")? = x as usize;
            }
            "isize" => {
                let x = i32::from_le_bytes(bytes[o..o + 4].try_into().expect("sized slice"));
                *v.try_downcast_mut::<isize>().ok_or("not an isize")? = x as isize;
            }
            "bool" => *v.try_downcast_mut::<bool>().ok_or("not a bool")? = bytes[o] != 0,
            "char" => {
                let x = u32::from_le_bytes(bytes[o..o + 4].try_into().expect("sized slice"));
                *v.try_downcast_mut::<char>().ok_or("not a char")? =
                    char::from_u32(x).ok_or("invalid char")?;
            }
            other => return Err(format!("can't copy a `{other}` out of a mod")),
        }
    }
    Ok(())
}