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