compmd 0.13.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
//! CEL's optional types (spec ยง8.2): `optional.of` and `optional.none`, the methods on an optional, and selecting or
//! indexing one. A reading that may find nothing gives an optional, so finding nothing isn't an error.

#![allow(
    clippy::unnecessary_wraps,
    reason = "every implementation has an overload's signature, which can fail"
)]

use super::Functions;
use super::value::Value;
use compmd_macros::library;

/// An optional function's implementation, as a CEL function's: the render, then the arguments.
pub(crate) type Call = fn(&dyn Functions, &[Value]) -> Result<Value, String>;

/// The functions of the `optional.` namespace.
#[library(prefix = "optional.", call = Call)]
pub(crate) enum OptionalFunction {
    /// An optional with the value given.
    ///
    /// ```cel
    /// optional.of(2).value() // 2
    /// ```
    #[overload(fn(value: Any) -> Optional(0) = of)]
    Of,

    /// An optional without a value.
    ///
    /// ```cel
    /// optional.none().hasValue() // false
    /// ```
    #[overload(fn() -> Optional(0) = none)]
    None,
}

fn of(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
    Ok(Value::optional(args.first().cloned()))
}

fn none(_: &dyn Functions, _: &[Value]) -> Result<Value, String> {
    Ok(Value::optional(None))
}

/// The value of the optional `args[0]`, if it has one.
fn inner(args: &[Value]) -> Option<&Value> {
    match args.first() {
        Some(Value::Optional(Some(value))) => Some(value),
        _ => None,
    }
}

/// Whether the optional has a value.
pub(crate) fn has_value(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
    Ok(Value::Bool(inner(args).is_some()))
}

/// The optional's value, an error without one.
pub(crate) fn value(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
    inner(args).cloned().ok_or_else(|| {
        "optional.none() has no value; use orValue() for one in its place".to_string()
    })
}

/// The optional's value, or the value given without one.
pub(crate) fn or_value(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
    Ok(inner(args)
        .or_else(|| args.get(1))
        .cloned()
        .unwrap_or(Value::Null))
}

/// The optional when it has a value, the other one otherwise.
pub(crate) fn or(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
    let first = args.first().filter(|_| inner(args).is_some());
    Ok(first
        .or_else(|| args.get(1))
        .cloned()
        .unwrap_or(Value::Null))
}