nushell/crates/nu_plugin_custom_values/src/cool_custom_value.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

158 lines
4.4 KiB
Rust

use nu_protocol::{
ast::{self, Math, Operator},
CustomValue, ShellError, Span, Type, Value,
};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct CoolCustomValue {
pub(crate) cool: String,
}
impl CoolCustomValue {
pub fn new(content: &str) -> Self {
Self {
cool: content.to_owned(),
}
}
pub fn into_value(self, span: Span) -> Value {
Value::custom(Box::new(self), span)
}
pub fn try_from_value(value: &Value) -> Result<Self, ShellError> {
let span = value.span();
match value {
Value::Custom { val, .. } => {
if let Some(cool) = val.as_any().downcast_ref::<Self>() {
Ok(cool.clone())
} else {
Err(ShellError::CantConvert {
to_type: "cool".into(),
from_type: "non-cool".into(),
span,
help: None,
})
}
}
x => Err(ShellError::CantConvert {
to_type: "cool".into(),
from_type: x.get_type().to_string(),
span,
help: None,
}),
}
}
}
#[typetag::serde]
impl CustomValue for CoolCustomValue {
fn clone_value(&self, span: Span) -> Value {
Value::custom(Box::new(self.clone()), span)
}
fn type_name(&self) -> String {
self.typetag_name().to_string()
}
fn to_base_value(&self, span: Span) -> Result<Value, ShellError> {
Ok(Value::string(
format!("I used to be a custom value! My data was ({})", self.cool),
span,
))
}
fn follow_path_int(
&self,
_self_span: Span,
index: usize,
path_span: Span,
) -> Result<Value, ShellError> {
if index == 0 {
Ok(Value::string(&self.cool, path_span))
} else {
Err(ShellError::AccessBeyondEnd {
max_idx: 0,
span: path_span,
})
}
}
fn follow_path_string(
&self,
self_span: Span,
column_name: String,
path_span: Span,
) -> Result<Value, ShellError> {
if column_name == "cool" {
Ok(Value::string(&self.cool, path_span))
} else {
Err(ShellError::CantFindColumn {
col_name: column_name,
span: Some(path_span),
src_span: self_span,
})
}
}
fn partial_cmp(&self, other: &Value) -> Option<Ordering> {
if let Value::Custom { val, .. } = other {
val.as_any()
.downcast_ref()
.and_then(|other: &CoolCustomValue| PartialOrd::partial_cmp(self, other))
} else {
None
}
}
fn operation(
&self,
lhs_span: Span,
operator: ast::Operator,
op_span: Span,
right: &Value,
) -> Result<Value, ShellError> {
match operator {
// Append the string inside `cool`
Operator::Math(Math::Concatenate) => {
if let Some(right) = right
.as_custom_value()
.ok()
.and_then(|c| c.as_any().downcast_ref::<CoolCustomValue>())
{
Ok(Value::custom(
Box::new(CoolCustomValue {
cool: format!("{}{}", self.cool, right.cool),
}),
op_span,
))
} else {
Err(ShellError::OperatorUnsupportedType {
op: Operator::Math(Math::Concatenate),
unsupported: right.get_type(),
op_span,
unsupported_span: right.span(),
help: None,
})
}
}
_ => Err(ShellError::OperatorUnsupportedType {
op: Operator::Math(Math::Concatenate),
unsupported: Type::Custom(self.type_name().into()),
op_span,
unsupported_span: lhs_span,
help: None,
}),
}
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}