rune/any.rs
1use core::any;
2
3use crate::compile::Named;
4use crate::runtime::{AnyTypeInfo, Dismantle, TypeHash};
5
6/// The trait implemented for types which can be used inside of Rune.
7///
8/// This can only be implemented correctly through the [`Any`] derive.
9/// Implementing it manually is not supported.
10///
11/// Rune only supports two types, *built-in* types like [`i64`] and *external*
12/// types which derive `Any`. Before they can be used they must be registered in
13/// [`Context::install`] through a [`Module`].
14///
15/// Every type which can be stored in the virtual machine has to say how it is
16/// taken apart, which is why [`Dismantle`] is required here. The derive writes
17/// it: a type which does not hold any [`Value`]s hands nothing over and is
18/// dropped in place, and a type which does marks the fields which hold them
19/// with `#[rune(dismantle)]`. See [`Dismantle`] for why this matters.
20///
21/// This is typically used in combination with declarative macros to register
22/// functions and macros, such as [`rune::function`].
23///
24/// [`Value`]: crate::runtime::Value
25///
26/// [`AnyObj`]: crate::runtime::AnyObj
27/// [`Context::install`]: crate::Context::install
28/// [`Module`]: crate::Module
29/// [`String`]: std::string::String
30/// [`rune::function`]: macro@crate::function
31/// [`rune::macro_`]: macro@crate::macro_
32/// [`Any`]: derive@crate::Any
33///
34/// # Examples
35///
36/// ```
37/// use rune::Any;
38///
39/// #[derive(Any)]
40/// struct Npc {
41/// #[rune(get)]
42/// health: u32,
43/// }
44///
45/// impl Npc {
46/// /// Construct a new NPC.
47/// #[rune::function(path = Self::new)]
48/// fn new(health: u32) -> Self {
49/// Self {
50/// health
51/// }
52/// }
53///
54/// /// Damage the NPC with the given `amount`.
55/// #[rune::function]
56/// fn damage(&mut self, amount: u32) {
57/// self.health -= amount;
58/// }
59/// }
60///
61/// fn install() -> Result<rune::Module, rune::ContextError> {
62/// let mut module = rune::Module::new();
63/// module.ty::<Npc>()?;
64/// module.function_meta(Npc::new)?;
65/// module.function_meta(Npc::damage)?;
66/// Ok(module)
67/// }
68/// ```
69pub trait Any: TypeHash + Named + any::Any + Dismantle {
70 /// The compile-time type information know for the type.
71 const ANY_TYPE_INFO: AnyTypeInfo = AnyTypeInfo::new(Self::full_name, Self::HASH);
72}
73
74/// Trait implemented for types which can be automatically converted to a
75/// [`Value`].
76///
77/// We can't use a blanked implementation over `T: Any` because it only governs
78/// what can be stored in any [`AnyObj`].
79///
80/// This trait in contrast is selectively implemented for types which we want to
81/// generate [`ToValue`] and [`FromValue`] implementations for.
82///
83/// [`Value`]: crate::runtime::Value
84/// [`AnyObj`]: crate::runtime::AnyObj
85/// [`ToValue`]: crate::runtime::ToValue
86/// [`FromValue`]: crate::runtime::FromValue
87///
88/// Note that you are *not* supposed to implement this directly. Make use of the
89/// [`Any`] derive instead.
90///
91/// [`Any`]: derive@crate::Any
92pub trait AnyMarker: Any {}
93
94/// Macro to mark a value as external, which will implement all the appropriate
95/// traits.
96///
97/// This is required to support the external type as a type argument in a
98/// registered function.
99///
100/// <br>
101///
102/// ## Container attributes
103///
104/// <br>
105///
106/// ### `#[rune(item = <path>)]`
107///
108/// Specify the item prefix which contains this time.
109///
110/// This is required in order to calculate the correct type hash, if this is
111/// omitted and the item is defined in a nested module the type hash won't match
112/// the expected path hash.
113///
114/// ```
115/// use rune::{Any, Module};
116///
117/// #[derive(Any)]
118/// #[rune(item = ::process)]
119/// struct Process {
120/// /* .. */
121/// }
122///
123/// let mut m = Module::with_crate("process")?;
124/// m.ty::<Process>()?;
125/// # Ok::<_, rune::ContextError>(())
126/// ```
127///
128/// <br>
129///
130/// ### `#[rune(name = <ident>)]` attribute
131///
132/// The name of a type defaults to its identifiers, so `struct Foo {}` would be
133/// given the name `Foo`.
134///
135/// This can be overrided with the `#[rune(name = <ident>)]` attribute:
136///
137/// ```
138/// use rune::{Any, Module};
139///
140/// #[derive(Any)]
141/// #[rune(name = Bar)]
142/// struct Foo {
143/// }
144///
145/// let mut m = Module::new();
146/// m.ty::<Foo>()?;
147/// # Ok::<_, rune::ContextError>(())
148/// ```
149///
150/// <br>
151///
152/// ### `#[rune(empty)]`, `#[rune(unnamed(<int>))]`
153///
154/// This attribute controls how the metadata of fields are handled in the type.
155///
156/// By default fields are registered depending on the type of structure or enum
157/// being registered. This prevents the metadata from being further customized
158/// through methods such as [`TypeMut::make_empty_struct`] since that would
159/// result in duplicate metadata being registered.
160///
161/// To avoid this behavior, the `#[rune(fields)]` attribute can be used which
162/// suppressed any field metadata from being generated for `none` or customized
163/// like `empty`. If set to `none` then it leaves the field metadata free to be
164/// configured manually during [`Module::ty`] setup.
165///
166/// Registering a type like this allows it to be used like an empty struct like
167/// `let v = Struct;` despite having fields:
168///
169/// ```
170/// use rune::{Any, Module};
171///
172/// #[derive(Any)]
173/// #[rune(empty, constructor = Struct::new)]
174/// struct Struct {
175/// field: u32,
176/// }
177///
178/// impl Struct {
179/// fn new() -> Self {
180/// Self { field: 42 }
181/// }
182/// }
183///
184/// let mut m = Module::new();
185/// m.ty::<Struct>()?;
186/// # Ok::<_, rune::ContextError>(())
187/// ```
188///
189/// Support for an unnamed struct:
190///
191/// ```
192/// use rune::{Any, Module};
193///
194/// #[derive(Any)]
195/// #[rune(unnamed(2), constructor = Struct::new)]
196/// struct Struct {
197/// a: u32,
198/// b: u32,
199/// }
200///
201/// impl Struct {
202/// fn new(a: u32, b: u32) -> Self {
203/// Self { a, b }
204/// }
205/// }
206///
207/// let mut m = Module::new();
208/// m.ty::<Struct>()?;
209/// # Ok::<_, rune::ContextError>(())
210/// ```
211///
212///
213/// <br>
214///
215/// ### `#[rune(constructor)]`
216///
217/// This allows for specifying that a type has a rune-visible constructor, and
218/// which method should be called to construct the value.
219///
220/// A constructor in this instance means supporting expressions such as:
221///
222/// * `Struct { field: 42 }` for named structs.
223/// * `Struct(42)` for unnamed structs.
224/// * `Struct` for empty structs.
225///
226/// By default the attribute will generate a constructor out of every field
227/// which is marked with `#[rune(get)]`. The remaining fields must then
228/// implement [`Default`].
229///
230/// ```
231/// use rune::{Any, Module};
232///
233/// #[derive(Any)]
234/// #[rune(constructor)]
235/// struct Struct {
236/// #[rune(get)]
237/// a: u32,
238/// b: u32,
239/// }
240///
241/// let mut m = Module::new();
242/// m.ty::<Struct>()?;
243/// # Ok::<_, rune::ContextError>(())
244/// ```
245///
246/// For fine-grained control over the constructor, `#[rune(constructor =
247/// <path>)]` can be used.
248///
249/// ```
250/// use rune::{Any, Module};
251///
252/// #[derive(Any)]
253/// #[rune(empty, constructor = Struct::new)]
254/// struct Struct {
255/// field: u32,
256/// }
257///
258/// impl Struct {
259/// fn new() -> Self {
260/// Self { field: 42 }
261/// }
262/// }
263///
264/// let mut m = Module::new();
265/// m.ty::<Struct>()?;
266/// # Ok::<_, rune::ContextError>(())
267/// ```
268///
269/// ### `#[rune(dismantle)]`
270///
271/// Every type stored in the virtual machine has to say how it is taken apart,
272/// which the derive writes as an implementation of [`Dismantle`]. A type which
273/// does not hold any [`Value`]s hands nothing over and is dropped in place,
274/// which is what is written unless this attribute says otherwise.
275///
276/// Marking the type says that it implements [`Dismantle`] itself, which is what
277/// a collection or an iterator which holds what it walks through a guard has to
278/// do:
279///
280/// ```
281/// use rune::Any;
282/// use rune::runtime::{Dismantle, Handover, Value};
283///
284/// #[derive(Any)]
285/// #[rune(dismantle)]
286/// struct List {
287/// values: Vec<Value>,
288/// }
289///
290/// impl Dismantle for List {
291/// fn dismantle(&mut self, out: &mut Handover<'_>) {
292/// for value in self.values.drain(..) {
293/// out.push(value);
294/// }
295/// }
296/// }
297/// ```
298///
299/// Marking fields instead writes it from them, in the order they are declared.
300/// This is the common case - see [`Dismantle`] for why a type which holds
301/// values has to hand them over.
302///
303/// ```
304/// use rune::Any;
305/// use rune::Value;
306///
307/// #[derive(Any)]
308/// struct Pair {
309/// #[rune(dismantle)]
310/// first: Value,
311/// #[rune(dismantle)]
312/// second: Option<Value>,
313/// count: u32,
314/// }
315/// ```
316///
317/// [`Dismantle`]: crate::runtime::Dismantle
318/// [`Value`]: crate::runtime::Value
319///
320/// ## Field attributes
321///
322/// <br>
323///
324/// ### Field functions
325///
326/// Field functions are special operations which operate on fields. These are
327/// distinct from associated functions, because they are invoked by using the
328/// operation associated with the kind of the field function.
329///
330/// The most common forms of fields functions are *getters* and *setters*, which
331/// are defined through the [`Protocol::GET`] and [`Protocol::SET`] protocols.
332///
333/// The `Any` derive can also generate default implementations of these through
334/// various `#[rune(...)]` attributes:
335///
336/// ```rust
337/// use rune::{Any, Module};
338///
339/// #[derive(Any)]
340/// struct Struct {
341/// #[rune(get, set, add_assign, copy)]
342/// number: i64,
343/// #[rune(get, set)]
344/// string: String,
345/// }
346///
347/// let mut m = Module::new();
348/// m.ty::<Struct>()?;
349/// # Ok::<_, rune::ContextError>(())
350/// ```
351///
352/// Once registered, this allows `External` to be used like this in Rune:
353///
354/// ```rune
355/// pub fn main(external) {
356/// external.number = external.number + 1;
357/// external.number += 1;
358/// external.string = `${external.string} World`;
359/// }
360/// ```
361///
362/// The full list of available field functions and their corresponding
363/// attributes are:
364///
365/// | Protocol | Attribute | |
366/// |-|-|-|
367/// | [`Protocol::GET`] | `#[rune(get)]` | For getters, like `external.field`. |
368/// | [`Protocol::SET`] | `#[rune(set)]` | For setters, like `external.field = 42`. |
369/// | [`Protocol::ADD_ASSIGN`] | `#[rune(add_assign)]` | The `+=` operation. |
370/// | [`Protocol::SUB_ASSIGN`] | `#[rune(sub_assign)]` | The `-=` operation. |
371/// | [`Protocol::MUL_ASSIGN`] | `#[rune(mul_assign)]` | The `*=` operation. |
372/// | [`Protocol::DIV_ASSIGN`] | `#[rune(div_assign)]` | The `/=` operation. |
373/// | [`Protocol::BIT_AND_ASSIGN`] | `#[rune(bit_and_assign)]` | The `&=` operation. |
374/// | [`Protocol::BIT_OR_ASSIGN`] | `#[rune(bit_or_assign)]` | The bitwise or operation. |
375/// | [`Protocol::BIT_XOR_ASSIGN`] | `#[rune(bit_xor_assign)]` | The `^=` operation. |
376/// | [`Protocol::SHL_ASSIGN`] | `#[rune(shl_assign)]` | The `<<=` operation. |
377/// | [`Protocol::SHR_ASSIGN`] | `#[rune(shr_assign)]` | The `>>=` operation. |
378/// | [`Protocol::REM_ASSIGN`] | `#[rune(rem_assign)]` | The `%=` operation. |
379///
380/// The manual way to register these functions is to use the new
381/// `Module::field_function` function. This clearly showcases that there's no
382/// relationship between the field used and the function registered:
383///
384/// ```rust
385/// use rune::{Any, Module};
386/// use rune::runtime::Protocol;
387///
388/// #[derive(Any)]
389/// struct External {
390/// }
391///
392/// impl External {
393/// fn field_get(&self) -> String {
394/// String::from("Hello World")
395/// }
396/// }
397///
398/// let mut module = Module::new();
399/// module.field_function(&Protocol::GET, "field", External::field_get)?;
400/// # Ok::<_, rune::support::Error>(())
401/// ```
402///
403/// Would allow for this in Rune:
404///
405/// ```rune
406/// pub fn main(external) {
407/// println!("{}", external.field);
408/// }
409/// ```
410///
411/// ### Customizing how fields are cloned with `#[rune(get)]`
412///
413/// In order to return a value through `#[rune(get)]`, the value has to be
414/// cloned.
415///
416/// By default, this is done through the [`TryClone` trait], but its behavior
417/// can be customized through the following attributes:
418///
419/// <br>
420///
421/// ### `#[rune(copy)]`
422///
423/// This indicates that the field is `Copy`.
424///
425/// <br>
426///
427/// ### `#[rune(clone)]`
428///
429/// This indicates that the field should use `std::clone::Clone` to clone the
430/// value. Note that this effecitvely means that the memory the value uses
431/// during cloning is *not* tracked and should be avoided in favor of using
432/// [`rune::alloc`] and the [`TryClone` trait] without good reason.
433///
434/// <br>
435///
436/// ### `#[rune(clone_with = <path>)]`
437///
438/// This specified a custom method that should be used to clone the value.
439///
440/// ```rust
441/// use rune::Any;
442/// use rune::sync::Arc;
443///
444/// #[derive(Any)]
445/// struct External {
446/// #[rune(get, clone_with = Inner::clone)]
447/// field: Inner,
448/// }
449///
450/// #[derive(Any, Clone)]
451/// struct Inner {
452/// name: Arc<String>,
453/// }
454/// ```
455///
456/// <br>
457///
458/// ### `#[rune(try_clone_with = <path>)]`
459///
460/// This specified a custom method that should be used to clone the value.
461///
462/// ```rust
463/// use rune::Any;
464/// use rune::alloc::prelude::*;
465///
466/// #[derive(Any)]
467/// struct External {
468/// #[rune(get, try_clone_with = String::try_clone)]
469/// field: String,
470/// }
471/// ```
472///
473/// [`Module::ty`]: crate::Module::ty
474/// [`Protocol::ADD_ASSIGN`]: crate::runtime::Protocol::ADD_ASSIGN
475/// [`Protocol::BIT_AND_ASSIGN`]: crate::runtime::Protocol::BIT_AND_ASSIGN
476/// [`Protocol::BIT_OR_ASSIGN`]: crate::runtime::Protocol::BIT_OR_ASSIGN
477/// [`Protocol::BIT_XOR_ASSIGN`]: crate::runtime::Protocol::BIT_XOR_ASSIGN
478/// [`Protocol::DIV_ASSIGN`]: crate::runtime::Protocol::DIV_ASSIGN
479/// [`Protocol::GET`]: crate::runtime::Protocol::GET
480/// [`Protocol::MUL_ASSIGN`]: crate::runtime::Protocol::MUL_ASSIGN
481/// [`Protocol::REM_ASSIGN`]: crate::runtime::Protocol::REM_ASSIGN
482/// [`Protocol::SET`]: crate::runtime::Protocol::SET
483/// [`Protocol::SHL_ASSIGN`]: crate::runtime::Protocol::SHL_ASSIGN
484/// [`Protocol::SHR_ASSIGN`]: crate::runtime::Protocol::SHR_ASSIGN
485/// [`Protocol::SUB_ASSIGN`]: crate::runtime::Protocol::SUB_ASSIGN
486/// [`rune::alloc`]: crate::alloc
487/// [`TryClone` trait]: crate::alloc::clone::TryClone
488/// [`TypeMut::make_empty_struct`]: crate::module::TypeMut::make_empty_struct
489pub use rune_macros::Any;