xur-runtime 0.1.5

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
use std::marker::PhantomData;

use facet::{Facet, Shape};
use xur_resolve::NativeTypeId;

use super::hooks::TypeHooks;
use super::into_native::{
    IntoBuiltinMethod, IntoBuiltinMethodMut, IntoNativeFn, IntoNativeMethod, IntoNativeMethodMut,
};
use super::{CallFn, Context, NativeType, Registry, Signature};
use crate::{BuiltinType, RunResult, Value};
use xur_resolve::{NativeVariantDecl, NativeVariantKind};

/// A type whose static [`Shape`] can serve as a return-type hint for the LSP.
///
/// Blanket-implemented for every [`Facet`] type. Implement manually for
/// xur-only runtime types that have no Rust equivalent (see [`XurPtr`]).
pub trait Returns {
    const RET: &'static Shape;
}

impl<T: Facet<'static>> Returns for T {
    const RET: &'static Shape = T::SHAPE;
}

/// Runtime-only xur types that have no Facet equivalent. Use with the
/// An element type for compound return-type hints.
#[derive(Clone, Copy)]
pub enum ElemHint {
    /// A Facet shape, introspectable for generics.
    Shape(&'static Shape),
    /// A type name for primitives that have no Facet representation (e.g. `type`).
    Name(&'static str),
    /// The nth type parameter of the receiver (e.g. element type of a list).
    Param(u8),
}

/// `_xur` builder methods to annotate return types for the LSP.
#[derive(Clone, Copy)]
pub enum XurType {
    /// Pointer with optional pointee type, displayed as `*T` or `ptr`.
    Ptr(Option<&'static Shape>),
    /// List with optional element type, displayed as `list` or `list[T]`.
    List(Option<ElemHint>),
    /// Map with optional key/value types, displayed as `map` or `map<K, V>`.
    Map(Option<&'static Shape>, Option<&'static Shape>),
    /// A named type with generic type parameters, e.g. `Result<module, str>`.
    Named(&'static str, &'static [ElemHint]),
    Record,
    Module,
    Unit,
}

impl XurType {
    pub const PTR: Self = Self::Ptr(None);
    pub const LIST: Self = Self::List(None);
    pub const MAP: Self = Self::Map(None, None);
    pub const UNIT: Self = Self::Unit;

    pub fn ptr<T: Facet<'static>>() -> Self {
        Self::Ptr(Some(T::SHAPE))
    }
    pub fn list<T: Facet<'static>>() -> Self {
        Self::List(Some(ElemHint::Shape(T::SHAPE)))
    }
    pub fn list_named(name: &'static str) -> Self {
        Self::List(Some(ElemHint::Name(name)))
    }
    pub fn map<K: Facet<'static>, V: Facet<'static>>() -> Self {
        Self::Map(Some(K::SHAPE), Some(V::SHAPE))
    }
    pub fn map_keys<K: Facet<'static>>() -> Self {
        Self::Map(Some(K::SHAPE), None)
    }
    pub fn map_values<V: Facet<'static>>() -> Self {
        Self::Map(None, Some(V::SHAPE))
    }
}

/// A return-type hint stored on a raw function: either a Facet [`Shape`]
/// (introspectable for generics) or an [`XurType`] name.
#[derive(Clone, Copy)]
pub enum ReturnHint {
    Shape(&'static Shape),
    Xur(XurType),
}

/// Adds items to one module of a [`Registry`].
pub struct ModuleBuilder<'r> {
    registry: &'r Registry,
    pub(super) module: usize,
}

impl<'r> ModuleBuilder<'r> {
    pub(super) fn new(registry: &'r Registry, module: usize) -> Self {
        Self { registry, module }
    }

    /// The registry being filled in.
    pub fn registry(&self) -> &'r Registry {
        self.registry
    }

    /// The submodule `name` of this module, created if needed. A lazy
    /// module can fill in submodules as well as itself.
    pub fn submodule(&self, name: &str) -> ModuleBuilder<'r> {
        let parent = self.module;
        let module = self
            .registry
            .with_inner(|inner| inner.child(Some(parent), name));
        ModuleBuilder::new(self.registry, module)
    }
}

impl ModuleBuilder<'_> {
    /// Registers a compile-time macro expander in this module. Items with
    /// `#[name(...)]` attributes are expanded before name resolution.
    pub fn register_macro(
        &mut self,
        name: &str,
        expander: impl xur_resolve::macros::MacroExpander + 'static,
    ) -> &mut Self {
        self.registry.with_inner(|inner| {
            inner.modules[self.module]
                .macros
                .insert(name.to_owned(), std::sync::Arc::new(expander));
        });
        self
    }

    /// Registers a Rust function or closure whose argument and return
    /// types implement [`Facet`].
    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
        let (signature, call) = f.into_native();
        self.add_module_fn(name, Some(signature), Vec::new(), call, None)
    }

    /// Like [`function`](Self::function), with explicit parameter names for
    /// LSP hover and inlay hints.
    pub fn named_function<Marker>(
        &mut self,
        name: &str,
        params: &[&str],
        f: impl IntoNativeFn<Marker>,
    ) -> &mut Self {
        let (signature, call) = f.into_native();
        let names = params.iter().map(|s| s.to_string()).collect();
        self.add_module_fn(name, Some(signature), names, call, None)
    }

    /// Registers a function that works on Xur values directly and can use
    /// the running program through its [`Context`].
    pub fn raw_function(
        &mut self,
        name: &str,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add_module_fn(name, None, Vec::new(), Box::new(f), None)
    }

    /// Like [`raw_function`](Self::raw_function), declaring the return type
    /// for LSP inlay hints.
    pub fn raw_function_returns<R: Returns>(
        &mut self,
        name: &str,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add_module_fn(
            name,
            None,
            Vec::new(),
            Box::new(f),
            Some(ReturnHint::Shape(R::RET)),
        )
    }

    /// Like [`raw_function_returns`](Self::raw_function_returns) for
    /// xur-internal types that have no Facet equivalent.
    pub fn raw_function_returns_xur(
        &mut self,
        name: &str,
        ret: XurType,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add_module_fn(
            name,
            None,
            Vec::new(),
            Box::new(f),
            Some(ReturnHint::Xur(ret)),
        )
    }

    /// Like [`raw_function`](Self::raw_function), with explicit parameter
    /// names for LSP hover and inlay hints.
    pub fn named_raw_function(
        &mut self,
        name: &str,
        params: &[&str],
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        let names = params.iter().map(|s| s.to_string()).collect();
        self.add_module_fn(name, None, names, Box::new(f), None)
    }

    /// Like [`named_raw_function`](Self::named_raw_function), declaring the
    /// return type for LSP inlay hints.
    pub fn named_raw_function_returns<R: Returns>(
        &mut self,
        name: &str,
        params: &[&str],
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        let names = params.iter().map(|s| s.to_string()).collect();
        self.add_module_fn(
            name,
            None,
            names,
            Box::new(f),
            Some(ReturnHint::Shape(R::RET)),
        )
    }

    /// Like [`named_raw_function_returns`](Self::named_raw_function_returns)
    /// for xur-internal types that have no Facet equivalent.
    pub fn named_raw_function_returns_xur(
        &mut self,
        name: &str,
        params: &[&str],
        ret: XurType,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        let names = params.iter().map(|s| s.to_string()).collect();
        self.add_module_fn(name, None, names, Box::new(f), Some(ReturnHint::Xur(ret)))
    }

    fn add_module_fn(
        &mut self,
        name: &str,
        signature: Option<Signature>,
        names: Vec<String>,
        call: Box<CallFn>,
        return_hint: Option<ReturnHint>,
    ) -> &mut Self {
        let decl = self.registry.add_fn(name, signature, names, call);
        if let Some(hint) = return_hint {
            self.registry.set_return_hint(decl.id, hint);
        }
        let module = self.module;
        self.registry
            .with_inner(|inner| inner.modules[module].functions.push(decl));
        self
    }

    /// Registers the type with facet shape `shape` as `name`, without its
    /// Rust type: values of it passed to Xur become records of this type,
    /// which written types can check and which display with its name. For
    /// registering every type reachable from some shape, such as a
    /// library's.
    pub fn shape_type(&mut self, name: &str, shape: &'static Shape) -> NativeTypeId {
        let module = self.module;
        self.registry.with_inner(|inner| {
            let id = NativeTypeId(inner.types.len() as u32);
            inner.types.push(NativeType {
                name: name.to_owned(),
                shape,
                functions: Vec::new(),
                hooks: None,
                explicit_variants: None,
            });
            inner.modules[module].types.push(id);
            id
        })
    }

    /// Registers a `#[repr(inttype)]` enum whose variants are integer
    /// constants. Each `(name, value)` pair becomes a unit variant that
    /// lowers to `Const(Int(value))`.
    pub fn repr_enum(&mut self, name: &str, variants: &[(&str, i64)]) -> &mut Self {
        let module = self.module;
        let variant_decls: Vec<NativeVariantDecl> = variants
            .iter()
            .map(|(vname, value)| NativeVariantDecl {
                name: vname.to_string(),
                kind: NativeVariantKind::Unit,
                repr_value: Some(*value),
            })
            .collect();
        self.registry.with_inner(|inner| {
            let id = NativeTypeId(inner.types.len() as u32);
            inner.types.push(NativeType {
                name: name.to_owned(),
                shape: <()>::SHAPE,
                functions: Vec::new(),
                hooks: None,
                explicit_variants: Some(variant_decls),
            });
            inner.modules[module].types.push(id);
        });
        self
    }

    /// Returns a [`TypeBuilder`] for a type `T` that was already registered
    /// (by this or another module's [`ty`](Self::ty)). Use it to add methods
    /// to a shared type from a different module. Panics if `T` has not been
    /// registered yet.
    pub fn ty_existing<T: Facet<'static> + Clone + Send + 'static>(
        &mut self,
    ) -> TypeBuilder<'_, T> {
        let id = self
            .registry
            .type_of_shape(T::SHAPE)
            .expect("ty_existing: type not registered");
        TypeBuilder {
            registry: self.registry,
            ty: id,
            _ty: PhantomData,
        }
    }

    /// Registers the Rust type `T` as `name`. Values of `T` passed to Xur
    /// become native objects holding the Rust value.
    pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
        &mut self,
        name: &str,
    ) -> TypeBuilder<'_, T> {
        let module = self.module;
        let id = self.registry.with_inner(|inner| {
            let id = NativeTypeId(inner.types.len() as u32);
            inner.types.push(NativeType {
                name: name.to_owned(),
                shape: T::SHAPE,
                functions: Vec::new(),
                hooks: Some(TypeHooks::new::<T>()),
                explicit_variants: None,
            });
            inner.modules[module].types.push(id);
            id
        });
        TypeBuilder {
            registry: self.registry,
            ty: id,
            _ty: PhantomData,
        }
    }

    /// Registers the Rust type `T` as `name` without requiring `Clone`, for
    /// a type that borrows memory kept alive beside it (see
    /// [`Registry::borrowing_object`]). Its fields and methods work, but it
    /// cannot be cloned into another value or rebuilt from Xur.
    pub fn ty_borrowing<T: Facet<'static> + Send + 'static>(
        &mut self,
        name: &str,
    ) -> TypeBuilder<'_, T> {
        let module = self.module;
        let id = self.registry.with_inner(|inner| {
            let id = NativeTypeId(inner.types.len() as u32);
            inner.types.push(NativeType {
                name: name.to_owned(),
                shape: T::SHAPE,
                functions: Vec::new(),
                hooks: Some(TypeHooks::borrowing::<T>()),
                explicit_variants: None,
            });
            inner.modules[module].types.push(id);
            id
        });
        TypeBuilder {
            registry: self.registry,
            ty: id,
            _ty: PhantomData,
        }
    }
}

/// Adds functions to the registered native type `T`.
pub struct TypeBuilder<'r, T> {
    registry: &'r Registry,
    ty: NativeTypeId,
    _ty: PhantomData<T>,
}

impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
    /// Registers the associated function `Type::name`. If its first
    /// parameter is `T` it can also be called as a method, on a copy.
    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
        let (signature, call) = f.into_native();
        self.add(name, Some(signature), call, None)
    }

    /// Registers a function working on Xur values directly, with the
    /// object first when called as a method. For methods taking or
    /// returning arbitrary Xur values, like a channel's `send`.
    pub fn raw_function(
        &mut self,
        name: &str,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add(name, None, Box::new(f), None)
    }

    /// Like [`raw_function`](Self::raw_function), declaring the return type
    /// for LSP inlay hints.
    pub fn raw_function_returns<R: Returns>(
        &mut self,
        name: &str,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add(name, None, Box::new(f), Some(ReturnHint::Shape(R::RET)))
    }

    /// Like [`raw_function_returns`](Self::raw_function_returns) for
    /// xur-internal types that have no Facet equivalent.
    pub fn raw_function_returns_xur(
        &mut self,
        name: &str,
        ret: XurType,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add(name, None, Box::new(f), Some(ReturnHint::Xur(ret)))
    }

    /// Registers a method taking `&self`: `value.name(args)` in Xur.
    pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
        let (signature, call) = f.into_native();
        self.add(name, Some(signature), call, None)
    }

    /// Registers a method taking `&mut self`, which changes the object in
    /// place.
    pub fn method_mut<Marker>(
        &mut self,
        name: &str,
        f: impl IntoNativeMethodMut<T, Marker>,
    ) -> &mut Self {
        let (signature, call) = f.into_native();
        self.add(name, Some(signature), call, None)
    }

    fn add(
        &mut self,
        name: &str,
        signature: Option<Signature>,
        call: Box<CallFn>,
        return_hint: Option<ReturnHint>,
    ) -> &mut Self {
        let decl = self.registry.add_fn(name, signature, Vec::new(), call);
        if let Some(hint) = return_hint {
            self.registry.set_return_hint(decl.id, hint);
        }
        let ty = self.ty;
        self.registry
            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
        self
    }
}

/// Adds methods to a built-in type, like `list` or `str`.
pub struct BuiltinBuilder<'r> {
    registry: &'r Registry,
    ty: BuiltinType,
}

impl<'r> BuiltinBuilder<'r> {
    pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
        Self { registry, ty }
    }

    /// Registers a method as a Rust function taking the receiver, converted,
    /// first: `|s: String| s.to_uppercase()` for `"a".to_upper()`.
    ///
    /// **Note:** this clones the receiver out of its `Value` wrapper. For
    /// builtin types backed by `Arc<Mutex<..>>` (bytes, list), prefer
    /// [`method`](Self::method) which borrows in place.
    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
        let (signature, call) = f.into_native();
        self.add(name, Some(signature), call, None)
    }

    /// Registers a method that borrows the receiver without cloning:
    /// `|bytes: &[u8], i: i64| -> Option<i64>`.
    ///
    /// `Recv` is `[u8]` for bytes or `str` for strings — any type that
    /// implements [`BuiltinRecv`].
    pub fn method<Recv: ?Sized + 'static, Marker>(
        &mut self,
        name: &str,
        f: impl IntoBuiltinMethod<Recv, Marker>,
    ) -> &mut Self {
        let (signature, call) = f.into_native();
        self.add(name, Some(signature), call, None)
    }

    /// Like [`method`](Self::method) but borrows mutably:
    /// `|bytes: &mut Vec<u8>, val: i64| { bytes.push(val as u8); }`.
    pub fn method_mut<Recv: 'static, Marker>(
        &mut self,
        name: &str,
        f: impl IntoBuiltinMethodMut<Recv, Marker>,
    ) -> &mut Self {
        let (signature, call) = f.into_native();
        self.add(name, Some(signature), call, None)
    }

    /// Registers a method working on Xur values directly, with the receiver
    /// first; needed to change a list in place.
    pub fn raw_function(
        &mut self,
        name: &str,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add(name, None, Box::new(f), None)
    }

    /// Like [`raw_function`](Self::raw_function), declaring the return type
    /// for LSP inlay hints.
    pub fn raw_function_returns<R: Returns>(
        &mut self,
        name: &str,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add(name, None, Box::new(f), Some(ReturnHint::Shape(R::RET)))
    }

    /// Like [`raw_function_returns`](Self::raw_function_returns) for
    /// xur-internal types that have no Facet equivalent.
    pub fn raw_function_returns_xur(
        &mut self,
        name: &str,
        ret: XurType,
        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
    ) -> &mut Self {
        self.add(name, None, Box::new(f), Some(ReturnHint::Xur(ret)))
    }

    fn add(
        &mut self,
        name: &str,
        signature: Option<Signature>,
        call: Box<CallFn>,
        return_hint: Option<ReturnHint>,
    ) -> &mut Self {
        let decl = self.registry.add_fn(name, signature, Vec::new(), call);
        if let Some(hint) = return_hint {
            self.registry.set_return_hint(decl.id, hint);
        }
        let key = (self.ty, name.to_owned());
        self.registry
            .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
        self
    }
}