mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use crate::expression::forms::interpolate::Interpolate;
use crate::expression::forms::step::Step;
use crate::expression::functions::Role;
use crate::expression::parse::ParsingError;
use crate::expression::{Dependency, Expr, Node};
use crate::log_target;

/// The zoom curve of an expression: the top-level interpolate or step whose
/// input is `zoom`.
#[derive(Clone, Copy)]
pub enum ZoomCurve<'a> {
    Interpolate(&'a Interpolate),
    Step(&'a Step),
}

impl PartialEq for ZoomCurve<'_> {
    /// Curves are equal when they are the same node of the expression.
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ZoomCurve::Interpolate(a), ZoomCurve::Interpolate(b)) => std::ptr::eq(*a, *b),
            (ZoomCurve::Step(a), ZoomCurve::Step(b)) => std::ptr::eq(*a, *b),
            _ => false,
        }
    }
}

impl std::fmt::Debug for ZoomCurve<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ZoomCurve::Interpolate(_) => f.write_str("Interpolate"),
            ZoomCurve::Step(_) => f.write_str("Step"),
        }
    }
}

/// The zoom curve found in an expression, none, or why the expression's use
/// of `zoom` is invalid.
pub(crate) type ZoomCurveResult<'a> = Result<Option<ZoomCurve<'a>>, ParsingError>;

fn zoom_input(input: &Expr) -> bool {
    input.as_compound().is_some_and(|z| z.overload().role == Role::Zoom)
}

/// Find a zoom curve in the expression tree: the relevant step or
/// interpolate item, or the error if the expression represents an error.
pub(crate) fn find_zoom_curve(e: &Expr) -> ZoomCurveResult<'_> {
    let found = match e.node() {
        Node::Let(let_) => find_zoom_curve(let_.result())?,
        Node::Coalesce(coalesce) => {
            let mut found = None;
            for child in coalesce.args() {
                found = find_zoom_curve(child)?;
                if found.is_some() {
                    break;
                }
            }
            found
        }
        Node::Interpolate(curve) if zoom_input(curve.input()) => Some(ZoomCurve::Interpolate(curve)),
        Node::Step(step) if zoom_input(step.input()) => Some(ZoomCurve::Step(step)),
        _ => None,
    };

    let mut error = None;
    e.each_child(&mut |child| match find_zoom_curve(child) {
        Ok(None) => {}
        Err(err) => error = Some(err),
        Ok(Some(child_curve)) => {
            if error.is_none() && found.is_none() {
                error = Some(ParsingError {
                    message: r#""zoom" expression may only be used as input to a top-level "step" or "interpolate" expression."#.to_owned(),
                    key: String::new(),
                });
            } else if error.is_some() || found != Some(child_curve) {
                error = Some(ParsingError {
                    message: r#"Only one zoom-based "step" or "interpolate" subexpression may be used in an expression."#.to_owned(),
                    key: String::new(),
                });
            }
        }
    });

    error.map_or(Ok(found), Err)
}

/// Find a zoom curve in the expression tree: the relevant step or
/// interpolate item, or `None` if the expression has none or uses `zoom`
/// invalidly, which is logged.
#[must_use]
pub fn find_zoom_curve_checked(e: &Expr) -> Option<ZoomCurve<'_>> {
    if !e.has(Dependency::ZOOM) {
        return None;
    }
    find_zoom_curve(e).unwrap_or_else(|err| {
        tracing::error!(target: log_target::STYLE, error = %err.message, "Invalid expression");
        None
    })
}