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