Skip to main content

rune/
lib.rs

1//! <img alt="rune logo" src="https://raw.githubusercontent.com/rune-rs/rune/main/assets/icon.png" />
2//! <br>
3//! <a href="https://github.com/rune-rs/rune"><img alt="github" src="https://img.shields.io/badge/github-rune--rs/rune-8da0cb?style=for-the-badge&logo=github" height="20"></a>
4//! <a href="https://crates.io/crates/rune"><img alt="crates.io" src="https://img.shields.io/crates/v/rune.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20"></a>
5//! <a href="https://docs.rs/rune"><img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-rune-66c2a5?style=for-the-badge&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20"></a>
6//! <a href="https://discord.gg/v5AeNkT"><img alt="chat on discord" src="https://img.shields.io/discord/558644981137670144.svg?logo=discord&style=flat-square" height="20"></a>
7//! <br>
8//! Minimum support: Rust <b>1.95+</b>.
9//! <br>
10//! <br>
11//! <a href="https://rune-rs.github.io"><b>Visit the site 🌐</b></a>
12//! &mdash;
13//! <a href="https://rune-rs.github.io/book/"><b>Read the book 📖</b></a>
14//! <br>
15//! <br>
16//!
17//! The Rune Language, an embeddable dynamic programming language for Rust.
18//!
19//! <br>
20//!
21//! ## Contributing
22//!
23//! If you want to help out, please have a look at [Open Issues].
24//!
25//! <br>
26//!
27//! ## Highlights of Rune
28//!
29//! * Run simple [Scripts 📖][support-scripts].
30//! * Runs a compact representation of the language on top of an efficient
31//!   [stack-based virtual machine][support-virtual-machine].
32//! * Clean [Rust integration 💻][support-rust-integration].
33//! * [Multithreaded 📖][support-multithreading] execution.
34//! * [Hot reloading 📖][support-hot-reloading].
35//! * Memory safe through [reference counting 📖][support-reference-counted].
36//! * [Awesome macros 📖][support-macros] and [Template literals 📖][support-templates].
37//! * [Try operators 📖][support-try] and [Pattern matching 📖][support-patterns].
38//! * [Structs and enums 📖][support-structs] with associated data and
39//!   functions.
40//! * Dynamic containers like [vectors 📖][support-dynamic-vectors], [objects
41//!   📖][support-anon-objects], and [tuples 📖][support-anon-tuples] all with
42//!   out-of-the-box [serde support 💻][support-serde].
43//! * First-class [async support 📖][support-async] with [Generators 📖][support-generators].
44//! * Dynamic [instance functions 📖][support-instance-functions].
45//! * [Stack isolation 📖][support-stack-isolation] between function calls.
46//!
47//! <br>
48//!
49//! ## Rune scripts
50//!
51//! You can run Rune programs with the bundled CLI:
52//!
53//! ```text
54//! cargo run --bin rune -- run scripts/hello_world.rn
55//! ```
56//!
57//! If you want to see detailed diagnostics of your program while it's running,
58//! you can use:
59//!
60//! ```text
61//! cargo run --bin rune -- run scripts/hello_world.rn --dump --trace
62//! ```
63//!
64//! See `--help` for more information.
65//!
66//! <br>
67//!
68//! ## Running scripts from Rust
69//!
70//! > You can find more examples [in the `examples` folder].
71//!
72//! The following is a complete example, including rich diagnostics using
73//! [`termcolor`]. It can be made much simpler if this is not needed.
74//!
75//! [`termcolor`]: https://docs.rs/termcolor
76//!
77//! ```no_run
78//! use rune::{Context, Diagnostics, Source, Sources, Vm};
79//! use rune::termcolor::{ColorChoice, StandardStream};
80//! use rune::sync::Arc;
81//!
82//! let context = Context::with_default_modules()?;
83//!
84//! let mut sources = Sources::new();
85//! sources.insert(Source::memory("pub fn add(a, b) { a + b }")?);
86//!
87//! let mut diagnostics = Diagnostics::new();
88//!
89//! let result = rune::prepare(&mut sources)
90//!     .with_context(&context)
91//!     .with_diagnostics(&mut diagnostics)
92//!     .build_vm();
93//!
94//! if !diagnostics.is_empty() {
95//!     let mut writer = StandardStream::stderr(ColorChoice::Always);
96//!     diagnostics.emit(&mut writer, &sources)?;
97//! }
98//!
99//! let mut vm = result?;
100//!
101//! let output = vm.call(["add"], (10i64, 20i64))?;
102//! let output: i64 = rune::from_value(output)?;
103//!
104//! println!("{}", output);
105//! # Ok::<_, rune::support::Error>(())
106//! ```
107//!
108//! [in the `examples` folder]: https://github.com/rune-rs/rune/tree/main/examples/examples
109//! [Open Issues]: https://github.com/rune-rs/rune/issues
110//! [support-anon-objects]: https://rune-rs.github.io/book/objects.html
111//! [support-anon-tuples]: https://rune-rs.github.io/book/tuples.html
112//! [support-async]: https://rune-rs.github.io/book/async.html
113//! [support-dynamic-vectors]: https://rune-rs.github.io/book/vectors.html
114//! [support-generators]: https://rune-rs.github.io/book/generators.html
115//! [support-hot-reloading]: https://rune-rs.github.io/book/hot_reloading.html
116//! [support-instance-functions]: https://rune-rs.github.io/book/instance_functions.html
117//! [support-macros]: https://rune-rs.github.io/book/macros.html
118//! [support-multithreading]: https://rune-rs.github.io/book/multithreading.html
119//! [support-patterns]: https://rune-rs.github.io/book/pattern_matching.html
120//! [support-reference-counted]: https://rune-rs.github.io/book/variables.html
121//! [support-rust-integration]: https://github.com/rune-rs/rune/tree/main/crates/rune-modules
122//! [support-scripts]: https://rune-rs.github.io/book/scripts.html
123//! [support-serde]: https://github.com/rune-rs/rune/blob/main/crates/rune-modules/src/json.rs
124//! [support-stack-isolation]: https://rune-rs.github.io/book/call_frames.html
125//! [support-structs]: https://rune-rs.github.io/book/structs.html
126//! [support-templates]: https://rune-rs.github.io/book/template_literals.html
127//! [support-try]: https://rune-rs.github.io/book/try_operator.html
128//! [support-virtual-machine]: https://rune-rs.github.io/book/the_stack.html
129
130#![allow(clippy::branches_sharing_code)]
131#![allow(clippy::enum_variant_names)]
132#![allow(clippy::match_like_matches_macro)]
133#![allow(clippy::module_inception)]
134#![allow(clippy::needless_doctest_main)]
135#![allow(clippy::self_named_constructors)]
136#![allow(clippy::should_implement_trait)]
137#![allow(clippy::too_many_arguments)]
138#![allow(clippy::type_complexity)]
139#![cfg_attr(rune_docsrs, feature(doc_cfg))]
140#![deny(missing_docs)]
141#![deny(rustdoc::broken_intra_doc_links)]
142#![deny(rustdoc::private_doc_tests)]
143#![no_std]
144
145#[cfg(feature = "std")]
146#[macro_use]
147extern crate std;
148
149// This is here for forward compatibility when we can support allocation-free
150// execution.
151#[cfg(not(feature = "alloc"))]
152compile_error!("The `alloc` feature is currently required to build rune, but will change for parts of rune in the future.");
153
154#[macro_use]
155extern crate alloc as rust_alloc;
156
157/// A macro that can be used to construct a [Span][crate::ast::Span] that can be
158/// pattern matched over.
159///
160/// # Examples
161///
162/// ```
163/// use rune::ast::Span;
164/// use rune::span;
165///
166/// let span = Span::new(42, 84);
167/// assert!(matches!(span, span!(42, 84)));
168/// ```
169#[macro_export]
170#[doc(hidden)]
171macro_rules! span {
172    ($start:expr, $end:expr) => {
173        $crate::ast::Span {
174            start: $crate::ast::ByteIndex($start),
175            end: $crate::ast::ByteIndex($end),
176        }
177    };
178}
179
180pub mod alloc;
181#[doc(inline)]
182pub use rune_alloc::sync;
183
184/// Helper prelude for `#[no_std]` support.
185pub mod no_std;
186
187#[macro_use]
188mod internal_macros;
189pub(crate) use self::internal_macros::{async_vm_try, declare_dyn_fn, declare_dyn_trait, vm_error};
190
191mod exported_macros;
192#[doc(inline)]
193#[allow(deprecated)]
194pub use self::exported_macros::{docstring, nested_try, vm_panic, vm_try, vm_write};
195
196#[macro_use]
197pub mod ast;
198
199#[cfg(feature = "fmt")]
200#[cfg_attr(rune_docsrs, doc(cfg(feature = "fmt")))]
201pub mod fmt;
202
203#[cfg(feature = "emit")]
204#[cfg_attr(rune_docsrs, doc(cfg(feature = "emit")))]
205#[doc(inline)]
206pub use ::codespan_reporting::term::termcolor;
207
208pub(crate) mod any;
209#[doc(inline)]
210pub use self::any::Any;
211
212mod build;
213pub use self::build::{prepare, Build, BuildError};
214
215pub mod compile;
216#[doc(inline)]
217pub use self::compile::{Context, ContextError, Options};
218
219pub mod item;
220#[doc(inline)]
221pub use self::item::{Item, ItemBuf};
222
223#[doc(hidden)]
224mod function_meta;
225
226mod function;
227
228pub mod module;
229#[doc(inline)]
230pub use self::module::module::Module;
231
232pub mod diagnostics;
233#[doc(inline)]
234pub use self::diagnostics::Diagnostics;
235
236pub mod hash;
237#[doc(inline)]
238pub use self::hash::{Hash, NonZeroHash, ToTypeHash};
239
240mod hashbrown;
241
242mod params;
243pub use self::params::Params;
244
245mod hir;
246
247mod indexing;
248
249pub mod macros;
250
251pub mod modules;
252
253pub mod parse;
254
255pub(crate) mod grammar;
256
257pub mod query;
258
259pub mod runtime;
260#[doc(inline)]
261pub use self::runtime::{
262    from_const_value, from_value, to_const_value, to_value, FromConstValue, FromValue, Mut, Ref,
263    ToConstValue, ToValue, TypeHash, Unit, Value, Vm, VmError,
264};
265
266mod shared;
267
268pub mod source;
269#[doc(inline)]
270pub use self::source::Source;
271
272#[macro_use]
273mod sources;
274#[doc(inline)]
275pub use self::sources::{SourceId, Sources};
276
277mod statics;
278#[doc(inline)]
279pub use self::statics::Statics;
280
281mod worker;
282
283#[doc(hidden)]
284pub mod support;
285
286#[cfg(feature = "workspace")]
287#[cfg_attr(rune_docsrs, doc(cfg(feature = "workspace")))]
288pub mod workspace;
289
290/// Macro used to annotate native functions which can be loaded as attribute
291/// macros in rune.
292///
293/// See [`Module::macro_meta`][crate::Module::macro_meta].
294///
295/// # Examples
296///
297/// ```
298/// use rune::Module;
299/// use rune::ast;
300/// use rune::compile;
301/// use rune::macros::{quote, MacroContext, TokenStream};
302/// use rune::parse::Parser;
303/// use rune::alloc::prelude::*;
304///
305/// /// Takes an identifier and converts it into a string.
306/// ///
307/// /// # Examples
308/// ///
309/// /// ```rune
310/// /// assert_eq!(ident_to_string!(Hello), "Hello");
311/// /// ```
312/// #[rune::macro_]
313/// fn ident_to_string(cx: &mut MacroContext<'_, '_, '_>, stream: &TokenStream) -> compile::Result<TokenStream> {
314///     let mut p = Parser::from_token_stream(stream, cx.input_span());
315///     let ident = p.parse_all::<ast::Ident>()?;
316///     let ident = cx.resolve(ident)?.try_to_owned()?;
317///     let string = cx.lit(&ident)?;
318///     Ok(quote!(#string).into_token_stream(cx)?)
319/// }
320///
321/// let mut m = Module::new();
322/// m.macro_meta(ident_to_string)?;
323/// # Ok::<_, rune::support::Error>(())
324/// ```
325#[doc(inline)]
326pub use rune_macros::attribute_macro;
327
328/// Macro used to annotate native functions which can be loaded into rune.
329///
330/// This macro automatically performs the following things:
331/// * Rust documentation comments are captured so that it can be used in
332///   generated Rune documentation.
333/// * The name of arguments is captured to improve documentation generation.
334/// * If an instance function is annotated this is detected (if the function
335///   receives `self`). This behavior can be forced using
336///   `#[rune::function(instance)]` if the function doesn't take `self`.
337/// * The name of the function can be set using the `#[rune::function(path =
338///   name)]` argument.
339/// * An associated function can be specified with the `#[rune::function(path =
340///   Type::name)]` argument. If `instance` is specified it is an associated
341///   instance function that can be defined externally.
342/// * Instance functions can be made a protocol function
343///   `#[rune::function(protocol = DISPLAY_FMT)]`.
344///
345/// # Instance and associated functions
346///
347/// Instance and associated functions are a bit tricky to declare using
348/// `#[rune::function]`, and care must be taken that you understand what needs
349/// to be done. So this section is dedicated to documenting the ins and outs of
350/// the process.
351///
352/// Briefly we should mention that instance functions are functions which are
353/// associated with a type at runtime. Calling a value like `value.hello()`
354/// invokes the `hello` associated function through the instance of `value`. The
355/// exact type of `value` will then be used to look up which function to call.
356/// They must take some kind of `self` parameter. Meanwhile associated functions
357/// are just functions which are associated with a static type. Like
358/// `String::new()`. The type `String` must then be in scope, and the function
359/// does not take a `self` parameter.
360///
361/// This is how you declare an instance function which takes `&self` or `&mut
362/// self`:
363///
364/// ```rust
365/// # use rune::Any;
366/// #[derive(Any)]
367/// struct Struct {
368///     /* .. */
369/// }
370///
371/// impl Struct {
372///     /// Get the length of the `Struct`.
373///     #[rune::function]
374///     fn len(&self) -> usize {
375///         /* .. */
376///         # todo!()
377///     }
378/// }
379/// ```
380///
381/// If a function does not take `&self` or `&mut self`, you must specify that
382/// it's an instance function using `#[rune::function(instance)]`. The first
383/// argument is then considered the instance the function gets associated with:
384///
385/// ```rust
386/// # use rune::Any;
387/// #[derive(Any)]
388/// struct Struct {
389///     /* .. */
390/// }
391///
392/// /// Get the length of the `Struct`.
393/// #[rune::function(instance)]
394/// fn len(this: &Struct) -> usize {
395///     /* .. */
396///     # todo!()
397/// }
398/// ```
399///
400/// To declare an associated function which does not receive the type we
401/// must specify the path to the function using `#[rune::function(path =
402/// Self::<name>)]`:
403///
404/// ```rust
405/// # use rune::Any;
406/// #[derive(Any)]
407/// struct Struct {
408///     /* .. */
409/// }
410///
411/// impl Struct {
412///     /// Construct a new [`Struct`].
413///     #[rune::function(path = Self::new)]
414///     fn new() -> Struct {
415///         Struct {
416///            /* .. */
417///         }
418///     }
419/// }
420/// ```
421///
422/// Or externally like this:
423///
424/// ```rust
425/// # use rune::Any;
426/// #[derive(Any)]
427/// struct Struct {
428///     /* .. */
429/// }
430///
431/// /// Construct a new [`Struct`].
432/// #[rune::function(free, path = Struct::new)]
433/// fn new() -> Struct {
434///     Struct {
435///        /* .. */
436///     }
437/// }
438/// ```
439///
440/// The first part `Struct` in `Struct::new` is used to determine the type
441/// the function is associated with.
442///
443/// Protocol functions can either be defined in an impl block or externally. To
444/// define a protocol externally, you can simply do this:
445///
446/// ```rust
447/// use rune::Any;
448/// use rune::runtime::Formatter;
449/// use rune::alloc::fmt::TryWrite;
450/// use rune::alloc;
451///
452/// #[derive(Any)]
453/// struct Struct {
454///     /* .. */
455/// }
456///
457/// #[rune::function(instance, protocol = DISPLAY_FMT)]
458/// fn display_fmt(this: &Struct, f: &mut Formatter) -> alloc::Result<()> {
459///     write!(f, "Struct {{ /* .. */ }}")
460/// }
461/// ```
462///
463/// # Examples
464///
465/// Defining and using a simple free function:
466///
467/// ```
468/// use rune::{Module, ContextError};
469///
470/// /// This is a pretty neat function which is called `std::str::to_uppercase("hello")`.
471/// #[rune::function]
472/// fn to_uppercase(string: &str) -> String {
473///     string.to_uppercase()
474/// }
475///
476/// fn module() -> Result<Module, ContextError> {
477///     let mut m = Module::new();
478///     m.function_meta(to_uppercase)?;
479///     Ok(m)
480/// }
481/// ```
482///
483/// A free instance function:
484///
485/// ```
486/// use rune::{Module, ContextError};
487///
488/// /// This is a pretty neat function, which is called like `"hello".to_uppercase()`.
489/// #[rune::function(instance)]
490/// fn to_uppercase(string: &str) -> String {
491///     string.to_uppercase()
492/// }
493///
494/// /// This is a pretty neat function, which is called like `string::to_uppercase2("hello")`.
495/// #[rune::function(path = string)]
496/// fn to_uppercase2(string: &str) -> String {
497///     string.to_uppercase()
498/// }
499///
500/// fn module() -> Result<Module, ContextError> {
501///     let mut m = Module::new();
502///     m.function_meta(to_uppercase)?;
503///     m.function_meta(to_uppercase2)?;
504///     Ok(m)
505/// }
506/// ```
507///
508/// Regular instance and protocol functions:
509///
510/// ```
511/// use rune::{Any, Module, ContextError};
512/// use rune::runtime::Formatter;
513/// use rune::alloc::fmt::TryWrite;
514/// use rune::alloc;
515///
516/// #[derive(Any)]
517/// struct String {
518///     inner: std::string::String
519/// }
520///
521/// impl String {
522///     /// Construct a new string wrapper.
523///     #[rune::function(path = Self::new)]
524///     fn new(string: &str) -> Self {
525///         Self {
526///             inner: string.into()
527///         }
528///     }
529///
530///     /// Uppercase the string inside of the string wrapper.
531///     ///
532///     /// # Examples
533///     ///
534///     /// ```rune
535///     /// let string = String::new("hello");
536///     /// assert_eq!(string.to_uppercase(), "HELLO");
537///     /// ```
538///     #[rune::function]
539///     fn to_uppercase(&self) -> String {
540///         String {
541///             inner: self.inner.to_uppercase()
542///         }
543///     }
544///
545///     /// Display the string using the [`DISPLAY_FMT`] protocol.
546///     ///
547///     /// # Examples
548///     ///
549///     /// ```rune
550///     /// let string = String::new("hello");
551///     /// assert_eq!(format!("{}", string), "hello");
552///     /// ```
553///     #[rune::function(protocol = DISPLAY_FMT)]
554///     fn display(&self, f: &mut Formatter) -> alloc::Result<()> {
555///         write!(f, "{}", self.inner)
556///     }
557/// }
558///
559/// /// Construct a new empty string.
560/// ///
561/// /// # Examples
562/// ///
563/// /// ```rune
564/// /// let string = String::empty();
565/// /// assert_eq!(string, "hello");
566/// /// ```
567/// #[rune::function(free, path = String::empty)]
568/// fn empty() -> String {
569///     String {
570///         inner: std::string::String::new()
571///     }
572/// }
573///
574/// /// Lowercase the string inside of the string wrapper.
575/// ///
576/// /// # Examples
577/// ///
578/// /// ```rune
579/// /// let string = String::new("Hello");
580/// /// assert_eq!(string.to_lowercase(), "hello");
581/// /// ```
582/// #[rune::function(instance)]
583/// fn to_lowercase(this: &String) -> String {
584///     String {
585///         inner: this.inner.to_lowercase()
586///     }
587/// }
588///
589/// fn module() -> Result<Module, ContextError> {
590///     let mut m = Module::new();
591///     m.ty::<String>()?;
592///     m.function_meta(String::new)?;
593///     m.function_meta(empty)?;
594///     m.function_meta(String::to_uppercase)?;
595///     m.function_meta(to_lowercase)?;
596///     m.function_meta(String::display)?;
597///     Ok(m)
598/// }
599/// ```
600///
601/// # Using `vm_result` and `<expr>.vm?`.
602///
603/// > **Deprecated:** This feature will be removed in a future version of Rune.
604/// > It is not recommended that you use a `Result<T, VmError>` return type
605/// > directly and make use of helpers like [`nested_try!`] for propagating
606/// > inner errors.
607///
608/// In order to conveniently deal with virtual machine errors which require use
609/// [`VmResult`] this attribute macro supports the `vm_result` option.
610///
611/// This changes the return value of the function to be [`VmResult`], and
612/// ensures that any try operator use is wrapped as appropriate. The special
613/// operator `<expr>.vm?` is also supported in this context, which is a
614/// shorthand for the [`vm_try!`] macro.
615///
616/// ```
617/// use rune::alloc::String;
618/// use rune::alloc::prelude::*;
619///
620/// #[rune::function(vm_result)]
621/// fn trim(string: &str) -> String {
622///     string.trim().try_to_owned().vm?
623/// }
624/// ```
625///
626/// This can be combined with regular uses of the try operator `?`:
627///
628/// ```
629/// use core::str::Utf8Error;
630///
631/// use rune::alloc::String;
632/// use rune::alloc::prelude::*;
633///
634/// #[rune::function(vm_result)]
635/// fn trim_bytes(bytes: &[u8]) -> Result<String, Utf8Error> {
636///     Ok(core::str::from_utf8(bytes)?.trim().try_to_owned().vm?)
637/// }
638/// ```
639///
640/// # Using `keep` to keep the name
641///
642/// By default, the name of the function is mangled and the metadata is given
643/// the original name. This means you can't easily call the function from both
644/// Rune and Rust. This behaviour can be changed by using the `keep` attribute, in
645/// which case you must refer to the meta object by a mangled name
646/// (specifically the function name with `__meta` appended):
647///
648/// ```
649/// use rune::{Module, ContextError};
650///
651/// /// Don't mangle the name of the function
652/// #[rune::function(keep)]
653/// fn to_uppercase(string: &str) -> String {
654///     string.to_uppercase()
655/// }
656///
657/// fn module() -> Result<Module, ContextError> {
658///     let mut m = Module::new();
659///     m.function_meta(to_uppercase__meta)?;
660///     Ok(m)
661/// }
662///
663/// fn call_from_rust() {
664///    assert_eq!(to_uppercase("hello"), "HELLO");
665/// }
666/// ```
667///
668/// [`vm_try!`]: crate::vm_try
669/// [`VmResult`]: crate::runtime::VmResult
670/// [`nested_try!`]: crate::nested_try
671#[doc(inline)]
672pub use rune_macros::function;
673
674/// Calculate a type hash at compile time.
675///
676/// By default this uses the `rune` crate.
677///
678/// # Examples
679///
680/// ```
681/// use rune::Hash;
682///
683/// let hash: Hash = rune::hash!(::std::option::Option::Some);
684/// ```
685#[doc(inline)]
686pub use rune_macros::hash;
687
688/// Calculate a type hash at compile time using a custom crate.
689///
690/// By default the [`hash!`] macro uses the `rune` crate.
691///
692/// # Examples
693///
694/// ```
695/// use rune_core::hash::Hash;
696///
697/// let hash: Hash = rune::hash_in!(rune_core::hash, ::std::option::Option::Some);
698/// ```
699#[doc(inline)]
700pub use rune_macros::hash_in;
701
702/// Construct an [`Item`] reference at compile time.
703///
704/// # Examples
705///
706/// ```
707/// use rune::{Item, ItemBuf};
708///
709/// static ITEM: &Item = rune::item!(::std::ops::generator::Generator);
710///
711/// let mut item = ItemBuf::with_crate("std")?;
712/// item.push("ops")?;
713/// item.push("generator")?;
714/// item.push("Generator")?;
715///
716/// assert_eq!(item, ITEM);
717/// # Ok::<_, rune::alloc::Error>(())
718/// ```
719#[doc(inline)]
720pub use rune_macros::item;
721
722/// Construct an [`Item`] reference at compile time.
723///
724/// This variant of the [`item!`] macro allows the module that's used to be
725/// specified as the first argument. By default this is `rune`.
726///
727/// # Examples
728///
729/// ```
730/// use rune_core::item::{Item, ItemBuf};
731/// use rune_macros::item_in;
732///
733/// static ITEM: &Item = rune::item_in!(rune_core::item, ::std::ops::generator::Generator);
734///
735/// let mut item = ItemBuf::with_crate("std")?;
736/// item.push("ops")?;
737/// item.push("generator")?;
738/// item.push("Generator")?;
739///
740/// assert_eq!(item, ITEM);
741/// # Ok::<_, rune_core::alloc::Error>(())
742/// ```
743#[doc(inline)]
744pub use rune_macros::item_in;
745
746/// Macro used to annotate native functions which can be loaded as macros in
747/// rune.
748///
749/// See [`Module::macro_meta`][crate::Module::macro_meta].
750///
751/// # Examples
752///
753/// ```
754/// use rune::Module;
755/// use rune::ast;
756/// use rune::compile;
757/// use rune::macros::{quote, MacroContext, TokenStream};
758/// use rune::parse::Parser;
759/// use rune::alloc::prelude::*;
760///
761/// /// Takes an identifier and converts it into a string.
762/// ///
763/// /// # Examples
764/// ///
765/// /// ```rune
766/// /// assert_eq!(ident_to_string!(Hello), "Hello");
767/// /// ```
768/// #[rune::macro_]
769/// fn ident_to_string(cx: &mut MacroContext<'_, '_, '_>, stream: &TokenStream) -> compile::Result<TokenStream> {
770///     let mut p = Parser::from_token_stream(stream, cx.input_span());
771///     let ident = p.parse_all::<ast::Ident>()?;
772///     let ident = cx.resolve(ident)?.try_to_owned()?;
773///     let string = cx.lit(&ident)?;
774///     Ok(quote!(#string).into_token_stream(cx)?)
775/// }
776///
777/// let mut m = Module::new();
778/// m.macro_meta(ident_to_string)?;
779/// # Ok::<_, rune::support::Error>(())
780/// ```
781#[doc(inline)]
782pub use rune_macros::macro_;
783
784/// Macro used to annotate a module with metadata.
785///
786/// ThIs defines a local function `module_meta` which can be used in conjunction
787/// with [`Module::from_meta`] to construct a module with a given item and
788/// captured documentation.
789///
790/// [`Module::from_meta`]: crate::module::Module::from_meta
791///
792/// # Examples
793///
794/// ```
795/// use rune::{ContextError, Module};
796///
797/// /// Utilities for working with colors.
798/// #[rune::module(::color)]
799/// pub fn module() -> Result<Module, ContextError> {
800///     let mut m = Module::from_meta(module__meta)?;
801///
802///     // Populate module.
803///
804///     Ok(m)
805/// }
806/// ```
807#[doc(inline)]
808pub use rune_macros::module;
809
810#[cfg(feature = "cli")]
811mod ace;
812
813#[cfg(feature = "cli")]
814#[cfg_attr(rune_docsrs, doc(cfg(feature = "cli")))]
815pub mod cli;
816
817#[cfg(feature = "languageserver")]
818#[cfg_attr(rune_docsrs, doc(cfg(feature = "languageserver")))]
819pub mod languageserver;
820
821#[cfg(feature = "doc")]
822#[cfg_attr(rune_docsrs, doc(cfg(feature = "doc")))]
823pub(crate) mod doc;
824
825/// Privately exported details.
826#[doc(hidden)]
827pub mod __priv {
828    pub use crate::any::AnyMarker;
829    pub use crate::function_meta::{
830        FunctionMetaData, FunctionMetaKind, FunctionMetaStatics, MacroMetaData, MacroMetaKind,
831    };
832    pub use crate::item::{Item, ItemBuf};
833    pub use crate::module::{InstallWith, Module, ModuleMetaData};
834    pub use crate::params::Params;
835    pub use crate::runtime::{
836        AnyTypeInfo, ConstConstruct, ConstConstructImpl, ConstValue, ConstValueBuf, Dismantle,
837        FromConstValue, FromValue, Handover, MaybeTypeOf, Object, OwnedTuple, Protocol,
838        RawValueGuard, RuntimeError, ToConstValue, ToValue, Tuple, TypeHash, TypeOf, TypeValue,
839        UnsafeToMut, UnsafeToRef, UnsafeToValue, Value, ValueMutGuard, ValueRefGuard, VmError,
840    };
841    pub use core::clone::Clone;
842
843    pub mod e {
844        use crate::alloc::borrow::TryToOwned;
845        use crate::runtime::{AnyTypeInfo, RuntimeError, TypeInfo, VmErrorKind};
846
847        #[doc(hidden)]
848        #[inline]
849        pub fn missing_struct_field(target: &'static str, name: &'static str) -> RuntimeError {
850            RuntimeError::new(VmErrorKind::MissingStructField { target, name })
851        }
852
853        #[doc(hidden)]
854        #[inline]
855        pub fn missing_variant(name: &str) -> RuntimeError {
856            match name.try_to_owned() {
857                Ok(name) => RuntimeError::new(VmErrorKind::MissingVariant { name }),
858                Err(error) => RuntimeError::from(error),
859            }
860        }
861
862        #[doc(hidden)]
863        #[inline]
864        pub fn expected_variant(actual: TypeInfo) -> RuntimeError {
865            RuntimeError::new(VmErrorKind::ExpectedVariant { actual })
866        }
867
868        #[doc(hidden)]
869        #[inline]
870        pub fn missing_variant_name() -> RuntimeError {
871            RuntimeError::new(VmErrorKind::MissingVariantName)
872        }
873
874        #[doc(hidden)]
875        #[inline]
876        pub fn missing_tuple_index(target: &'static str, index: usize) -> RuntimeError {
877            RuntimeError::new(VmErrorKind::MissingTupleIndex { target, index })
878        }
879
880        #[doc(hidden)]
881        #[inline]
882        pub fn unsupported_object_field_get(target: AnyTypeInfo) -> RuntimeError {
883            RuntimeError::new(VmErrorKind::UnsupportedObjectFieldGet {
884                target: TypeInfo::from(target),
885            })
886        }
887
888        #[doc(hidden)]
889        #[inline]
890        pub fn unsupported_tuple_index_get(target: AnyTypeInfo, index: usize) -> RuntimeError {
891            RuntimeError::new(VmErrorKind::UnsupportedTupleIndexGet {
892                target: TypeInfo::from(target),
893                index,
894            })
895        }
896    }
897}
898
899#[cfg(feature = "musli")]
900mod musli;
901#[cfg(feature = "serde")]
902mod serde;
903
904#[cfg(test)]
905mod tests;
906
907rune_macros::binding! {
908    impl ::std::string::String for crate::alloc::String;
909    #[cfg(feature = "std")]
910    #[cfg_attr(rune_docsrs, doc(cfg(feature = "std")))]
911    impl ::std::io::Error for std::io::Error;
912    impl ::std::string::FromUtf8Error for crate::alloc::string::FromUtf8Error;
913    #[cfg(feature = "anyhow")]
914    impl ::std::error::Error for anyhow::Error;
915    impl ::std::fmt::Error for core::fmt::Error;
916    impl ::std::char::ParseCharError for core::char::ParseCharError;
917    impl ::std::num::ParseFloatError for core::num::ParseFloatError;
918    impl ::std::num::ParseIntError for core::num::ParseIntError;
919    impl ::std::string::Utf8Error for core::str::Utf8Error;
920    #[any]
921    #[dismantle]
922    impl ::std::option::Option for Option<Value>;
923    #[type_of]
924    impl<T> ::std::option::Option for Option<T>;
925    #[any]
926    #[dismantle]
927    impl ::std::result::Result for Result<Value, Value>;
928    #[type_of]
929    impl<T, E> ::std::result::Result for Result<T, E>;
930    #[type_of]
931    impl ::std::bool for bool;
932    #[type_of]
933    impl ::std::char for char;
934    #[type_of]
935    impl ::std::i64 for i8;
936    #[type_of]
937    impl ::std::i64 for i16;
938    #[type_of]
939    impl ::std::i64 for i32;
940    #[type_of]
941    impl ::std::i64 for i64;
942    #[type_of]
943    impl ::std::i64 for i128;
944    #[type_of]
945    impl ::std::i64 for isize;
946    #[type_of]
947    impl ::std::u64 for u8;
948    #[type_of]
949    impl ::std::u64 for u16;
950    #[type_of]
951    impl ::std::u64 for u32;
952    #[type_of]
953    impl ::std::u64 for u64;
954    #[type_of]
955    impl ::std::u64 for u128;
956    #[type_of]
957    impl ::std::u64 for usize;
958    #[type_of]
959    impl ::std::f64 for f32;
960    #[type_of]
961    impl ::std::f64 for f64;
962    #[type_of]
963    impl<C, B> ::std::ops::ControlFlow for core::ops::ControlFlow<C, B>;
964    #[type_of]
965    impl ::std::bytes::Bytes for [u8];
966    #[type_of]
967    impl ::std::cmp::Ordering for core::cmp::Ordering;
968    #[type_of]
969    impl ::std::string::String for rust_alloc::string::String;
970    #[type_of]
971    impl ::std::string::String for crate::alloc::Box<str>;
972    #[type_of]
973    impl ::std::string::String for str;
974    #[type_of]
975    impl ::std::vec::Vec for [Value];
976    #[type_of]
977    impl<T> ::std::vec::Vec for rust_alloc::vec::Vec<T>;
978    #[type_of]
979    impl<T> ::std::vec::Vec for crate::alloc::Vec<T>;
980    #[type_of]
981    impl<T, const N: usize> ::std::vec::Vec for [T; N];
982    #[type_of]
983    impl<T> ::std::vec::Vec for crate::runtime::VecTuple<T>;
984    #[type_of]
985    impl ::std::tuple::Tuple for crate::runtime::Tuple;
986    #[type_of]
987    impl<T> ::std::object::Object for crate::alloc::HashMap<rust_alloc::string::String, T>;
988    #[type_of]
989    impl<T> ::std::object::Object for crate::alloc::HashMap<alloc::String, T>;
990    #[type_of]
991    #[cfg(feature = "std")]
992    #[cfg_attr(rune_docsrs, doc(cfg(feature = "std")))]
993    impl<T> ::std::object::Object for std::collections::HashMap<rust_alloc::string::String, T>;
994    #[type_of]
995    #[cfg(feature = "std")]
996    #[cfg_attr(rune_docsrs, doc(cfg(feature = "std")))]
997    impl<T> ::std::object::Object for std::collections::HashMap<alloc::String, T>;
998    #[type_of]
999    impl ::std::any::Type for crate::runtime::Type;
1000    #[type_of]
1001    impl ::std::any::Hash for crate::hash::Hash;
1002}
1003
1004vm_error!(crate::alloc::Error);