xur-runtime 0.1.10

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
use facet::Facet;

use super::*;
use crate::testing::{TestCx, fn_id};

const TEST_PRELUDE: &str = "\
#[try(unwrap = \"Ok\")]
pub enum Result<T, E = str> { Ok(T) Err(E) }
pub use Result::Ok;
pub use Result::Err;
#[try(unwrap = \"Some\")]
pub enum Option<T> { Some(T) None }
pub use Option::Some;
pub use Option::None;
";

#[derive(Facet, Debug, Clone, PartialEq)]
struct Point {
    x: f64,
    y: f64,
}

fn registry() -> Registry {
    let registry = Registry::new();
    registry
        .module("geo::shapes")
        .function("double", |x: i64| x * 2)
        .function("describe", |name: String, n: u8| format!("{name}#{n}"));
    registry
        .module("geo")
        .ty::<Point>("Point")
        .function("new", |x: f64, y: f64| Point { x, y })
        .method("norm", |p: &Point| p.x.hypot(p.y))
        .method_mut("scale", |p: &mut Point, k: f64| {
            p.x *= k;
            p.y *= k;
        });
    registry
}

#[test]
fn decls_describe_the_module_tree() {
    let decls = registry().decls();
    assert_eq!(decls.len(), 1);
    let geo = &decls[0];
    assert_eq!(geo.name, "geo");
    assert_eq!(geo.modules[0].name, "shapes");
    assert_eq!(geo.modules[0].functions[1].name, "describe");
    assert_eq!(geo.types[0].name, "Point");
    assert_eq!(geo.types[0].functions[1].name, "norm");
    assert_eq!(geo.types[0].functions[2].name, "scale");
}

#[test]
fn typed_functions_convert_arguments_and_results() {
    let registry = registry();
    let mut cx = TestCx::new(&registry, TEST_PRELUDE);
    let double = fn_id(&registry, "geo::shapes::double");
    assert_eq!(cx.call(double, &[Value::int(21)]), Ok(Value::int(42)));
    let describe = fn_id(&registry, "geo::shapes::describe");
    assert_eq!(
        cx.call(describe, &[Value::str("p"), Value::int(3)]),
        Ok(Value::str("p#3"))
    );
}

#[test]
fn signatures_record_shapes() {
    let registry = registry();
    let signature = registry
        .function(fn_id(&registry, "geo::shapes::describe"))
        .signature
        .clone()
        .unwrap();
    assert_eq!(signature.params, [String::SHAPE, u8::SHAPE]);
    assert_eq!(signature.ret, String::SHAPE);
}

#[test]
fn a_string_named_return_type_still_produces_an_lsp_hint() {
    // A raw sig with a string-named return (`returns("record")`) must set a
    // return hint — otherwise the LSP can't infer the type. Previously only
    // `.lsp(..)` and shape-typed returns did, so named ones showed nothing.
    let registry = Registry::new();
    registry
        .module("m")
        .raw_function_sig("mk", RawSig::new().returns("record"), |_cx, _args| {
            Ok(Value::Unit)
        });
    assert!(matches!(
        registry.function(fn_id(&registry, "m::mk")).return_hint,
        Some(ReturnHint::Xur(XurType::Named("record", &[])))
    ));
}

#[test]
fn signatures_describe_types_without_shapes() {
    use crate::{Opt, OptionalArg, XurStr};
    let registry = Registry::new();
    registry.module("t").named_function(
        "find",
        &["text", "needle", "start"],
        |_t: XurStr, _n: Value, _s: OptionalArg<i64>| -> Opt<XurStr> { Opt(None) },
    );
    let f = registry.function(fn_id(&registry, "t::find"));
    let signature = f.signature.as_ref().unwrap();
    let names: Vec<_> = signature
        .param_types
        .iter()
        .map(|t| registry.type_desc_name(t))
        .collect();
    assert_eq!(names, ["str", "any", "i64"]);
    assert_eq!(signature.required, 2);
    assert_eq!(registry.type_desc_name(&signature.ret_type), "Option<str>");
}

fn new_point(cx: &mut TestCx<'_>, x: f64, y: f64) -> Value {
    let new = fn_id(cx.registry, "geo::Point::new");
    cx.call(new, &[Value::float(x), Value::float(y)]).unwrap()
}

#[test]
fn registered_types_are_native_objects() {
    let registry = registry();
    let mut cx = TestCx::new(&registry, TEST_PRELUDE);
    let point = new_point(&mut cx, 3.0, 4.0);
    let Value::Native(object) = &point else {
        panic!("expected a native object, found {point:?}");
    };
    assert_eq!(object.with(Point::clone), Some(Point { x: 3.0, y: 4.0 }));
    assert_eq!(
        cx.call(fn_id(&registry, "geo::Point::norm"), &[point]),
        Ok(Value::float(5.0))
    );
}

#[test]
fn mutating_methods_change_the_object_in_place() {
    let registry = registry();
    let mut cx = TestCx::new(&registry, TEST_PRELUDE);
    let point = new_point(&mut cx, 1.0, 2.0);
    let alias = point.clone();
    let scale = fn_id(&registry, "geo::Point::scale");
    assert_eq!(cx.call(scale, &[point, Value::float(3.0)]), Ok(Value::Unit));
    let Value::Native(object) = &alias else {
        unreachable!()
    };
    assert_eq!(object.with(Point::clone), Some(Point { x: 3.0, y: 6.0 }));
}

#[test]
fn native_fields_display_and_equality() {
    let registry = registry();
    let mut cx = TestCx::new(&registry, TEST_PRELUDE);
    let (Value::Native(a), Value::Native(b)) =
        (new_point(&mut cx, 1.0, 2.0), new_point(&mut cx, 1.0, 2.0))
    else {
        unreachable!()
    };
    assert_eq!(registry.field(&cx, &a, "y"), Some(Ok(Value::float(2.0))));
    assert_eq!(registry.field(&cx, &a, "z"), None);
    assert_eq!(registry.display(&a), "Point { x: 1.0, y: 2.0 }");
    assert!(registry.native_eq(&a, &b));
}

#[test]
fn bad_calls_are_runtime_errors() {
    let registry = registry();
    let mut cx = TestCx::new(&registry, TEST_PRELUDE);
    let double = fn_id(&registry, "geo::shapes::double");
    assert_eq!(
        cx.call(double, &[]).unwrap_err().message(),
        "expected 1 argument(s), found 0"
    );
    assert_eq!(
        cx.call(double, &[Value::str("x")]).unwrap_err().message(),
        "expected `i64`, found string"
    );
}

#[test]
fn lazy_modules_are_registered_when_expanded() {
    let registry = Registry::new();
    registry.lazy_module("big::part", |m| {
        m.function("answer", || 42i64);
    });
    let decls = registry.decls();
    assert!(decls[0].modules[0].lazy);
    assert!(decls[0].modules[0].functions.is_empty());

    let expanded = registry.expand(&["big".into(), "part".into()]);
    assert!(!expanded.lazy);
    assert_eq!(expanded.functions[0].name, "answer");
    assert!(!registry.decls()[0].modules[0].lazy);
}

#[test]
fn registries_can_be_shared_between_threads() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Registry>();
}

#[test]
fn lazy_modules_can_fill_in_submodules() {
    let registry = Registry::new();
    registry.lazy_module("lib", |module| {
        module.function("top", || 1i64);
        module.submodule("inner").function("deep", || 2i64);
    });
    assert!(registry.decls()[0].lazy);
    let expanded = registry.expand(&["lib".to_owned()]);
    assert_eq!(expanded.functions[0].name, "top");
    assert_eq!(expanded.modules[0].name, "inner");
    assert_eq!(expanded.modules[0].functions[0].name, "deep");
}

#[test]
fn shape_xur_name_maps_rust_types() {
    let registry = registry();
    assert_eq!(registry.shape_xur_name(String::SHAPE), "str");
    assert_eq!(registry.shape_xur_name(bool::SHAPE), "bool");
    assert_eq!(registry.shape_xur_name(i64::SHAPE), "i64");
    assert_eq!(registry.shape_xur_name(f64::SHAPE), "f64");
    assert_eq!(registry.shape_xur_name(<Vec<String>>::SHAPE), "list<str>");
    assert_eq!(registry.shape_xur_name(<Vec<u8>>::SHAPE), "bytes");
    assert_eq!(registry.shape_xur_name(<()>::SHAPE), "()");
    // Generic types keep their type arguments.
    assert_eq!(
        registry.shape_xur_name(<Result<Vec<String>, String>>::SHAPE),
        "Result<list<str>, str>",
    );
    assert_eq!(
        registry.shape_xur_name(<Option<String>>::SHAPE),
        "Option<str>"
    );
    // Registered types use their xur name.
    assert_eq!(registry.shape_xur_name(Point::SHAPE), "Point");
    // shape_type_param extracts generic arguments.
    assert_eq!(
        registry.shape_type_param(<Result<Vec<String>, String>>::SHAPE, 0),
        Some("list<str>".into()),
    );
    assert_eq!(
        registry.shape_type_param(<Result<Vec<String>, String>>::SHAPE, 1),
        Some("str".into()),
    );
    assert_eq!(
        registry.shape_type_param(<Option<i64>>::SHAPE, 0),
        Some("i64".into()),
    );
    assert_eq!(registry.shape_type_param(String::SHAPE, 0), None);
}

#[test]
fn named_methods_put_self_first() {
    #[derive(Facet, Clone)]
    struct Counter {
        n: i64,
    }
    let registry = Registry::new();
    registry.module("t").ty::<Counter>("Counter").named_method(
        "add",
        &["by"],
        |c: &Counter, by: i64| c.n + by,
    );
    registry.builtin(BuiltinType::Str).named_method(
        "repeat_n",
        &["times"],
        |s: &str, times: i64| s.repeat(times as usize),
    );
    let add = registry.function(fn_id(&registry, "t::Counter::add"));
    assert_eq!(add.param_names, ["self", "by"]);
    let repeat = registry
        .builtin_method(BuiltinType::Str, "repeat_n")
        .unwrap();
    assert_eq!(registry.function(repeat).param_names, ["times"]);
}

#[test]
fn type_shapes_carry_doc_comments() {
    /// A thing with a size.
    #[derive(Facet, Clone)]
    struct Box2 {
        /// How big it is.
        size: i64,
    }
    let registry = Registry::new();
    registry.module("t").ty::<Box2>("Box2");
    let id = registry.type_id_by_name("Box2").unwrap();
    let shape = registry.type_shape(id);
    assert_eq!(shape.doc, [" A thing with a size."]);
    let Type::User(UserType::Struct(st)) = shape.ty else {
        panic!("a struct");
    };
    assert_eq!(st.fields[0].doc, [" How big it is."]);
}

#[test]
fn dyn_values_describe_themselves() {
    use crate::desc::{Int, ListOf, T, Tuple2};
    use crate::{Dyn, Opt};
    let registry = Registry::new();
    registry
        .builtin(BuiltinType::List)
        .named_method(
            "first_of",
            &["fallback"],
            |list: &[Value], fallback: Dyn<T>| {
                Opt(Some(Dyn::<T>::new(
                    list.first().cloned().unwrap_or(fallback.0),
                )))
            },
        )
        .method("pairs", |_list: &[Value]| -> Dyn<ListOf<Tuple2<Int, T>>> {
            Dyn::new(Value::list(Vec::new()))
        });
    let describe = |name: &str| {
        let id = registry.builtin_method(BuiltinType::List, name).unwrap();
        let f = registry.function(id);
        let sig = f.signature.as_ref().unwrap();
        let params: Vec<_> = sig
            .param_types
            .iter()
            .map(|t| registry.type_desc_name(t))
            .collect();
        (params, registry.type_desc_name(&sig.ret_type))
    };
    assert_eq!(
        describe("first_of"),
        (vec!["T".to_string()], "Option<T>".to_string())
    );
    assert_eq!(describe("pairs"), (vec![], "list<(i64, T)>".to_string()));
}

crate::one_of! {
    #[allow(dead_code)]
    enum Small {
        Int(i64),
        Text(crate::XurStr),
    }
}

crate::one_of! {
    #[allow(dead_code)]
    enum Many {
        A(i64),
        B(f64),
        C(bool),
        D(crate::XurStr),
    }
}

crate::one_of! {
    #[allow(dead_code)]
    enum ManyArg as "Plenty" {
        A(i64),
        B(f64),
        C(bool),
        D(crate::XurStr),
    }
}

#[test]
fn long_named_unions_show_their_name() {
    use crate::OneOf;
    let registry = Registry::new();
    registry
        .module("t")
        .named_function("small", &["x"], |_x: OneOf<Small>| ())
        .named_function("many", &["x"], |_x: OneOf<Many>| ())
        .named_function("plenty", &["x"], |_x: OneOf<ManyArg>| ());
    let param = |name: &str| {
        let f = registry.function(fn_id(&registry, name));
        registry.type_desc_name(&f.signature.as_ref().unwrap().param_types[0])
    };
    assert_eq!(param("t::small"), "i64 | str");
    assert_eq!(param("t::many"), "Many");
    assert_eq!(param("t::plenty"), "Plenty");
    let tree = crate::doc::dump(&registry, &[]);
    assert_eq!(tree.aliases["Many"], ["i64", "f64", "bool", "str"]);
}

#[test]
fn enums_only_convert_from_their_own_values() {
    use crate::convert::{from_value, into_value};

    #[derive(Facet, Debug, Clone, Copy, PartialEq)]
    #[repr(u8)]
    enum Builder {
        New,
        Append,
    }
    #[derive(Facet, Debug, Clone, Copy, PartialEq)]
    #[repr(u8)]
    enum List {
        New,
        Add,
    }

    let registry = Registry::new();
    registry.module("t").shape_type("Builder", Builder::SHAPE);
    registry.module("t").shape_type("List", List::SHAPE);
    let cx = TestCx::new(&registry, TEST_PRELUDE);

    let list_new = into_value(&cx, List::New).unwrap();
    assert_eq!(from_value::<List>(&cx, &list_new), Ok(List::New));
    // Same variant name, different enum.
    assert!(from_value::<Builder>(&cx, &list_new).is_err());
}