poet_rhai/lib.rs
1//! # Rhai - embedded scripting for Rust
2//!
3//! 
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`, `MAX_USIZE_INT` < `INT::MAX` because `usize` == `u32` and `INT` == `i64`
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// Internal modules
110#[macro_use]
111mod reify;
112#[macro_use]
113mod defer;
114
115mod api;
116mod ast;
117pub mod config;
118mod engine;
119mod eval;
120mod func;
121mod module;
122mod optimizer;
123pub mod packages;
124mod parser;
125#[cfg(feature = "serde")]
126pub mod serde;
127mod tests;
128mod tokenizer;
129mod types;
130
131/// Error encountered when parsing a script.
132type PERR = ParseErrorType;
133/// Evaluation result.
134type ERR = EvalAltResult;
135/// General evaluation error for Rhai scripts.
136type RhaiError = Box<ERR>;
137/// Generic [`Result`] type for Rhai functions.
138type RhaiResultOf<T> = Result<T, RhaiError>;
139/// General [`Result`] type for Rhai functions returning [`Dynamic`] values.
140type RhaiResult = RhaiResultOf<Dynamic>;
141
142/// The system integer type. It is defined as [`i64`].
143///
144/// If the `only_i32` feature is enabled, this will be [`i32`] instead.
145#[cfg(not(feature = "only_i32"))]
146pub type INT = i64;
147
148/// The system integer type.
149/// It is defined as [`i32`] since the `only_i32` feature is used.
150///
151/// If the `only_i32` feature is not used, this will be `i64` instead.
152#[cfg(feature = "only_i32")]
153pub type INT = i32;
154
155/// The unsigned system base integer type. It is defined as [`u64`].
156///
157/// If the `only_i32` feature is enabled, this will be [`u32`] instead.
158#[cfg(not(feature = "only_i32"))]
159#[allow(non_camel_case_types)]
160type UNSIGNED_INT = u64;
161
162/// The unsigned system integer base type.
163/// It is defined as [`u32`] since the `only_i32` feature is used.
164///
165/// If the `only_i32` feature is not used, this will be `u64` instead.
166#[cfg(feature = "only_i32")]
167#[allow(non_camel_case_types)]
168type UNSIGNED_INT = u32;
169
170/// Number of bits in [`INT`].
171///
172/// It is 64 unless the `only_i32` feature is enabled when it will be 32.
173const INT_BITS: usize = std::mem::size_of::<INT>() * 8;
174
175/// Number of bytes that make up an [`INT`].
176///
177/// It is 8 unless the `only_i32` feature is enabled when it will be 4.
178#[cfg(not(feature = "no_index"))]
179const INT_BYTES: usize = std::mem::size_of::<INT>();
180
181/// The system floating-point type. It is defined as [`f64`].
182///
183/// Not available under `no_float`.
184///
185/// If the `f32_float` feature is enabled, this will be [`f32`] instead.
186#[cfg(not(feature = "no_float"))]
187#[cfg(not(feature = "f32_float"))]
188pub type FLOAT = f64;
189
190/// The system floating-point type.
191/// It is defined as [`f32`] since the `f32_float` feature is used.
192///
193/// Not available under `no_float`.
194///
195/// If the `f32_float` feature is not used, this will be `f64` instead.
196#[cfg(not(feature = "no_float"))]
197#[cfg(feature = "f32_float")]
198pub type FLOAT = f32;
199
200/// Number of bytes that make up a [`FLOAT`].
201///
202/// It is 8 unless the `f32_float` feature is enabled when it will be 4.
203#[cfg(not(feature = "no_float"))]
204#[cfg(not(feature = "no_index"))]
205const FLOAT_BYTES: usize = std::mem::size_of::<FLOAT>();
206
207/// An exclusive integer range.
208type ExclusiveRange = std::ops::Range<INT>;
209
210/// An inclusive integer range.
211type InclusiveRange = std::ops::RangeInclusive<INT>;
212
213#[cfg(feature = "std")]
214use once_cell::sync::OnceCell;
215
216#[cfg(not(feature = "std"))]
217use once_cell::race::OnceBox as OnceCell;
218
219pub use api::build_type::{CustomType, TypeBuilder};
220#[cfg(not(feature = "no_custom_syntax"))]
221pub use api::custom_syntax::Expression;
222#[cfg(not(feature = "no_std"))]
223#[cfg(any(not(target_family = "wasm"), not(target_os = "unknown")))]
224pub use api::files::{eval_file, run_file};
225pub use api::{eval::eval, run::run};
226pub use ast::{FnAccess, AST};
227use defer::Deferred;
228pub use engine::{Engine, OP_CONTAINS, OP_EQUALS};
229pub use eval::EvalContext;
230#[cfg(not(feature = "no_function"))]
231#[cfg(not(feature = "no_object"))]
232use func::calc_typed_method_hash;
233use func::{calc_fn_hash, calc_fn_hash_full, calc_var_hash};
234pub use func::{plugin, FuncArgs, NativeCallContext, RhaiNativeFunc};
235pub use module::{FnNamespace, FuncRegistration, Module};
236pub use packages::string_basic::{FUNC_TO_DEBUG, FUNC_TO_STRING};
237pub use rhai_codegen::*;
238#[cfg(not(feature = "no_time"))]
239pub use types::Instant;
240pub use types::{
241 Dynamic, EvalAltResult, FnPtr, ImmutableString, LexError, ParseError, ParseErrorType, Position,
242 Scope, VarDefInfo,
243};
244
245/// _(debugging)_ Module containing types for debugging.
246/// Exported under the `debugging` feature only.
247#[cfg(feature = "debugging")]
248pub mod debugger {
249 #[cfg(not(feature = "no_function"))]
250 pub use super::eval::CallStackFrame;
251 pub use super::eval::{BreakPoint, Debugger, DebuggerCommand, DebuggerEvent};
252}
253
254/// _(internals)_ An identifier in Rhai.
255/// Exported under the `internals` feature only.
256///
257/// Identifiers are assumed to be all-ASCII and short with few exceptions.
258///
259/// [`SmartString`](https://crates.io/crates/smartstring) is used as the underlying storage type
260/// because most identifiers can be stored inline.
261#[expose_under_internals]
262type Identifier = SmartString;
263
264/// Alias to [`Rc`][std::rc::Rc] or [`Arc`][std::sync::Arc] depending on the `sync` feature flag.
265pub use func::Shared;
266
267/// Alias to [`RefCell`][std::cell::RefCell] or [`RwLock`][std::sync::RwLock] depending on the `sync` feature flag.
268pub use func::Locked;
269
270/// A shared [`Module`].
271type SharedModule = Shared<Module>;
272
273#[cfg(not(feature = "no_function"))]
274pub use func::Func;
275
276#[cfg(not(feature = "no_function"))]
277pub use ast::ScriptFnMetadata;
278
279#[cfg(not(feature = "no_function"))]
280pub use api::call_fn::CallFnOptions;
281
282/// Variable-sized array of [`Dynamic`] values.
283///
284/// Not available under `no_index`.
285#[cfg(not(feature = "no_index"))]
286pub type Array = Vec<Dynamic>;
287
288/// Variable-sized array of [`u8`] values (byte array).
289///
290/// Not available under `no_index`.
291#[cfg(not(feature = "no_index"))]
292pub type Blob = Vec<u8>;
293
294/// A dictionary of [`Dynamic`] values with string keys.
295///
296/// Not available under `no_object`.
297///
298/// [`SmartString`](https://crates.io/crates/smartstring) is used as the key type because most
299/// property names are ASCII and short, fewer than 23 characters, so they can be stored inline.
300#[cfg(not(feature = "no_object"))]
301pub type Map = std::collections::BTreeMap<Identifier, Dynamic>;
302
303#[cfg(not(feature = "no_object"))]
304pub use api::json::format_map_as_json;
305
306#[cfg(not(feature = "no_module"))]
307pub use module::ModuleResolver;
308
309/// Module containing all built-in _module resolvers_ available to Rhai.
310#[cfg(not(feature = "no_module"))]
311pub use module::resolvers as module_resolvers;
312
313#[cfg(not(feature = "no_optimize"))]
314pub use optimizer::OptimizationLevel;
315
316// Expose internal data structures.
317
318#[cfg(feature = "internals")]
319pub use types::dynamic::{AccessMode, DynamicReadLock, DynamicWriteLock, Variant};
320
321#[cfg(feature = "internals")]
322pub use module::{FuncInfo, FuncMetadata};
323
324#[cfg(feature = "internals")]
325#[cfg(not(feature = "no_float"))]
326pub use types::FloatWrapper;
327
328#[cfg(feature = "internals")]
329pub use types::{BloomFilterU64, CustomTypeInfo, Span, StringsInterner};
330
331#[cfg(feature = "internals")]
332pub use tokenizer::{
333 get_next_token, is_valid_function_name, is_valid_identifier, parse_raw_string_literal,
334 parse_string_literal, InputStream, MultiInputsStream, Token, TokenIterator, TokenizeState,
335 TokenizerControl, TokenizerControlBlock,
336};
337
338#[cfg(feature = "internals")]
339pub use parser::ParseState;
340
341#[cfg(feature = "internals")]
342pub use api::default_limits;
343
344#[cfg(feature = "internals")]
345pub use ast::{
346 ASTFlags, ASTNode, BinaryExpr, EncapsulatedEnviron, Expr, FlowControl, FnCallExpr,
347 FnCallHashes, Ident, OpAssignment, RangeCase, ScriptFuncDef, Stmt, StmtBlock,
348 SwitchCasesCollection,
349};
350
351#[cfg(feature = "internals")]
352#[cfg(not(feature = "no_custom_syntax"))]
353pub use ast::CustomExpr;
354
355#[cfg(feature = "internals")]
356#[cfg(not(feature = "no_module"))]
357pub use ast::Namespace;
358
359#[cfg(feature = "internals")]
360pub use eval::{Caches, FnResolutionCache, FnResolutionCacheEntry, GlobalRuntimeState, Target};
361
362#[cfg(feature = "internals")]
363#[allow(deprecated)]
364pub use func::{locked_read, locked_write, NativeCallContextStore, RhaiFunc};
365
366#[cfg(feature = "internals")]
367#[cfg(feature = "metadata")]
368pub use api::definitions::Definitions;
369
370/// Number of items to keep inline for [`StaticVec`].
371const STATIC_VEC_INLINE_SIZE: usize = 3;
372
373/// _(internals)_ Alias to [`smallvec::SmallVec<[T; 3]>`](https://crates.io/crates/smallvec),
374/// which is a [`Vec`] backed by a small, inline, fixed-size array when there are ≤ 3 items stored.
375/// Exported under the `internals` feature only.
376///
377/// # History
378///
379/// And Saint Attila raised the `SmallVec` up on high, saying, "O Lord, bless this Thy `SmallVec`
380/// that, with it, Thou mayest blow Thine allocation costs to tiny bits in Thy mercy."
381///
382/// And the Lord did grin, and the people did feast upon the lambs and sloths and carp and anchovies
383/// and orangutans and breakfast cereals and fruit bats and large chu...
384///
385/// And the Lord spake, saying, "First shalt thou depend on the [`smallvec`](https://crates.io/crates/smallvec) crate.
386/// Then, shalt thou keep three inline. No more. No less. Three shalt be the number thou shalt keep inline,
387/// and the number to keep inline shalt be three. Four shalt thou not keep inline, nor either keep inline
388/// thou two, excepting that thou then proceed to three. Five is right out. Once the number three,
389/// being the third number, be reached, then, lobbest thou thy `SmallVec` towards thy heap, who,
390/// being slow and cache-naughty in My sight, shall snuff it."
391///
392/// # Why Three
393///
394/// `StaticVec` is used frequently to keep small lists of items in inline (non-heap) storage in
395/// order to improve cache friendliness and reduce indirections.
396///
397/// The number 3, other than being the holy number, is carefully chosen for a balance between
398/// storage space and reduce allocations. That is because most function calls (and most functions,
399/// for that matter) contain fewer than 4 arguments, the exception being closures that capture a
400/// large number of external variables.
401///
402/// In addition, most script blocks either contain many statements, or just one or two lines;
403/// most scripts load fewer than 4 external modules; most module paths contain fewer than 4 levels
404/// (e.g. `std::collections::map::HashMap` is 4 levels and it is just about as long as they get).
405#[expose_under_internals]
406type StaticVec<T> = smallvec::SmallVec<[T; STATIC_VEC_INLINE_SIZE]>;
407
408/// _(internals)_ A smaller [`Vec`] alternative. Exported under the `internals` feature only.
409/// Exported under the `internals` feature only.
410///
411/// The standard [`Vec`] type uses three machine words (i.e. 24 bytes on 64-bit).
412///
413/// [`ThinVec`](https://crates.io/crates/thin-vec) only uses one machine word, storing other
414/// information inline together with the data.
415///
416/// This is primarily used in places where a few bytes affect the size of the type
417/// -- e.g. in `enum`'s.
418#[expose_under_internals]
419type ThinVec<T> = thin_vec::ThinVec<T>;
420
421/// Number of items to keep inline for [`FnArgsVec`].
422#[cfg(not(feature = "no_closure"))]
423const FN_ARGS_VEC_INLINE_SIZE: usize = 5;
424
425/// _(internals)_ Inline arguments storage for function calls.
426/// Exported under the `internals` feature only.
427///
428/// Not available under `no_closure`.
429///
430/// # Notes
431///
432/// Since most usage of this is during a function call to gather up arguments, this is mostly
433/// allocated on the stack, so we can tolerate a larger number of values stored inline.
434///
435/// Most functions have few parameters, but closures with a lot of captured variables can
436/// potentially have many. Having a larger inline storage for arguments reduces allocations in
437/// scripts with heavy closure usage.
438///
439/// Under `no_closure`, this type aliases to [`StaticVec`][crate::StaticVec] instead.
440#[expose_under_internals]
441#[cfg(not(feature = "no_closure"))]
442type FnArgsVec<T> = smallvec::SmallVec<[T; FN_ARGS_VEC_INLINE_SIZE]>;
443
444/// Inline arguments storage for function calls.
445/// This type aliases to [`StaticVec`][crate::StaticVec].
446#[expose_under_internals]
447#[cfg(feature = "no_closure")]
448type FnArgsVec<T> = crate::StaticVec<T>;
449
450type SmartString = smartstring::SmartString<smartstring::LazyCompact>;
451
452// Compiler guards against mutually-exclusive feature flags
453
454#[cfg(feature = "no_float")]
455#[cfg(feature = "f32_float")]
456compile_error!("`f32_float` cannot be used with `no_float`");
457
458#[cfg(feature = "only_i32")]
459#[cfg(feature = "only_i64")]
460compile_error!("`only_i32` and `only_i64` cannot be used together");
461
462#[cfg(feature = "no_std")]
463#[cfg(feature = "wasm-bindgen")]
464compile_error!("`wasm-bindgen` cannot be used with `no-std`");
465
466#[cfg(target_family = "wasm")]
467#[cfg(feature = "no_std")]
468compile_error!("`no_std` cannot be used for WASM target");
469
470#[cfg(not(target_family = "wasm"))]
471#[cfg(feature = "wasm-bindgen")]
472compile_error!("`wasm-bindgen` cannot be used for non-WASM target");