Skip to main content

rhai/
lib.rs

1//! # Rhai - embedded scripting for Rust
2//!
3//! ![Rhai logo](https://rhai.rs/book/images/logo/rhai-banner-transparent-colour.svg)
4//!
5//! Rhai is a tiny, simple and fast embedded scripting language for Rust
6//! that gives you a safe and easy way to add scripting to your applications.
7//!
8//! It provides a familiar syntax based on JavaScript+Rust and a simple Rust interface.
9//!
10//! # A Quick Example
11//!
12//! ## Contents of `my_script.rhai`
13//!
14//! ```rhai
15//! /// Brute force factorial function
16//! fn factorial(x) {
17//!     if x == 1 { return 1; }
18//!     x * factorial(x - 1)
19//! }
20//!
21//! // Calling an external function 'compute'
22//! compute(factorial(10))
23//! ```
24//!
25//! ## The Rust part
26//!
27//! ```no_run
28//! use rhai::{Engine, EvalAltResult};
29//!
30//! fn main() -> Result<(), Box<EvalAltResult>>
31//! {
32//!     // Define external function
33//!     fn compute_something(x: i64) -> bool {
34//!         (x % 40) == 0
35//!     }
36//!
37//!     // Create scripting engine
38//!     let mut engine = Engine::new();
39//!
40//!     // Register external function as 'compute'
41//!     engine.register_fn("compute", compute_something);
42//!
43//! #   #[cfg(not(feature = "no_std"))]
44//! #   #[cfg(not(target_family = "wasm"))]
45//! #
46//!     // Evaluate the script, expecting a 'bool' result
47//!     let result: bool = engine.eval_file("my_script.rhai".into())?;
48//!
49//!     assert_eq!(result, true);
50//!
51//!     Ok(())
52//! }
53//! ```
54//!
55//! # Features
56//!
57#![cfg_attr(feature = "document-features", doc = document_features::document_features!(
58    feature_label = "<span id=\"feature-{feature}\">**`{feature}`**</span>"
59))]
60//!
61//! # On-Line Documentation
62//!
63//! See [The Rhai Book](https://rhai.rs/book) for details on the Rhai scripting engine and language.
64
65// Map `no_std` feature.
66#![cfg_attr(feature = "no_std", no_std)]
67//
68// Clippy lints.
69//
70#![deny(missing_docs)]
71// #![warn(clippy::all)]
72// #![warn(clippy::pedantic)]
73// #![warn(clippy::nursery)]
74#![warn(clippy::cargo)]
75#![warn(clippy::undocumented_unsafe_blocks)]
76#![allow(clippy::missing_errors_doc)]
77#![allow(clippy::missing_panics_doc)]
78#![allow(clippy::used_underscore_binding)]
79#![allow(clippy::inline_always)]
80#![allow(clippy::module_name_repetitions)]
81#![allow(clippy::negative_feature_names)]
82#![allow(clippy::box_collection)]
83#![allow(clippy::upper_case_acronyms)]
84#![allow(clippy::match_same_arms)]
85#![allow(clippy::unnecessary_box_returns)]
86// The lints below are turned off to reduce signal/noise ratio
87#![allow(clippy::cognitive_complexity)] // Hey, this is a scripting engine with a compiler...
88#![allow(clippy::too_many_lines)] // Same...
89#![allow(clippy::too_many_arguments)] // Same...
90#![allow(clippy::absurd_extreme_comparisons)] // On `only_i32`
91#![allow(clippy::wildcard_imports)] // Wildcard imports are used to import the plugins prelude
92#![allow(clippy::enum_glob_use)] // Sometimes useful to import all `Tokens` etc.
93#![allow(clippy::no_effect_underscore_binding)] // Underscored variables may be used by code within feature guards
94#![allow(clippy::semicolon_if_nothing_returned)] // One-liner `match` cases are sometimes formatted as multi-line blocks
95
96// TODO: Further audit no_std compatibility
97// When building with no_std + sync features, explicit imports from alloc
98// are needed despite using no_std_compat. This fixed compilation errors
99// in `native.rs` around missing trait implementations for some users.
100//#[cfg(feature = "no_std")]
101extern crate alloc;
102
103#[cfg(feature = "no_std")]
104extern crate no_std_compat as std;
105
106#[cfg(feature = "no_std")]
107use std::prelude::v1::*;
108
109// The code emitted by codegen relies on this
110extern crate self as rhai;
111
112// Internal modules
113#[macro_use]
114mod reify;
115#[macro_use]
116mod defer;
117
118mod api;
119mod ast;
120pub mod config;
121mod engine;
122mod eval;
123mod func;
124mod module;
125mod optimizer;
126pub mod packages;
127mod parser;
128#[cfg(feature = "serde")]
129pub mod serde;
130mod tests;
131mod tokenizer;
132mod types;
133
134/// Error encountered when parsing a script.
135type PERR = ParseErrorType;
136/// Evaluation result.
137type ERR = EvalAltResult;
138/// General evaluation error for Rhai scripts.
139type RhaiError = Box<ERR>;
140/// Generic [`Result`] type for Rhai functions.
141type RhaiResultOf<T> = Result<T, RhaiError>;
142/// General [`Result`] type for Rhai functions returning [`Dynamic`] values.
143type RhaiResult = RhaiResultOf<Dynamic>;
144
145/// The system integer type. It is defined as [`i64`].
146///
147/// If the `only_i32` feature is enabled, this will be [`i32`] instead.
148#[cfg(not(feature = "only_i32"))]
149pub type INT = i64;
150
151/// The system integer type.
152/// It is defined as [`i32`] since the `only_i32` feature is used.
153///
154/// If the `only_i32` feature is not used, this will be `i64` instead.
155#[cfg(feature = "only_i32")]
156pub type INT = i32;
157
158/// The unsigned system base integer type. It is defined as [`u64`].
159///
160/// If the `only_i32` feature is enabled, this will be [`u32`] instead.
161#[cfg(not(feature = "only_i32"))]
162#[allow(non_camel_case_types)]
163type UNSIGNED_INT = u64;
164
165/// The unsigned system integer base type.
166/// It is defined as [`u32`] since the `only_i32` feature is used.
167///
168/// If the `only_i32` feature is not used, this will be `u64` instead.
169#[cfg(feature = "only_i32")]
170#[allow(non_camel_case_types)]
171type UNSIGNED_INT = u32;
172
173/// Number of bits in [`INT`].
174///
175/// It is 64 unless the `only_i32` feature is enabled when it will be 32.
176const INT_BITS: usize = std::mem::size_of::<INT>() * 8;
177
178/// Number of bytes that make up an [`INT`].
179///
180/// It is 8 unless the `only_i32` feature is enabled when it will be 4.
181#[cfg(not(feature = "no_index"))]
182const INT_BYTES: usize = std::mem::size_of::<INT>();
183
184/// The system floating-point type. It is defined as [`f64`].
185///
186/// Not available under `no_float`.
187///
188/// If the `f32_float` feature is enabled, this will be [`f32`] instead.
189#[cfg(not(feature = "no_float"))]
190#[cfg(not(feature = "f32_float"))]
191pub type FLOAT = f64;
192
193/// The system floating-point type.
194/// It is defined as [`f32`] since the `f32_float` feature is used.
195///
196/// Not available under `no_float`.
197///
198/// If the `f32_float` feature is not used, this will be `f64` instead.
199#[cfg(not(feature = "no_float"))]
200#[cfg(feature = "f32_float")]
201pub type FLOAT = f32;
202
203/// Number of bytes that make up a [`FLOAT`].
204///
205/// It is 8 unless the `f32_float` feature is enabled when it will be 4.
206#[cfg(not(feature = "no_float"))]
207#[cfg(not(feature = "no_index"))]
208const FLOAT_BYTES: usize = std::mem::size_of::<FLOAT>();
209
210/// An exclusive integer range.
211type ExclusiveRange = std::ops::Range<INT>;
212
213/// An inclusive integer range.
214type InclusiveRange = std::ops::RangeInclusive<INT>;
215
216#[cfg(feature = "std")]
217use once_cell::sync::OnceCell;
218
219#[cfg(not(feature = "std"))]
220use once_cell::race::OnceBox as OnceCell;
221
222pub use api::build_type::{CustomType, TypeBuilder};
223#[cfg(not(feature = "no_custom_syntax"))]
224pub use api::custom_syntax::Expression;
225#[cfg(not(feature = "no_std"))]
226#[cfg(any(not(target_family = "wasm"), not(target_os = "unknown")))]
227pub use api::files::{eval_file, run_file};
228pub use api::{eval::eval, run::run};
229pub use ast::{FnAccess, AST};
230use defer::Deferred;
231pub use engine::{Engine, OP_CONTAINS, OP_EQUALS};
232pub use eval::{EvalContext, EvalContextFrameGuard};
233#[cfg(not(feature = "no_function"))]
234#[cfg(not(feature = "no_object"))]
235use func::calc_typed_method_hash;
236use func::{calc_fn_hash, calc_fn_hash_full, calc_var_hash};
237pub use func::{plugin, FuncArgs, NativeCallContext, RhaiNativeFunc};
238pub use module::{FnNamespace, FuncRegistration, Module};
239pub use packages::string_basic::{FUNC_TO_DEBUG, FUNC_TO_STRING};
240pub use rhai_codegen::*;
241#[cfg(not(feature = "no_time"))]
242pub use types::Instant;
243pub use types::{
244    Dynamic, EvalAltResult, FnPtr, ImmutableString, LexError, ParseError, ParseErrorType, Position,
245    Scope, VarDefInfo,
246};
247
248/// _(debugging)_ Module containing types for debugging.
249/// Exported under the `debugging` feature only.
250#[cfg(feature = "debugging")]
251pub mod debugger {
252    #[cfg(not(feature = "no_function"))]
253    pub use super::eval::CallStackFrame;
254    pub use super::eval::{BreakPoint, Debugger, DebuggerCommand, DebuggerEvent};
255}
256
257/// _(internals)_ An identifier in Rhai.
258/// Exported under the `internals` feature only.
259///
260/// Identifiers are assumed to be all-ASCII and short with few exceptions.
261///
262/// [`SmartString`](https://crates.io/crates/smartstring) is used as the underlying storage type
263/// because most identifiers can be stored inline.
264#[expose_under_internals]
265type Identifier = SmartString;
266
267/// Alias to [`Rc`][std::rc::Rc] or [`Arc`][std::sync::Arc] depending on the `sync` feature flag.
268pub use func::Shared;
269
270/// Alias to [`RefCell`][std::cell::RefCell] or [`RwLock`][std::sync::RwLock] depending on the `sync` feature flag.
271pub use func::Locked;
272
273/// A shared [`Module`].
274type SharedModule = Shared<Module>;
275
276#[cfg(not(feature = "no_function"))]
277pub use func::Func;
278
279#[cfg(not(feature = "no_function"))]
280pub use ast::ScriptFnMetadata;
281
282#[cfg(not(feature = "no_function"))]
283pub use api::call_fn::CallFnOptions;
284
285/// Variable-sized array of [`Dynamic`] values.
286///
287/// Not available under `no_index`.
288#[cfg(not(feature = "no_index"))]
289pub type Array = Vec<Dynamic>;
290
291/// Variable-sized array of [`u8`] values (byte array).
292///
293/// Not available under `no_index`.
294#[cfg(not(feature = "no_index"))]
295pub type Blob = Vec<u8>;
296
297/// A dictionary of [`Dynamic`] values with string keys.
298///
299/// Not available under `no_object`.
300///
301/// [`SmartString`](https://crates.io/crates/smartstring) is used as the key type because most
302/// property names are ASCII and short, fewer than 23 characters, so they can be stored inline.
303#[cfg(not(feature = "no_object"))]
304pub type Map = std::collections::BTreeMap<Identifier, Dynamic>;
305
306#[cfg(not(feature = "no_object"))]
307pub use api::json::format_map_as_json;
308
309#[cfg(not(feature = "no_module"))]
310pub use module::ModuleResolver;
311
312/// Module containing all built-in _module resolvers_ available to Rhai.
313#[cfg(not(feature = "no_module"))]
314pub use module::resolvers as module_resolvers;
315
316#[cfg(not(feature = "no_optimize"))]
317pub use optimizer::OptimizationLevel;
318
319// Expose internal data structures.
320
321#[cfg(feature = "internals")]
322pub use types::dynamic::{AccessMode, DynamicReadLock, DynamicWriteLock, Variant};
323
324#[cfg(feature = "internals")]
325pub use module::{FuncInfo, FuncMetadata};
326
327#[cfg(feature = "internals")]
328#[cfg(not(feature = "no_float"))]
329pub use types::FloatWrapper;
330
331#[cfg(feature = "internals")]
332pub use types::{BloomFilterU64, CustomTypeInfo, Span, StringsInterner};
333
334#[cfg(feature = "internals")]
335pub use tokenizer::{
336    get_next_token, is_valid_function_name, is_valid_identifier, parse_raw_string_literal,
337    parse_string_literal, InputStream, MultiInputsStream, Token, TokenIterator, TokenizeState,
338    TokenizerControl, TokenizerControlBlock,
339};
340
341#[cfg(feature = "internals")]
342pub use parser::ParseState;
343
344#[cfg(feature = "internals")]
345pub use api::default_limits;
346
347#[cfg(feature = "internals")]
348pub use ast::{
349    ASTFlags, ASTNode, BinaryExpr, EncapsulatedEnviron, Expr, FlowControl, FnCallExpr,
350    FnCallHashes, Ident, OpAssignment, RangeCase, ScriptFuncDef, Stmt, StmtBlock,
351    SwitchCasesCollection,
352};
353
354#[cfg(feature = "internals")]
355#[cfg(not(feature = "no_custom_syntax"))]
356pub use ast::CustomExpr;
357
358#[cfg(feature = "internals")]
359#[cfg(not(feature = "no_module"))]
360pub use ast::Namespace;
361
362#[cfg(feature = "internals")]
363pub use eval::{Caches, FnResolutionCache, FnResolutionCacheEntry, GlobalRuntimeState, Target};
364
365#[cfg(feature = "internals")]
366#[allow(deprecated)]
367pub use func::{locked_read, locked_write, NativeCallContextStore, RhaiFunc};
368
369#[cfg(feature = "internals")]
370#[cfg(feature = "metadata")]
371pub use api::definitions::Definitions;
372
373/// Number of items to keep inline for [`StaticVec`].
374const STATIC_VEC_INLINE_SIZE: usize = 3;
375
376/// _(internals)_ Alias to [`smallvec::SmallVec<[T; 3]>`](https://crates.io/crates/smallvec),
377/// which is a [`Vec`] backed by a small, inline, fixed-size array when there are ≤ 3 items stored.
378/// Exported under the `internals` feature only.
379///
380/// # History
381///
382/// And Saint Attila raised the `SmallVec` up on high, saying, "O Lord, bless this Thy `SmallVec`
383/// that, with it, Thou mayest blow Thine allocation costs to tiny bits in Thy mercy."
384///
385/// And the Lord did grin, and the people did feast upon the lambs and sloths and carp and anchovies
386/// and orangutans and breakfast cereals and fruit bats and large chu...
387///
388/// And the Lord spake, saying, "First shalt thou depend on the [`smallvec`](https://crates.io/crates/smallvec) crate.
389/// Then, shalt thou keep three inline. No more. No less. Three shalt be the number thou shalt keep inline,
390/// and the number to keep inline shalt be three. Four shalt thou not keep inline, nor either keep inline
391/// thou two, excepting that thou then proceed to three. Five is right out. Once the number three,
392/// being the third number, be reached, then, lobbest thou thy `SmallVec` towards thy heap, who,
393/// being slow and cache-naughty in My sight, shall snuff it."
394///
395/// # Why Three
396///
397/// `StaticVec` is used frequently to keep small lists of items in inline (non-heap) storage in
398/// order to improve cache friendliness and reduce indirections.
399///
400/// The number 3, other than being the holy number, is carefully chosen for a balance between
401/// storage space and reduce allocations. That is because most function calls (and most functions,
402/// for that matter) contain fewer than 4 arguments, the exception being closures that capture a
403/// large number of external variables.
404///
405/// In addition, most script blocks either contain many statements, or just one or two lines;
406/// most scripts load fewer than 4 external modules; most module paths contain fewer than 4 levels
407/// (e.g. `std::collections::map::HashMap` is 4 levels and it is just about as long as they get).
408#[expose_under_internals]
409type StaticVec<T> = smallvec::SmallVec<[T; STATIC_VEC_INLINE_SIZE]>;
410
411/// _(internals)_ A smaller [`Vec`] alternative. Exported under the `internals` feature only.
412/// Exported under the `internals` feature only.
413///
414/// The standard [`Vec`] type uses three machine words (i.e. 24 bytes on 64-bit).
415///
416/// [`ThinVec`](https://crates.io/crates/thin-vec) only uses one machine word, storing other
417/// information inline together with the data.
418///
419/// This is primarily used in places where a few bytes affect the size of the type
420/// -- e.g. in `enum`'s.
421#[expose_under_internals]
422type ThinVec<T> = thin_vec::ThinVec<T>;
423
424/// Number of items to keep inline for [`FnArgsVec`].
425#[cfg(not(feature = "no_closure"))]
426const FN_ARGS_VEC_INLINE_SIZE: usize = 5;
427
428/// _(internals)_ Inline arguments storage for function calls.
429/// Exported under the `internals` feature only.
430///
431/// Not available under `no_closure`.
432///
433/// # Notes
434///
435/// Since most usage of this is during a function call to gather up arguments, this is mostly
436/// allocated on the stack, so we can tolerate a larger number of values stored inline.
437///
438/// Most functions have few parameters, but closures with a lot of captured variables can
439/// potentially have many.  Having a larger inline storage for arguments reduces allocations in
440/// scripts with heavy closure usage.
441///
442/// Under `no_closure`, this type aliases to [`StaticVec`] instead.
443#[expose_under_internals]
444#[cfg(not(feature = "no_closure"))]
445type FnArgsVec<T> = smallvec::SmallVec<[T; FN_ARGS_VEC_INLINE_SIZE]>;
446
447/// Inline arguments storage for function calls.
448/// This type aliases to [`StaticVec`][crate::StaticVec].
449#[expose_under_internals]
450#[cfg(feature = "no_closure")]
451type FnArgsVec<T> = crate::StaticVec<T>;
452
453type SmartString = smartstring::SmartString<smartstring::LazyCompact>;
454
455// Compiler guards against mutually-exclusive feature flags
456
457#[cfg(feature = "no_float")]
458#[cfg(feature = "f32_float")]
459compile_error!("`f32_float` cannot be used with `no_float`");
460
461#[cfg(feature = "only_i32")]
462#[cfg(feature = "only_i64")]
463compile_error!("`only_i32` and `only_i64` cannot be used together");
464
465#[cfg(feature = "no_std")]
466#[cfg(feature = "wasm-bindgen")]
467compile_error!("`wasm-bindgen` cannot be used with `no-std`");
468
469#[cfg(target_family = "wasm")]
470#[cfg(feature = "no_std")]
471compile_error!("`no_std` cannot be used for WASM target");
472
473#[cfg(not(target_family = "wasm"))]
474#[cfg(feature = "wasm-bindgen")]
475compile_error!("`wasm-bindgen` cannot be used for non-WASM target");