xur-runtime 0.1.8

Values, native-function registry and facet conversions for the Xur language
Documentation
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 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"]);
}