nu_protocol/value/custom_value.rs
1use std::{cmp::Ordering, fmt, path::Path};
2
3use crate::shell_error::generic::GenericError;
4use crate::{ShellError, Span, Spanned, Type, Value, ast::Operator, casing::Casing};
5
6/// Trait definition for a custom [`Value`](crate::Value) type
7#[typetag::serde(tag = "type")]
8pub trait CustomValue: fmt::Debug + Send + Sync {
9 /// Custom `Clone` implementation
10 ///
11 /// This can reemit a `Value::Custom(Self, span)` or materialize another representation
12 /// if necessary.
13 fn clone_value(&self, span: Span) -> Value;
14
15 //fn category(&self) -> Category;
16
17 /// The friendly type name to show for the custom value, e.g. in `describe` and in error
18 /// messages. This does not have to be the same as the name of the struct or enum, but
19 /// conventionally often is.
20 fn type_name(&self) -> String;
21
22 /// Converts the custom value to a base nushell value.
23 ///
24 /// This imposes the requirement that you can represent the custom value in some form using the
25 /// Value representations that already exist in nushell
26 fn to_base_value(&self, span: Span) -> Result<Value, ShellError>;
27
28 /// Any representation used to downcast object to its original type
29 fn as_any(&self) -> &dyn std::any::Any;
30
31 /// Any representation used to downcast object to its original type (mutable reference)
32 fn as_mut_any(&mut self) -> &mut dyn std::any::Any;
33
34 /// Follow cell path by numeric index (e.g. rows).
35 ///
36 /// Let `$val` be the custom value then these are the fields passed to this method:
37 /// ```text
38 /// ╭── index [path_span]
39 /// ┴
40 /// $val.0?
41 /// ──┬─ ┬
42 /// │ ╰── optional, `true` if present
43 /// ╰── self [self_span]
44 /// ```
45 fn follow_path_int(
46 &self,
47 self_span: Span,
48 index: usize,
49 path_span: Span,
50 optional: bool,
51 ) -> Result<Value, ShellError> {
52 let _ = (self_span, index, optional);
53 Err(ShellError::IncompatiblePathAccess {
54 type_name: self.type_name(),
55 span: path_span,
56 })
57 }
58
59 /// Follow cell path by string key (e.g. columns).
60 ///
61 /// Let `$val` be the custom value then these are the fields passed to this method:
62 /// ```text
63 /// ╭── column_name [path_span]
64 /// │ ╭── casing, `Casing::Insensitive` if present
65 /// ───┴── ┴
66 /// $val.column?!
67 /// ──┬─ ┬
68 /// │ ╰── optional, `true` if present
69 /// ╰── self [self_span]
70 /// ```
71 fn follow_path_string(
72 &self,
73 self_span: Span,
74 column_name: String,
75 path_span: Span,
76 optional: bool,
77 casing: Casing,
78 ) -> Result<Value, ShellError> {
79 let _ = (self_span, column_name, optional, casing);
80 Err(ShellError::IncompatiblePathAccess {
81 type_name: self.type_name(),
82 span: path_span,
83 })
84 }
85
86 /// ordering with other value (see [`std::cmp::PartialOrd`])
87 fn partial_cmp(&self, _other: &Value) -> Option<Ordering> {
88 None
89 }
90
91 /// Definition of an operation between the object that implements the trait
92 /// and another Value.
93 ///
94 /// The Operator enum is used to indicate the expected operation.
95 ///
96 /// Default impl raises [`ShellError::OperatorUnsupportedType`].
97 fn operation(
98 &self,
99 lhs_span: Span,
100 operator: Operator,
101 op: Span,
102 right: &Value,
103 ) -> Result<Value, ShellError> {
104 let _ = (lhs_span, right);
105 Err(ShellError::OperatorUnsupportedType {
106 op: operator,
107 unsupported: Type::Custom(self.type_name().into()),
108 op_span: op,
109 unsupported_span: lhs_span,
110 help: None,
111 })
112 }
113
114 /// Save custom value to disk.
115 ///
116 /// This method is used in `save` to save a custom value to disk.
117 /// This is done before opening any file, so saving can be handled differently.
118 ///
119 /// The default impl just returns an error.
120 fn save(
121 &self,
122 path: Spanned<&Path>,
123 value_span: Span,
124 save_span: Span,
125 ) -> Result<(), ShellError> {
126 let _ = path;
127 Err(ShellError::Generic(
128 GenericError::new(
129 "Cannot save custom value",
130 format!("Saving custom value {} failed", self.type_name()),
131 save_span,
132 )
133 .with_inner([ShellError::Generic(
134 GenericError::new(
135 "Custom value does not implement `save`",
136 format!("{} doesn't implement saving to disk", self.type_name()),
137 value_span,
138 )
139 .with_help("Check the plugin's documentation for this value type. It might use a different way to save."),
140 )]),
141 ))
142 }
143
144 /// For custom values in plugins: return `true` here if you would like to be notified when all
145 /// copies of this custom value are dropped in the engine.
146 ///
147 /// The notification will take place via `custom_value_dropped()` on the plugin type.
148 ///
149 /// The default is `false`.
150 fn notify_plugin_on_drop(&self) -> bool {
151 false
152 }
153
154 /// Returns an estimate of the memory size used by this CustomValue in bytes
155 ///
156 /// The default implementation returns the size of the trait object.
157 fn memory_size(&self) -> usize {
158 std::mem::size_of_val(self)
159 }
160
161 /// Returns `true` if this custom value should be iterable (like a list) when used with
162 /// commands like `each`, `where`, etc.
163 ///
164 /// When this returns `true`, the engine will call `to_base_value()` to convert the custom
165 /// value to a list before iteration. This is useful for lazy data structures like database
166 /// query builders that should behave like lists when iterated.
167 ///
168 /// The default is `false`.
169 #[deprecated(
170 since = "0.111.1",
171 note = "will be replaced by a new custom-value iterator system next release; \
172 avoid new uses unless you need current behavior"
173 )]
174 fn is_iterable(&self) -> bool {
175 false
176 }
177}