nushell/crates/nu_plugin_custom_values/src/cool_custom_value.rs
Piepmatz b79a2255d2
Add derive macros for FromValue and IntoValue to ease the use of Values in Rust code (#13031)
# Description
After discussing with @sholderbach the cumbersome usage of
`nu_protocol::Value` in Rust, I created a derive macro to simplify it.
I’ve added a new crate called `nu-derive-value`, which includes two
macros, `IntoValue` and `FromValue`. These are re-exported in
`nu-protocol` and should be encouraged to be used via that re-export.

The macros ensure that all types can easily convert from and into
`Value`. For example, as a plugin author, you can define your plugin
configuration using a Rust struct and easily convert it using
`FromValue`. This makes plugin configuration less of a hassle.

I introduced the `IntoValue` trait for a standardized approach to
converting values into `Value` (and a fallible variant `TryIntoValue`).
This trait could potentially replace existing `into_value` methods.
Along with this, I've implemented `FromValue` for several standard types
and refined other implementations to use blanket implementations where
applicable.

I made these design choices with input from @devyn.

There are more improvements possible, but this is a solid start and the
PR is already quite substantial.

# User-Facing Changes

For `nu-protocol` users, these changes simplify the handling of
`Value`s. There are no changes for end-users of nushell itself.

# Tests + Formatting
Documenting the macros itself is not really possible, as they cannot
really reference any other types since they are the root of the
dependency graph. The standard library has the same problem
([std::Debug](https://doc.rust-lang.org/stable/std/fmt/derive.Debug.html)).
However I documented the `FromValue` and `IntoValue` traits completely.

For testing, I made of use `proc-macro2` in the derive macro code. This
would allow testing the generated source code. Instead I just tested
that the derived functionality is correct. This is done in
`nu_protocol::value::test_derive`, as a consumer of `nu-derive-value`
needs to do the testing of the macro usage. I think that these tests
should provide a stable baseline so that users can be sure that the impl
works.

# After Submitting
With these macros available, we can probably use them in some examples
for plugins to showcase the use of them.
2024-06-17 16:05:11 -07:00

152 lines
4.2 KiB
Rust

use nu_protocol::{ast, CustomValue, ShellError, Span, 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`
ast::Operator::Math(ast::Math::Append) => {
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::OperatorMismatch {
op_span,
lhs_ty: self.typetag_name().into(),
lhs_span,
rhs_ty: right.get_type().to_string(),
rhs_span: right.span(),
})
}
}
_ => Err(ShellError::UnsupportedOperator {
operator,
span: op_span,
}),
}
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}