xur-runtime 0.1.7

Values, native-function registry and facet conversions for the Xur language
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! Registering Rust functions and types as Xur modules.
//!
//! ```ignore
//! let mut registry = Registry::new();
//! registry
//!     .module("std::math")
//!     .function("sqrt", |x: f64| x.sqrt())
//!     .function("max", |a: i64, b: i64| a.max(b));
//! registry
//!     .module("geo")
//!     .ty::<Point>("Point")
//!     .function("new", |x: f64, y: f64| Point { x, y }) // `Point::new(1.0, 2.0)`
//!     .method("norm", |p: &Point| p.x.hypot(p.y)) //     `p.norm()`
//!     .method_mut("scale", |p: &mut Point, k: f64| { p.x *= k; p.y *= k });
//! ```
//!
//! Any `Fn(A, B, ...) -> R` whose argument and return types implement
//! [`Facet`] can be registered: arguments are converted from Xur values and
//! the result back with [`convert`](crate::convert). Functions that need the
//! running program itself, such as `std::import`, are registered with
//! [`ModuleBuilder::raw_function`] and receive a [`Context`].
//!
//! Values of a registered type live in Xur as [`Value::Native`]: the Rust
//! value itself, shared, so methods taking `&mut self` change it in place.
//! Its fields can be read (`p.x`) and it is displayed with its `Display` or
//! `Debug` implementation.

mod builder;
mod hooks;
mod into_native;
#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread::JoinHandle;

use facet::{Def, Facet, Peek, Shape, StructKind, StructType, Type, UserType};
use xur_resolve::{
    DefId, NativeFnDecl, NativeFnId, NativeModule, NativeProvider, NativeTypeDecl, NativeTypeId,
    NativeVariantDecl, NativeVariantKind, RtType, macros::MacroExpander,
};

use xur_span::{Span, Symbol};

use crate::convert::{Builder, ConvertCx};
use crate::value::NativeObject;
use crate::{AdtInfo, BuiltinType, RunResult, RuntimeError, TypeDesc, TypeRef, Value};

pub use builder::{
    BuiltinBuilder, ElemHint, ModuleBuilder, ReturnHint, Returns, TypeBuilder, XurType,
};
pub use into_native::{
    BuiltinRecv, BuiltinRecvMut, IntoBuiltinMethod, IntoBuiltinMethodMut, IntoNativeFn,
    IntoNativeMethod, IntoNativeMethodMut,
};

use hooks::TypeHooks;

/// What a native function can ask of the running program.
pub trait Context: ConvertCx {
    /// Loads the module at `path`, relative to the file of the module
    /// making the call, and returns it as a value.
    fn import(&mut self, path: &str) -> RunResult<Value>;
    /// Formats `value` as `{}` does in format strings.
    fn display(&self, value: &Value) -> String;
    /// The generic arguments the native function was called with, as in
    /// `type_name::<T>()`.
    fn type_args(&self) -> &[TypeRef];
    /// Writes `text` to the program's standard output.
    fn print(&mut self, text: &str) -> RunResult<()>;
    /// Writes `text` to the program's standard error. By default this is the
    /// process's stderr; embedders can redirect it.
    fn eprint(&mut self, text: &str) -> RunResult<()> {
        use std::io::Write;
        std::io::stderr()
            .write_all(text.as_bytes())
            .map_err(|error| RuntimeError::new(format!("couldn't write to stderr: {error}")))
    }
    /// Calls a function, closure or constructor value.
    fn call(&mut self, callee: &Value, args: &[Value]) -> RunResult<Value>;
    /// Calls `f`, a function or closure taking no arguments, on a new
    /// thread; joining the thread gives its result.
    fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;

    // Reflection, for `std::reflect`.

    /// How the type of `value` is named in messages, e.g. `` `Point` ``.
    fn describe_type(&self, value: &Value) -> String;
    /// A `file:line:col` location for `span`, for reporting errors raised inside
    /// a native callback (e.g. an egui draw function) where the span would
    /// otherwise be lost. Returns an empty string if it can't be resolved.
    fn describe_span(&self, span: Span) -> String;
    /// The runtime type of `value` as a type value, preserving int/float width
    /// (`reflect::type_of`).
    fn type_of(&self, value: &Value) -> RtType;
    /// The struct or enum variant `def`, or `None` if it is neither.
    fn adt_info(&self, def: DefId) -> Option<AdtInfo>;
    /// The names of the methods `value.name()` can call.
    fn methods(&self, value: &Value) -> Vec<String>;
    /// `value.name`.
    fn field(&mut self, value: &Value, name: &str) -> RunResult<Value>;
    /// A copy of the struct `value` with the field `name` set to `new`.
    fn set_field(&mut self, value: &Value, name: &str, new: Value) -> RunResult<Value>;
    /// `receiver.name(args)`.
    fn call_method(&mut self, receiver: Value, name: &str, args: &[Value]) -> RunResult<Value>;

    /// Attempts to coerce `value` into the struct or enum `target`, as
    /// `value as Type` does. Returns the coerced value, or an error if the
    /// coercion fails.
    fn try_cast(&self, value: &Value, target: DefId) -> RunResult<Value>;

    /// The integer repr value of a repr enum variant, if `def` is one.
    fn repr_value(&self, def: DefId) -> Option<i64>;

    /// Reflection data for a function, closure, or constructor value.
    fn fn_info(&self, value: &Value) -> Option<crate::FnInfo>;

    /// An opaque handle for calling xur closures from outside the normal
    /// execution path, such as from native hook callbacks. Returns `None`
    /// if the engine doesn't support it.
    fn shared_handle(&self) -> Option<Box<dyn std::any::Any + Send + Sync>> {
        None
    }

    /// The name of a definition: the variant name for an enum variant,
    /// the type name for a struct or enum.
    fn def_name(&self, _def: DefId) -> Option<String> {
        None
    }

    /// The variants of the enum `def`: `(name, variant_def, has_fields)`.
    fn enum_variants(&self, _def: DefId) -> Vec<(String, DefId, bool)> {
        Vec::new()
    }
}

pub(crate) type CallFn = dyn Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync;

/// The Rust types of a typed native function, for checking calls.
#[derive(Debug, Clone)]
pub struct Signature {
    pub params: Vec<&'static Shape>,
    pub ret: &'static Shape,
    pub param_names: Vec<String>,
    /// The parameters' types for display, one per entry in `params`.
    pub param_types: Vec<TypeDesc>,
    /// The return type for display.
    pub ret_type: TypeDesc,
    /// How many leading parameters are required; the rest are optional.
    pub required: usize,
}

pub struct NativeFn {
    pub name: String,
    /// `None` for raw functions, which take any arguments.
    pub signature: Option<Signature>,
    /// Return type for raw functions that lack a full signature.
    pub return_hint: Option<ReturnHint>,
    pub param_names: Vec<String>,
    call: Box<CallFn>,
}

impl NativeFn {
    pub fn call(&self, cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
        (self.call)(cx, args)
    }
}

pub(super) struct NativeType {
    name: String,
    shape: &'static Shape,
    functions: Vec<NativeFnDecl>,
    /// `None` for types registered by shape only, whose values are
    /// records rather than native objects.
    hooks: Option<TypeHooks>,
    /// Explicit variant declarations for repr enums registered from Rust.
    /// When set, these are used instead of deriving variants from the shape.
    explicit_variants: Option<Vec<NativeVariantDecl>>,
}

/// Fills in a lazy module, the first time a program uses it.
type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;

struct ModuleData {
    name: String,
    /// For a lazy module not yet needed, what registers its contents.
    init: Option<ModuleInit>,
    children: Vec<usize>,
    functions: Vec<NativeFnDecl>,
    types: Vec<NativeTypeId>,
    macros: HashMap<String, Arc<dyn MacroExpander>>,
}

/// Every native function and type, organised into modules.
///
/// A registry is shared by every thread of a running program and by name
/// resolution, which may expand lazy modules while a native function runs,
/// so it is internally locked: each operation holds the lock only briefly,
/// and functions are handed out as `Arc`s to call without it.
#[derive(Default)]
pub struct Registry {
    inner: RwLock<Inner>,
}

#[derive(Default)]
struct Inner {
    fns: Vec<Arc<NativeFn>>,
    /// Methods of built-in values, such as `list.push`.
    builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
    types: Vec<NativeType>,
    modules: Vec<ModuleData>,
    /// Modules that are not submodules of another, like `std`.
    roots: Vec<usize>,
    /// Conversions to Xur for shapes facet cannot see inside.
    converters: Vec<(&'static Shape, Converter)>,
}

/// The fields a record of a type registered by shape is built with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecordCtor {
    pub kind: NativeVariantKind,
    /// In declaration order; `0`, `1`, ... for tuple fields.
    pub fields: Vec<Symbol>,
}

/// The variants of an enum's shape, as resolution declares them.
fn variant_decls(shape: &'static Shape) -> Vec<NativeVariantDecl> {
    let Type::User(UserType::Enum(en)) = shape.ty else {
        return Vec::new();
    };
    en.variants
        .iter()
        .map(|variant| NativeVariantDecl {
            name: variant.name.to_owned(),
            kind: variant_kind(variant.data.kind),
            repr_value: None,
        })
        .collect()
}

fn variant_kind(kind: StructKind) -> NativeVariantKind {
    match kind {
        StructKind::Unit => NativeVariantKind::Unit,
        StructKind::Tuple | StructKind::TupleStruct => NativeVariantKind::Tuple,
        StructKind::Struct => NativeVariantKind::Named,
    }
}

/// Converts a value of some shape to Xur, given a peek at it.
pub type Converter = fn(&dyn ConvertCx, Peek<'_, 'static>) -> RunResult<Value>;

impl Registry {
    pub fn new() -> Self {
        Self::default()
    }

    fn read(&self) -> RwLockReadGuard<'_, Inner> {
        self.inner.read().unwrap_or_else(PoisonError::into_inner)
    }

    fn write(&self) -> RwLockWriteGuard<'_, Inner> {
        self.inner.write().unwrap_or_else(PoisonError::into_inner)
    }

    /// The module at `path`, such as `std::io`, created if needed.
    pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
        let module = self.write().module_at(path);
        ModuleBuilder::new(self, module)
    }

    /// Registers the module at `path` lazily: `init` registers its contents
    /// the first time a program looks inside it, so large modules that a
    /// program doesn't use cost nothing.
    pub fn lazy_module(
        &self,
        path: &str,
        init: impl FnOnce(&mut ModuleBuilder<'_>) + Send + Sync + 'static,
    ) {
        let mut inner = self.write();
        let module = inner.module_at(path);
        inner.modules[module].init = Some(Box::new(init));
    }

    /// Methods of the built-in type `ty`, such as `list.push(x)`.
    pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
        BuiltinBuilder::new(self, ty)
    }

    /// The method `name` of the built-in type `ty`.
    pub fn builtin_method(&self, ty: BuiltinType, name: &str) -> Option<NativeFnId> {
        self.read()
            .builtin_methods
            .get(&(ty, name.to_owned()))
            .copied()
    }

    /// The function `name` registered for the native type `ty`.
    pub fn type_function(&self, ty: NativeTypeId, name: &str) -> Option<NativeFnId> {
        let inner = self.read();
        let functions = &inner.types[ty.0 as usize].functions;
        functions.iter().find(|f| f.name == name).map(|f| f.id)
    }

    /// The functions of the native type `ty` that can be called as methods:
    /// those whose first parameter is the type itself, and raw functions.
    pub fn type_methods(&self, ty: NativeTypeId) -> Vec<String> {
        let inner = self.read();
        let native = &inner.types[ty.0 as usize];
        native
            .functions
            .iter()
            .filter(|decl| match &inner.fns[decl.id.0 as usize].signature {
                Some(signature) => signature.params.first() == Some(&native.shape),
                None => true,
            })
            .map(|decl| decl.name.clone())
            .collect()
    }

    /// The names of the methods of the built-in type `ty`, sorted.
    pub fn builtin_methods(&self, ty: BuiltinType) -> Vec<String> {
        let mut names: Vec<_> = self
            .read()
            .builtin_methods
            .keys()
            .filter(|(builtin, _)| *builtin == ty)
            .map(|(_, name)| name.clone())
            .collect();
        names.sort();
        names
    }

    /// The names of the fields of the native type `ty`, if it is a struct.
    pub fn type_fields(&self, ty: NativeTypeId) -> Vec<String> {
        let shape = self.read().types[ty.0 as usize].shape;
        match shape.ty {
            Type::User(UserType::Struct(StructType { fields, .. })) => {
                fields.iter().map(|field| field.name.to_owned()).collect()
            }
            _ => Vec::new(),
        }
    }

    pub fn function(&self, id: NativeFnId) -> Arc<NativeFn> {
        Arc::clone(&self.read().fns[id.0 as usize])
    }

    pub fn type_name(&self, id: NativeTypeId) -> String {
        self.read().types[id.0 as usize].name.clone()
    }

    /// The Rust shape `id` was registered with: its fields, variants and
    /// the doc comments on all of them (`shape.doc`, `field.doc`), for
    /// generated docs.
    pub fn type_shape(&self, id: NativeTypeId) -> &'static Shape {
        self.read().types[id.0 as usize].shape
    }

    /// The native type registered under `name`, if any.
    pub fn type_id_by_name(&self, name: &str) -> Option<NativeTypeId> {
        let inner = self.read();
        inner
            .types
            .iter()
            .enumerate()
            .find_map(|(i, ty)| (ty.name == name).then_some(NativeTypeId(i as u32)))
    }

    /// The xur display name for `shape`, mapping Rust types to their xur
    /// equivalents: `String` → `str`, `Vec<u8>` → `bytes`, `Vec<T>` →
    /// `list<T>`, `Option`/`Result` with their type arguments, registered
    /// types by their xur name, and falling back to the Rust name.
    pub fn shape_xur_name(&self, shape: &'static Shape) -> String {
        if let Some(id) = self.type_of_shape(shape) {
            return self.type_name(id);
        }
        let elem = |t: &'static Shape, wrap: &str| {
            if t == u8::SHAPE {
                "bytes".to_string()
            } else {
                format!("{wrap}<{}>", self.shape_xur_name(t))
            }
        };
        match shape.def {
            Def::Option(o) => return format!("Option<{}>", self.shape_xur_name(o.t())),
            Def::Result(r) => {
                return format!(
                    "Result<{}, {}>",
                    self.shape_xur_name(r.t()),
                    self.shape_xur_name(r.e())
                );
            }
            Def::List(l) => return elem(l.t(), "list"),
            Def::Array(a) => return elem(a.t(), "list"),
            Def::Slice(sl) => return elem(sl.t(), "list"),
            Def::Set(set) => return format!("list<{}>", self.shape_xur_name(set.t())),
            Def::Map(m) => {
                return format!(
                    "map<{}, {}>",
                    self.shape_xur_name(m.k()),
                    self.shape_xur_name(m.v())
                );
            }
            _ => {}
        }
        let name = shape.type_name().to_string();
        match name.as_str() {
            "String" | "&str" | "str" | "alloc::string::String" | "Arc<str>" => "str".into(),
            _ => name.split('<').next().unwrap_or(&name).into(),
        }
    }

    /// The display name of a [`TypeDesc`].
    pub fn type_desc_name(&self, desc: &TypeDesc) -> String {
        match desc {
            TypeDesc::Shape(shape) => self.shape_xur_name(shape),
            TypeDesc::Name(name) => (*name).into(),
            TypeDesc::Generic(name, args) => {
                let args: Vec<_> = args.iter().map(|a| self.type_desc_name(a)).collect();
                format!("{name}<{}>", args.join(", "))
            }
            TypeDesc::Union(options) => {
                let options: Vec<_> = options.iter().map(|a| self.type_desc_name(a)).collect();
                options.join(" | ")
            }
            TypeDesc::Unknown => "_".into(),
        }
    }

    /// The return-type Shape of a native function (from its typed signature
    /// or a [`ReturnHint::Shape`] hint). Returns `None` for raw functions
    /// with no hint or an [`XurType`] hint.
    pub fn native_return_shape(&self, id: NativeFnId) -> Option<&'static Shape> {
        let f = self.function(id);
        if let Some(sig) = &f.signature {
            return Some(sig.ret);
        }
        match f.return_hint {
            Some(ReturnHint::Shape(s)) => Some(s),
            _ => None,
        }
    }

    /// The xur type name of a native function's return type, if known.
    pub fn native_return_name(&self, id: NativeFnId) -> Option<String> {
        let f = self.function(id);
        if let Some(sig) = &f.signature {
            return Some(self.type_desc_name(&sig.ret_type));
        }
        match f.return_hint {
            Some(ReturnHint::Shape(s)) => Some(self.shape_xur_name(s)),
            Some(ReturnHint::Xur(xur)) => Some(self.xur_type_name(xur)),
            None => None,
        }
    }

    fn xur_type_name(&self, ty: XurType) -> String {
        match ty {
            XurType::Ptr(Some(inner)) => format!("*{}", self.shape_xur_name(inner)),
            XurType::Ptr(None) => "ptr".into(),
            XurType::List(None) => "list".into(),
            XurType::List(Some(hint)) => format!("list<{}>", self.elem_hint_name(hint)),
            XurType::Map(None, None) => "map".into(),
            XurType::Map(Some(k), Some(v)) => {
                format!(
                    "map<{}, {}>",
                    self.shape_xur_name(k),
                    self.shape_xur_name(v)
                )
            }
            XurType::Map(Some(k), None) => format!("map<{}, _>", self.shape_xur_name(k)),
            XurType::Map(None, Some(v)) => format!("map<_, {}>", self.shape_xur_name(v)),
            XurType::Named(name, []) => (*name).into(),
            XurType::Named(name, params) => {
                let args: Vec<_> = params.iter().map(|h| self.elem_hint_name(*h)).collect();
                format!("{name}<{}>", args.join(", "))
            }
            XurType::Record => "record".into(),
            XurType::Module => "module".into(),
            XurType::Unit => "()".into(),
        }
    }

    /// Sets the return-type hint on a raw function registered without a
    fn elem_hint_name(&self, hint: ElemHint) -> String {
        match hint {
            ElemHint::Shape(s) => self.shape_xur_name(s),
            ElemHint::Name(n) => n.into(),
            ElemHint::Param(n) => format!("T{n}"),
        }
    }

    /// full signature, for LSP inlay hints.
    pub(super) fn set_return_hint(&self, id: NativeFnId, hint: ReturnHint) {
        let mut inner = self.write();
        let slot = &mut inner.fns[id.0 as usize];
        Arc::get_mut(slot)
            .expect("return hint set during registration")
            .return_hint = Some(hint);
    }

    /// Extract the xur name of the `index`th type parameter from a generic
    /// Shape: for `Result<T, E>`, index 0 → T, index 1 → E; for `Option<T>`,
    /// index 0 → T.
    pub fn shape_type_param(&self, shape: &'static Shape, index: usize) -> Option<String> {
        if let Ok(r) = shape.def.into_result() {
            return match index {
                0 => Some(self.shape_xur_name(r.t())),
                1 => Some(self.shape_xur_name(r.e())),
                _ => None,
            };
        }
        if let Ok(o) = shape.def.into_option() {
            return (index == 0).then(|| self.shape_xur_name(o.t()));
        }
        None
    }

    /// The native type registered for `shape`, if any.
    pub fn type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
        let index = self
            .read()
            .types
            .iter()
            .position(|ty| ty.shape == shape && ty.hooks.is_some())?;
        Some(NativeTypeId(index as u32))
    }

    /// The type registered by shape only for `shape`, whose values are
    /// typed records.
    pub fn record_type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
        let index = self
            .read()
            .types
            .iter()
            .position(|ty| ty.shape == shape && ty.hooks.is_none())?;
        Some(NativeTypeId(index as u32))
    }

    /// Converts values of `shape` to Xur with `convert`, for types facet
    /// cannot see inside, such as opaque ones. Such values cannot be
    /// converted back.
    pub fn converter(&self, shape: &'static Shape, convert: Converter) {
        self.write().converters.push((shape, convert));
    }

    /// Whether a conversion is registered for `shape`.
    pub fn has_converter(&self, shape: &'static Shape) -> bool {
        self.converter_of(shape).is_some()
    }

    /// The conversion registered for `shape`, if any.
    pub(crate) fn converter_of(&self, shape: &'static Shape) -> Option<Converter> {
        let inner = self.read();
        let (_, convert) = inner.converters.iter().find(|(s, _)| *s == shape)?;
        Some(*convert)
    }

    /// How a value of the type `ty`, registered by shape, is built: the
    /// fields of the struct itself, or of its enum variant `variant`.
    /// `None` if there is no such struct or variant.
    pub fn record_ctor(&self, ty: NativeTypeId, variant: Option<Symbol>) -> Option<RecordCtor> {
        let shape = self.read().types[ty.0 as usize].shape;
        let data = match (shape.ty, variant) {
            (Type::User(UserType::Struct(st)), None) => st,
            (Type::User(UserType::Enum(en)), Some(variant)) => {
                en.variants
                    .iter()
                    .find(|v| v.name == variant.as_str())?
                    .data
            }
            _ => return None,
        };
        Some(RecordCtor {
            kind: variant_kind(data.kind),
            fields: data
                .fields
                .iter()
                .map(|field| Symbol::intern(field.name))
                .collect(),
        })
    }

    /// Whether any type, of either kind, is registered for `shape`.
    pub fn has_shape(&self, shape: &'static Shape) -> bool {
        self.read().types.iter().any(|ty| ty.shape == shape)
    }

    /// Reads field `name` of a native object.
    pub fn field(
        &self,
        cx: &dyn ConvertCx,
        object: &NativeObject,
        name: &str,
    ) -> Option<RunResult<Value>> {
        let field = self.hooks(object.ty).field;
        object.with_any(|value| field(cx, value, name))
    }

    /// Formats a native object with its `Display`, or else `Debug`.
    /// A native object's `Display`, or its Xur type name in angle brackets
    /// when the Rust type has no `Display` (`<AnyImage>`), rather than a
    /// debug dump.
    pub fn display(&self, object: &NativeObject) -> String {
        object
            .with_any(self.hooks(object.ty).display)
            .unwrap_or_else(|| format!("<{}>", self.type_name(object.ty)))
    }

    /// Whether two native objects are equal by their Rust `PartialEq`.
    pub fn native_eq(&self, a: &NativeObject, b: &NativeObject) -> bool {
        if a.ty != b.ty {
            return false;
        }
        if std::ptr::eq(a, b) {
            return true;
        }
        let eq = self.hooks(a.ty).eq;
        a.with_any(|a| b.with_any(|b| eq(a, b)))
    }

    /// A native object of the type registered for `T`, holding `value` and
    /// keeping `keep_alive` alive with it so any memory `value` borrows
    /// stays valid. For types like `PEFile<'static>` that borrow a file's
    /// bytes: the bytes go in `keep_alive`.
    pub fn borrowing_object<T: Facet<'static> + Send + 'static>(
        &self,
        value: T,
        keep_alive: Arc<dyn std::any::Any + Send + Sync>,
    ) -> RunResult<Value> {
        let ty = self
            .type_of_shape(T::SHAPE)
            .ok_or_else(|| RuntimeError::new(format!("`{}` is not a registered type", T::SHAPE)))?;
        let object = NativeObject::borrowing(ty, Box::new(value), keep_alive);
        Ok(Value::Native(object.into()))
    }

    /// A native object holding a clone of the registered value behind `peek`.
    pub(crate) fn object_from_peek(
        &self,
        ty: NativeTypeId,
        peek: Peek<'_, 'static>,
    ) -> Option<NativeObject> {
        let value = (self.hooks(ty).clone_peek)(peek)?;
        Some(NativeObject::new(ty, value))
    }

    /// Writes a clone of `object` into a builder for its type.
    pub(crate) fn set_object(&self, partial: Builder, object: &NativeObject) -> RunResult<Builder> {
        let set = self.hooks(object.ty).set;
        object.with_any(|value| set(partial, value))
    }

    /// The hooks of a type registered with its Rust type, which every type
    /// with native objects is.
    fn hooks(&self, ty: NativeTypeId) -> TypeHooks {
        self.read().types[ty.0 as usize]
            .hooks
            .expect("native objects only exist for types registered with their Rust type")
    }

    /// The registered modules as name resolution sees them.
    pub fn decls(&self) -> Vec<NativeModule> {
        let inner = self.read();
        inner
            .roots
            .iter()
            .map(|&module| inner.decl(module))
            .collect()
    }

    /// Registers the contents of the lazy module at `path`, if not yet
    /// registered, and describes it.
    pub fn expand(&self, path: &[String]) -> NativeModule {
        let (module, init) = {
            let mut inner = self.write();
            let module = inner
                .find(path)
                .unwrap_or_else(|| panic!("no native module `{}`", path.join("::")));
            (module, inner.modules[module].init.take())
        };
        // The initializer registers through the builder, which locks.
        if let Some(init) = init {
            init(&mut ModuleBuilder::new(self, module));
        }
        self.read().decl(module)
    }

    pub fn add_fn(
        &self,
        name: &str,
        signature: Option<Signature>,
        param_names: Vec<String>,
        call: Box<CallFn>,
    ) -> NativeFnDecl {
        self.write().add_fn(name, signature, param_names, call)
    }

    fn with_inner<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
        f(&mut self.write())
    }
}

impl Inner {
    fn module_at(&mut self, path: &str) -> usize {
        let mut names = path.split("::");
        let root = names.next().expect("split yields at least one item");
        let mut module = self.child(None, root);
        for name in names {
            module = self.child(Some(module), name);
        }
        module
    }

    fn find(&self, path: &[String]) -> Option<usize> {
        let mut module: Option<usize> = None;
        for name in path {
            let siblings = match module {
                Some(parent) => &self.modules[parent].children,
                None => &self.roots,
            };
            module = Some(*siblings.iter().find(|&&m| self.modules[m].name == *name)?);
        }
        module
    }

    fn decl(&self, module: usize) -> NativeModule {
        let data = &self.modules[module];
        if data.init.is_some() {
            return NativeModule {
                name: data.name.clone(),
                lazy: true,
                ..NativeModule::default()
            };
        }
        NativeModule {
            name: data.name.clone(),
            lazy: false,
            functions: data.functions.clone(),
            types: data
                .types
                .iter()
                .map(|&id| {
                    let ty = &self.types[id.0 as usize];
                    NativeTypeDecl {
                        name: ty.name.clone(),
                        id,
                        functions: ty.functions.clone(),
                        variants: if let Some(ref v) = ty.explicit_variants {
                            v.clone()
                        } else {
                            variant_decls(ty.shape)
                        },
                    }
                })
                .collect(),
            modules: data
                .children
                .iter()
                .map(|&child| self.decl(child))
                .collect(),
        }
    }

    /// The submodule `name` of `parent` (or the root module `name`).
    fn child(&mut self, parent: Option<usize>, name: &str) -> usize {
        let siblings = match parent {
            Some(parent) => &self.modules[parent].children,
            None => &self.roots,
        };
        if let Some(&existing) = siblings.iter().find(|&&m| self.modules[m].name == name) {
            return existing;
        }
        let module = self.modules.len();
        self.modules.push(ModuleData {
            name: name.to_owned(),
            init: None,
            children: Vec::new(),
            functions: Vec::new(),
            types: Vec::new(),
            macros: HashMap::new(),
        });
        match parent {
            Some(parent) => self.modules[parent].children.push(module),
            None => self.roots.push(module),
        }
        module
    }

    fn add_fn(
        &mut self,
        name: &str,
        signature: Option<Signature>,
        param_names: Vec<String>,
        call: Box<CallFn>,
    ) -> NativeFnDecl {
        let id = NativeFnId(self.fns.len() as u32);
        self.fns.push(Arc::new(NativeFn {
            name: name.to_owned(),
            signature,
            return_hint: None,
            param_names: param_names.clone(),
            call,
        }));
        NativeFnDecl {
            name: name.to_owned(),
            id,
            param_names,
        }
    }
}

impl NativeProvider for Registry {
    fn modules(&self) -> Vec<NativeModule> {
        self.decls()
    }

    fn expand(&self, path: &[String]) -> NativeModule {
        Registry::expand(self, path)
    }

    fn macro_expander(&self, path: &[&str]) -> Option<Arc<dyn MacroExpander>> {
        if path.is_empty() {
            return None;
        }
        let (module_path, macro_name) = path.split_at(path.len() - 1);
        let macro_name = macro_name[0];

        // Walk the module tree, expanding lazy modules along the way.
        // Each lock is acquired and released before the next to avoid
        // deadlocking when a lazy init needs a write lock.
        let mut module: Option<usize> = None;
        for name in module_path {
            let idx = {
                let inner = self.read();
                let siblings = match module {
                    Some(parent) => &inner.modules[parent].children,
                    None => &inner.roots,
                };
                siblings
                    .iter()
                    .find(|&&m| inner.modules[m].name == *name)
                    .copied()?
            };

            let init = self.write().modules[idx].init.take();
            if let Some(init) = init {
                init(&mut ModuleBuilder::new(self, idx));
            }
            module = Some(idx);
        }

        let parent = module?;
        self.read().modules[parent].macros.get(macro_name).cloned()
    }

    fn register_enum_builtins(&self, enum_def: DefId) -> Vec<NativeFnDecl> {
        vec![
            self.add_fn(
                "from_str",
                None,
                vec!["name".into()],
                Box::new({
                    let def = enum_def;
                    move |cx, args| enum_from_str(cx, def, args)
                }),
            ),
            self.add_fn(
                "len",
                None,
                Vec::new(),
                Box::new({
                    let def = enum_def;
                    move |cx, args| enum_len(cx, def, args)
                }),
            ),
            self.add_fn(
                "values",
                None,
                Vec::new(),
                Box::new({
                    let def = enum_def;
                    move |cx, args| enum_values(cx, def, args)
                }),
            ),
        ]
    }
}

fn enum_from_str(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
    let [Value::Str(name)] = args else {
        return Err(RuntimeError::new("`from_str` takes a string"));
    };
    let lang = cx.lang();
    for (vname, vdef, has_fields) in cx.enum_variants(enum_def) {
        if vname == name.as_ref() && !has_fields {
            return Ok(Value::adt(lang.some, vec![Value::adt(vdef, vec![])]));
        }
    }
    Ok(Value::adt(lang.none, vec![]))
}

fn enum_len(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
    if !args.is_empty() {
        return Err(RuntimeError::new("`len` takes no arguments"));
    }
    Ok(Value::int(cx.enum_variants(enum_def).len() as i64))
}

fn enum_values(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
    if !args.is_empty() {
        return Err(RuntimeError::new("`values` takes no arguments"));
    }
    let values: Vec<Value> = cx
        .enum_variants(enum_def)
        .into_iter()
        .filter(|(_, _, has_fields)| !has_fields)
        .map(|(_, vdef, _)| Value::adt(vdef, vec![]))
        .collect();
    Ok(Value::list(values))
}