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