Skip to main content

nu_protocol/value/
custom_value.rs

1use crate::ast::PathMember;
2use crate::shell_error::generic::GenericError;
3use crate::value::CellPathMutation;
4use crate::{ShellError, Span, Spanned, Type, Value, ast::Operator, casing::Casing};
5use std::any::Any;
6use std::hash::Hasher;
7use std::{cmp::Ordering, fmt, path::Path};
8
9/// Trait definition for a custom [`Value`](crate::Value) type
10#[typetag::serde(tag = "type")]
11pub trait CustomValue: fmt::Debug + Send + Sync + Any {
12    /// Custom `Clone` implementation
13    ///
14    /// This can reemit a `Value::Custom(Self, span)` or materialize another representation
15    /// if necessary.
16    fn clone_value(&self, span: Span) -> Value;
17
18    //fn category(&self) -> Category;
19
20    /// The friendly type name to show for the custom value, e.g. in `describe` and in error
21    /// messages. This does not have to be the same as the name of the struct or enum, but
22    /// conventionally often is.
23    fn type_name(&self) -> String;
24
25    /// Converts the custom value to a base nushell value.
26    ///
27    /// This imposes the requirement that you can represent the custom value in some form using the
28    /// Value representations that already exist in nushell
29    fn to_base_value(&self, span: Span) -> Result<Value, ShellError>;
30
31    /// Any representation used to downcast object to its original type
32    fn as_any(&self) -> &dyn std::any::Any;
33
34    /// Any representation used to downcast object to its original type (mutable reference)
35    fn as_mut_any(&mut self) -> &mut dyn std::any::Any;
36
37    /// Follow cell path by numeric index (e.g. rows).
38    ///
39    /// Let `$val` be the custom value then these are the fields passed to this method:
40    /// ```text
41    ///      ╭── index [path_span]
42    ///      ┴
43    /// $val.0?
44    /// ──┬─  ┬
45    ///   │   ╰── optional, `true` if present
46    ///   ╰── self [self_span]
47    /// ```
48    fn follow_path_int(
49        &self,
50        self_span: Span,
51        index: usize,
52        path_span: Span,
53        optional: bool,
54    ) -> Result<Value, ShellError> {
55        let _ = (self_span, index, optional);
56        Err(ShellError::IncompatiblePathAccess {
57            type_name: self.type_name(),
58            span: path_span,
59        })
60    }
61
62    /// Follow cell path by string key (e.g. columns).
63    ///
64    /// Let `$val` be the custom value then these are the fields passed to this method:
65    /// ```text
66    ///         ╭── column_name [path_span]
67    ///         │   ╭── casing, `Casing::Insensitive` if present
68    ///      ───┴── ┴
69    /// $val.column?!
70    /// ──┬─       ┬
71    ///   │        ╰── optional, `true` if present
72    ///   ╰── self [self_span]
73    /// ```
74    fn follow_path_string(
75        &self,
76        self_span: Span,
77        column_name: String,
78        path_span: Span,
79        optional: bool,
80        casing: Casing,
81    ) -> Result<Value, ShellError> {
82        let _ = (self_span, column_name, optional, casing);
83        Err(ShellError::IncompatiblePathAccess {
84            type_name: self.type_name(),
85            span: path_span,
86        })
87    }
88
89    /// Update a value at the given cell path, returning a new `Value`.
90    ///
91    /// The default implementation converts to a base value, performs the mutation,
92    /// and returns the base value (losing the custom value wrapper). Override this
93    /// to preserve the custom value type through mutations.
94    fn update_data_at_cell_path(
95        &self,
96        cell_path: &[PathMember],
97        new_val: Value,
98        action: &CellPathMutation,
99        head: Span,
100    ) -> Result<Value, ShellError> {
101        let mut base = self.to_base_value(head)?;
102        base.mutate_data_at_cell_path(cell_path, new_val, action)?;
103        Ok(base)
104    }
105
106    /// ordering with other value (see [`std::cmp::PartialOrd`])
107    ///
108    /// Return `Some(Ordering::Equal)` for equal values even if the type has no order otherwise.
109    /// [`Value::strict_eq`] relies on it, so a value for which this returns `None` is not equal
110    /// to itself and gets its own `group-by` key.
111    fn partial_cmp(&self, _other: &Value) -> Option<Ordering> {
112        None
113    }
114
115    /// Hash this custom value.
116    ///
117    /// This backs `Hash` for [`Value::Custom`], which hashes [`type_name`](Self::type_name)
118    /// first. It must agree with [`partial_cmp`](Self::partial_cmp): two values of the same type
119    /// that compare equal must hash equally, so hash only fields that `partial_cmp` looks at.
120    /// The default hashes nothing more, which is always consistent but puts every value of the
121    /// type in one bucket. Do not hash [`to_base_value`](Self::to_base_value): it is not an
122    /// equality proxy, and for plugin values it panics or crosses into the plugin. Hash floats
123    /// with [`hash_f64`](crate::hash_f64), and stop a collection after
124    /// [`HASH_ITEM_LIMIT`](crate::HASH_ITEM_LIMIT) items.
125    ///
126    /// Plugin custom values keep the default. Their equality is decided by the plugin, and equal
127    /// values need not serialize to the same bytes.
128    fn hash_value(&self, _state: &mut dyn Hasher) {}
129
130    /// Definition of an operation between the object that implements the trait
131    /// and another Value.
132    ///
133    /// The Operator enum is used to indicate the expected operation.
134    ///
135    /// Default impl raises [`ShellError::OperatorUnsupportedType`].
136    fn operation(
137        &self,
138        lhs_span: Span,
139        operator: Operator,
140        op: Span,
141        right: &Value,
142    ) -> Result<Value, ShellError> {
143        let _ = (lhs_span, right);
144        Err(ShellError::OperatorUnsupportedType {
145            op: operator,
146            unsupported: Type::Custom(self.type_name().into()),
147            op_span: op,
148            unsupported_span: lhs_span,
149            help: None,
150        })
151    }
152
153    /// Save custom value to disk.
154    ///
155    /// This method is used in `save` to save a custom value to disk.
156    /// This is done before opening any file, so saving can be handled differently.
157    ///
158    /// The default impl just returns an error.
159    fn save(
160        &self,
161        path: Spanned<&Path>,
162        value_span: Span,
163        save_span: Span,
164    ) -> Result<(), ShellError> {
165        let _ = path;
166        Err(ShellError::Generic(
167            GenericError::new(
168                "Cannot save custom value",
169                format!("Saving custom value {} failed", self.type_name()),
170                save_span,
171            )
172            .with_inner([ShellError::Generic(
173                GenericError::new(
174                    "Custom value does not implement `save`",
175                    format!("{} doesn't implement saving to disk", self.type_name()),
176                    value_span,
177                )
178                .with_help("Check the plugin's documentation for this value type. It might use a different way to save."),
179            )]),
180        ))
181    }
182
183    /// For custom values in plugins: return `true` here if you would like to be notified when all
184    /// copies of this custom value are dropped in the engine.
185    ///
186    /// The notification will take place via `custom_value_dropped()` on the plugin type.
187    ///
188    /// The default is `false`.
189    fn notify_plugin_on_drop(&self) -> bool {
190        false
191    }
192
193    /// Returns an estimate of the memory size used by this CustomValue in bytes
194    ///
195    /// The default implementation returns the size of the trait object.
196    fn memory_size(&self) -> usize {
197        std::mem::size_of_val(self)
198    }
199
200    /// Returns `true` if this custom value should be iterable (like a list) when used with
201    /// commands like `each`, `where`, etc.
202    ///
203    /// When this returns `true`, the engine will call `to_base_value()` to convert the custom
204    /// value to a list before iteration. This is useful for lazy data structures like database
205    /// query builders that should behave like lists when iterated.
206    ///
207    /// The default is `false`.
208    fn is_iterable(&self) -> bool {
209        false
210    }
211}