use crate::conversion::Convertible;
use crate::expression::parse::{ParseResult, ParsingContext};
use crate::expression::type_::{self, Type};
use crate::expression::value::{Value, type_of};
use crate::expression::{EvalResult, EvaluationContext, EvaluationError, Expr, Node};
pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
let length = value.array_length();
if length != 2 {
ctx.error(format!("Expected one argument, but found {length} instead."));
return None;
}
let input = ctx.parse(&value.array_member(1), 1, None, None)?;
let t = &input.type_();
if !t.is_array() && *t != Type::String && *t != Type::Value {
ctx.error(format!("Expected argument of type string or array, but found {} instead.", type_::to_string(t)));
return None;
}
Some(Expr::new(Node::Length(Box::new(input))))
}
pub(crate) fn evaluate(input: &Expr, params: &EvaluationContext<'_>) -> EvalResult<f64> {
let value = input.evaluate_ref(params)?;
match &*value {
Value::String(s) => Ok(s.chars().count() as f64),
Value::Array(v) => Ok(v.len() as f64),
_ => Err(EvaluationError::new(format!(
"Expected value to be of type string or array, but found {} instead.",
type_::to_string(&type_of(&value))
))),
}
}
#[must_use]
pub(crate) fn char_byte_offset(s: &str, char_offset: usize) -> usize {
s.char_indices().nth(char_offset).map_or(s.len(), |(i, _)| i)
}