vyder_std 0.3.4

Standard library for vyder.
Documentation
//! Various functions to help with error handling.
//!
//! Available under the name `std-error`.

use std::process::ExitCode;

use vyder::{values, Error, ExpectArity, Module, Span, Value, ValueResult};

/// Crashes if the value is an error, returns the value if it's not.
///
/// Expectes exactly one argument.
pub fn unwrap(
    arguments: &[ValueResult],
    span: Span,
) -> Result<(ValueResult, Option<ExitCode>), Error> {
    let argument = arguments.to_vec().expect_exact::<1>(&span)?[0].clone();

    if let ValueResult::Err(value) = argument {
        eprintln!("unexpected error value: {}", value);
        Ok((
            ValueResult::Ok(Value::new_value(values::Nil.into(), span)),
            Some(ExitCode::FAILURE),
        ))
    } else {
        Ok((argument, None))
    }
}

/// Returns the value it's given, converting it to a non-error if it's an error.
///
/// Expectes exactly one argument.
pub fn ignore(
    arguments: &[ValueResult],
    span: Span,
) -> Result<(ValueResult, Option<ExitCode>), Error> {
    let argument = arguments.to_vec().expect_exact::<1>(&span)?[0].clone();

    let argument = match argument {
        ValueResult::Ok(value) | ValueResult::Err(value) => ValueResult::Ok(value),
    };

    Ok((argument, None))
}

/// Returns `true` if the value is an error, otherwise `false`.
///
/// Expectes exactly one argument.
pub fn is_error(
    arguments: &[ValueResult],
    span: Span,
) -> Result<(ValueResult, Option<ExitCode>), Error> {
    let argument = arguments.to_vec().expect_exact::<1>(&span)?[0].clone();

    let is_error = match argument {
        ValueResult::Ok(_) => false,
        ValueResult::Err(_) => true,
    };

    Ok((
        Value::new_ok_value(values::Bool { value: is_error }.into(), span),
        None,
    ))
}

pub fn get_module() -> Module {
    Module::builder()
        .function("unwrap", unwrap, false)
        .function("ignore", ignore, false)
        .build()
}