Skip to main content

aver/types/
result.rs

1/// Result namespace — combinators for Result<T, E>.
2///
3/// Methods:
4///   Result.withDefault(result, default) → T  — unwrap Ok or return default
5///
6/// Constructors (Ok, Err) are registered separately in interpreter/core.rs.
7/// No effects required.
8use std::collections::HashMap;
9
10use crate::value::{RuntimeError, Value};
11
12pub fn register(global: &mut HashMap<String, Value>) {
13    // Result namespace already exists (created in interpreter/core.rs for Ok/Err ctors).
14    // We merge our members into it via a separate step in core.rs.
15    // This function registers nothing — see `extra_result_members()`.
16    let _ = global;
17}
18
19/// Members to merge into the existing Result namespace.
20pub fn extra_members() -> Vec<(&'static str, String)> {
21    vec![("withDefault", "Result.withDefault".to_string())]
22}
23
24pub fn effects(_name: &str) -> &'static [&'static str] {
25    &[]
26}
27
28pub fn call(name: &str, args: &[Value]) -> Option<Result<Value, RuntimeError>> {
29    match name {
30        "Result.withDefault" => Some(with_default(args)),
31        _ => None,
32    }
33}
34
35// ─── Implementations ────────────────────────────────────────────────────────
36
37fn with_default(args: &[Value]) -> Result<Value, RuntimeError> {
38    if args.len() != 2 {
39        return Err(RuntimeError::Error(format!(
40            "Result.withDefault() takes 2 arguments (result, default), got {}",
41            args.len()
42        )));
43    }
44    match &args[0] {
45        Value::Ok(v) => Ok(*v.clone()),
46        Value::Err(_) => Ok(args[1].clone()),
47        _ => Err(RuntimeError::Error(
48            "Result.withDefault: first argument must be a Result".to_string(),
49        )),
50    }
51}