nushell/crates/nu-command/src/math/reducers.rs
Ian Manske 62e56d3581
Rework operator type errors (#14429)
# Description

This PR adds two new `ParseError` and `ShellError` cases for type errors
relating to operators.
- `OperatorUnsupportedType` is used when a type is not supported by an
operator in any way, shape, or form. E.g., `+` does not support `bool`.
- `OperatorIncompatibleTypes` is used when a operator is used with types
it supports, but the combination of types provided cannot be used
together. E.g., `filesize + duration` is not a valid combination.

The other preexisting error cases related to operators have been removed
and replaced with the new ones above. Namely:

- `ShellError::OperatorMismatch`
- `ShellError::UnsupportedOperator`
- `ParseError::UnsupportedOperationLHS`
- `ParseError::UnsupportedOperationRHS`
- `ParseError::UnsupportedOperationTernary`

# User-Facing Changes

- `help operators` now lists the precedence of `not` as 55 instead of 0
(above the other boolean operators). Fixes #13675.
- `math median` and `math mode` now ignore NaN values so that `[NaN NaN]
| math median` and `[NaN NaN] | math mode` no longer trigger a type
error. Instead, it's now an empty input error. Fixing this in earnest
can be left for a future PR.
- Comparisons with `nan` now return false instead of causing an error.
E.g., `1 == nan` is now `false`.
- All the operator type errors have been standardized and reworked. In
particular, they can now have a help message, which is currently used
for types errors relating to `++`.

```nu
[1] ++ 2
```
```
Error: nu::parser::operator_unsupported_type

  × The '++' operator does not work on values of type 'int'.
   ╭─[entry #1:1:5]
 1 │ [1] ++ 2
   ·     ─┬ ┬
   ·      │ ╰── int
   ·      ╰── does not support 'int'
   ╰────
  help: if you meant to append a value to a list or a record to a table, use the `append` command or wrap the value in a list. For example: `$list ++ $value` should be
        `$list ++ [$value]` or `$list | append $value`.
```
2025-02-12 20:03:40 -08:00

144 lines
4.6 KiB
Rust

use nu_protocol::{ShellError, Span, Value};
use std::cmp::Ordering;
pub enum Reduce {
Summation,
Product,
Minimum,
Maximum,
}
pub type ReducerFunction =
Box<dyn Fn(Value, Vec<Value>, Span, Span) -> Result<Value, ShellError> + Send + Sync + 'static>;
pub fn reducer_for(command: Reduce) -> ReducerFunction {
match command {
Reduce::Summation => Box::new(|_, values, span, head| sum(values, span, head)),
Reduce::Product => Box::new(|_, values, span, head| product(values, span, head)),
Reduce::Minimum => Box::new(|_, values, span, head| min(values, span, head)),
Reduce::Maximum => Box::new(|_, values, span, head| max(values, span, head)),
}
}
pub fn max(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let mut biggest = data
.first()
.ok_or_else(|| ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
})?
.clone();
for value in &data {
if value.partial_cmp(&biggest) == Some(Ordering::Greater) {
biggest = value.clone();
}
}
Ok(biggest)
}
pub fn min(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let mut smallest = data
.first()
.ok_or_else(|| ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
})?
.clone();
for value in &data {
if value.partial_cmp(&smallest) == Some(Ordering::Less) {
smallest = value.clone();
}
}
Ok(smallest)
}
pub fn sum(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let initial_value = data.first();
let mut acc = match initial_value {
Some(v) => {
let span = v.span();
match v {
Value::Filesize { .. } => Ok(Value::filesize(0, span)),
Value::Duration { .. } => Ok(Value::duration(0, span)),
Value::Int { .. } | Value::Float { .. } => Ok(Value::int(0, span)),
_ => Ok(Value::nothing(head)),
}
}
None => Err(ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
}),
}?;
for value in &data {
match value {
Value::Int { .. }
| Value::Float { .. }
| Value::Filesize { .. }
| Value::Duration { .. } => {
acc = acc.add(head, value, head)?;
}
Value::Error { error, .. } => return Err(*error.clone()),
other => {
return Err(ShellError::UnsupportedInput {
msg: format!("Attempted to compute the sum of a value '{}' that cannot be summed with a type of `{}`.",
other.coerce_string()?, other.get_type()),
input: "value originates from here".into(),
msg_span: head,
input_span: other.span(),
});
}
}
}
Ok(acc)
}
pub fn product(data: Vec<Value>, span: Span, head: Span) -> Result<Value, ShellError> {
let initial_value = data.first();
let mut acc = match initial_value {
Some(v) => {
let span = v.span();
match v {
Value::Int { .. } | Value::Float { .. } => Ok(Value::int(1, span)),
_ => Ok(Value::nothing(head)),
}
}
None => Err(ShellError::UnsupportedInput {
msg: "Empty input".to_string(),
input: "value originates from here".into(),
msg_span: head,
input_span: span,
}),
}?;
for value in &data {
match value {
Value::Int { .. } | Value::Float { .. } => {
acc = acc.mul(head, value, head)?;
}
Value::Error { error, .. } => return Err(*error.clone()),
other => {
return Err(ShellError::UnsupportedInput {
msg: format!("Attempted to compute the product of a value '{}' that cannot be multiplied with a type of `{}`.",
other.coerce_string()?, other.get_type()),
input: "value originates from here".into(),
msg_span: head,
input_span: other.span(),
});
}
}
}
Ok(acc)
}