xur-std 0.1.8

The standard library of the Xur language
Documentation
//! `std::ptr`: raw pointer construction and arithmetic.

use xur_runtime::registry::{RawSig, XurType};
use xur_runtime::{BuiltinType, Registry, RunResult, RuntimeError, TypeDesc, Value};

pub(crate) fn register(registry: &Registry) {
    registry
        .module("std::ptr")
        .raw_function_sig(
            "null",
            RawSig::new().returns("ptr").lsp(XurType::PTR),
            |_cx, _args| Ok(Value::Ptr(0)),
        )
        .raw_function_sig(
            "from_int",
            RawSig::new()
                .param("addr", "i64")
                .returns("ptr")
                .lsp(XurType::PTR),
            |_cx, args| {
                let [Value::Int(addr)] = args else {
                    return Err(RuntimeError::new("`from_int` takes an integer"));
                };
                Ok(Value::Ptr(addr.to_u64().ok_or_else(|| {
                    RuntimeError::new(format!("`from_int`: {} does not fit in u64", addr))
                })?))
            },
        );
    registry
        .builtin(BuiltinType::Ptr)
        .raw_method_sig(
            "to_int",
            RawSig::new().returns(TypeDesc::of::<i64>()),
            |_cx, args| {
                let [Value::Ptr(addr)] = args else {
                    return Err(RuntimeError::new("`to_int` takes a pointer"));
                };
                Ok(Value::Int((*addr).into()))
            },
        )
        .raw_method_sig(
            "is_null",
            RawSig::new().returns(TypeDesc::of::<bool>()),
            |_cx, args| {
                let [Value::Ptr(addr)] = args else {
                    return Err(RuntimeError::new("`is_null` takes a pointer"));
                };
                Ok(Value::Bool(*addr == 0))
            },
        )
        .raw_method_sig(
            "offset",
            RawSig::new()
                .param("n", "i64")
                .returns("ptr")
                .lsp(XurType::PTR),
            |_cx, args| {
                let [Value::Ptr(addr), Value::Int(n)] = args else {
                    return Err(RuntimeError::new("`offset` takes an integer"));
                };
                Ok(Value::Ptr(addr.wrapping_add(n.to_i128() as u64)))
            },
        )
        .raw_method_sig(
            "to_hex",
            RawSig::new().returns(TypeDesc::of::<String>()),
            |_cx, args| -> RunResult<Value> {
                let [Value::Ptr(addr)] = args else {
                    return Err(RuntimeError::new("`to_hex` takes a pointer"));
                };
                Ok(Value::str(&format!("0x{addr:x}")))
            },
        );
}