1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//! Main module defining the script evaluation [`Engine`].

use crate::api::default_limits::MAX_STRINGS_INTERNED;
use crate::api::options::LangOptions;
use crate::func::native::{
    locked_write, OnDebugCallback, OnDefVarCallback, OnParseTokenCallback, OnPrintCallback,
    OnVarCallback,
};
use crate::packages::{Package, StandardPackage};
use crate::tokenizer::Token;
use crate::types::StringsInterner;
use crate::{Dynamic, Identifier, ImmutableString, Locked, SharedModule};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{collections::BTreeSet, fmt, num::NonZeroU8};

pub type Precedence = NonZeroU8;

pub const KEYWORD_PRINT: &str = "print";
pub const KEYWORD_DEBUG: &str = "debug";
pub const KEYWORD_TYPE_OF: &str = "type_of";
pub const KEYWORD_EVAL: &str = "eval";
pub const KEYWORD_FN_PTR: &str = "Fn";
pub const KEYWORD_FN_PTR_CALL: &str = "call";
pub const KEYWORD_FN_PTR_CURRY: &str = "curry";
#[cfg(not(feature = "no_closure"))]
pub const KEYWORD_IS_SHARED: &str = "is_shared";
pub const KEYWORD_IS_DEF_VAR: &str = "is_def_var";
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_IS_DEF_FN: &str = "is_def_fn";
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_THIS: &str = "this";
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
pub const KEYWORD_GLOBAL: &str = "global";
#[cfg(not(feature = "no_object"))]
pub const FN_GET: &str = "get$";
#[cfg(not(feature = "no_object"))]
pub const FN_SET: &str = "set$";
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
pub const FN_IDX_GET: &str = "index$get$";
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
pub const FN_IDX_SET: &str = "index$set$";
#[cfg(not(feature = "no_function"))]
pub const FN_ANONYMOUS: &str = "anon$";

/// Standard equality comparison operator.
///
/// Some standard functions (e.g. searching an [`Array`][crate::Array]) implicitly call this
/// function to compare two [`Dynamic`] values.
pub const OP_EQUALS: &str = Token::EqualsTo.literal_syntax();

/// Standard containment testing function.
///
/// The `in` operator is implemented as a call to this function.
pub const OP_CONTAINS: &str = "contains";

/// Standard not operator.
pub const OP_NOT: &str = Token::Bang.literal_syntax();

/// Separator for namespaces.
#[cfg(not(feature = "no_module"))]
pub const NAMESPACE_SEPARATOR: &str = Token::DoubleColon.literal_syntax();

/// Rhai main scripting engine.
///
/// # Thread Safety
///
/// [`Engine`] is re-entrant.
///
/// Currently, [`Engine`] is neither [`Send`] nor [`Sync`].
/// Use the `sync` feature to make it [`Send`] `+` [`Sync`].
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// let result = engine.eval::<i64>("40 + 2")?;
///
/// println!("Answer: {result}");   // prints 42
/// # Ok(())
/// # }
/// ```
pub struct Engine {
    /// A collection of all modules loaded into the global namespace of the Engine.
    pub(crate) global_modules: Vec<SharedModule>,
    /// A collection of all sub-modules directly loaded into the Engine.
    #[cfg(not(feature = "no_module"))]
    pub(crate) global_sub_modules: std::collections::BTreeMap<Identifier, SharedModule>,

    /// A module resolution service.
    #[cfg(not(feature = "no_module"))]
    pub(crate) module_resolver: Option<Box<dyn crate::ModuleResolver>>,

    /// Strings interner.
    pub(crate) interned_strings: Option<Locked<StringsInterner>>,

    /// A set of symbols to disable.
    pub(crate) disabled_symbols: BTreeSet<Identifier>,
    /// A map containing custom keywords and precedence to recognize.
    #[cfg(not(feature = "no_custom_syntax"))]
    pub(crate) custom_keywords: std::collections::BTreeMap<Identifier, Option<Precedence>>,
    /// Custom syntax.
    #[cfg(not(feature = "no_custom_syntax"))]
    pub(crate) custom_syntax:
        std::collections::BTreeMap<Identifier, Box<crate::api::custom_syntax::CustomSyntax>>,

    /// Callback closure for filtering variable definition.
    pub(crate) def_var_filter: Option<Box<OnDefVarCallback>>,
    /// Callback closure for resolving variable access.
    pub(crate) resolve_var: Option<Box<OnVarCallback>>,
    /// Callback closure to remap tokens during parsing.
    pub(crate) token_mapper: Option<Box<OnParseTokenCallback>>,

    /// Callback closure when a [`Array`][crate::Array] property accessed does not exist.
    #[cfg(not(feature = "no_index"))]
    #[cfg(feature = "internals")]
    pub(crate) invalid_array_index: Option<Box<crate::func::native::OnInvalidArrayIndexCallback>>,
    /// Callback closure when a [`Map`][crate::Map] property accessed does not exist.
    #[cfg(not(feature = "no_object"))]
    #[cfg(feature = "internals")]
    pub(crate) missing_map_property: Option<Box<crate::func::native::OnMissingMapPropertyCallback>>,

    /// Callback closure for implementing the `print` command.
    pub(crate) print: Option<Box<OnPrintCallback>>,
    /// Callback closure for implementing the `debug` command.
    pub(crate) debug: Option<Box<OnDebugCallback>>,
    /// Callback closure for progress reporting.
    #[cfg(not(feature = "unchecked"))]
    pub(crate) progress: Option<Box<crate::func::native::OnProgressCallback>>,

    /// Language options.
    pub(crate) options: LangOptions,

    /// Default value for the custom state.
    pub(crate) def_tag: Dynamic,

    /// Script optimization level.
    #[cfg(not(feature = "no_optimize"))]
    pub(crate) optimization_level: crate::OptimizationLevel,

    /// Max limits.
    #[cfg(not(feature = "unchecked"))]
    pub(crate) limits: crate::api::limits::Limits,

    /// Callback closure for debugging.
    #[cfg(feature = "debugging")]
    pub(crate) debugger_interface: Option<(
        Box<crate::eval::OnDebuggingInit>,
        Box<crate::eval::OnDebuggerCallback>,
    )>,
}

impl fmt::Debug for Engine {
    #[cold]
    #[inline(never)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut f = f.debug_struct("Engine");

        f.field("global_modules", &self.global_modules);

        #[cfg(not(feature = "no_module"))]
        f.field("global_sub_modules", &self.global_sub_modules);

        f.field("disabled_symbols", &self.disabled_symbols);

        #[cfg(not(feature = "no_custom_syntax"))]
        f.field("custom_keywords", &self.custom_keywords).field(
            "custom_syntax",
            &self
                .custom_syntax
                .keys()
                .map(crate::SmartString::as_str)
                .collect::<String>(),
        );

        f.field("def_var_filter", &self.def_var_filter.is_some())
            .field("resolve_var", &self.resolve_var.is_some())
            .field("token_mapper", &self.token_mapper.is_some());

        #[cfg(not(feature = "unchecked"))]
        f.field("progress", &self.progress.is_some());

        f.field("options", &self.options)
            .field("default_tag", &self.def_tag);

        #[cfg(not(feature = "no_optimize"))]
        f.field("optimization_level", &self.optimization_level);

        #[cfg(not(feature = "unchecked"))]
        f.field("limits", &self.limits);

        #[cfg(feature = "debugging")]
        f.field("debugger_interface", &self.debugger_interface.is_some());

        f.finish()
    }
}

impl Default for Engine {
    #[inline(always)]
    #[must_use]
    fn default() -> Self {
        Self::new()
    }
}

/// Make getter function
#[cfg(not(feature = "no_object"))]
#[inline(always)]
#[must_use]
pub fn make_getter(id: &str) -> Identifier {
    let mut buf = Identifier::new_const();
    buf.push_str(FN_GET);
    buf.push_str(id);
    buf
}

/// Make setter function
#[cfg(not(feature = "no_object"))]
#[inline(always)]
#[must_use]
pub fn make_setter(id: &str) -> Identifier {
    let mut buf = Identifier::new_const();
    buf.push_str(FN_SET);
    buf.push_str(id);
    buf
}

impl Engine {
    /// An empty raw [`Engine`].
    pub const RAW: Self = Self {
        global_modules: Vec::new(),

        #[cfg(not(feature = "no_module"))]
        global_sub_modules: std::collections::BTreeMap::new(),

        #[cfg(not(feature = "no_module"))]
        module_resolver: None,

        interned_strings: None,
        disabled_symbols: BTreeSet::new(),
        #[cfg(not(feature = "no_custom_syntax"))]
        custom_keywords: std::collections::BTreeMap::new(),
        #[cfg(not(feature = "no_custom_syntax"))]
        custom_syntax: std::collections::BTreeMap::new(),

        def_var_filter: None,
        resolve_var: None,
        token_mapper: None,

        #[cfg(not(feature = "no_index"))]
        #[cfg(feature = "internals")]
        invalid_array_index: None,
        #[cfg(not(feature = "no_object"))]
        #[cfg(feature = "internals")]
        missing_map_property: None,

        print: None,
        debug: None,

        #[cfg(not(feature = "unchecked"))]
        progress: None,

        options: LangOptions::new(),

        def_tag: Dynamic::UNIT,

        #[cfg(not(feature = "no_optimize"))]
        optimization_level: crate::OptimizationLevel::Simple,

        #[cfg(not(feature = "unchecked"))]
        limits: crate::api::limits::Limits::new(),

        #[cfg(feature = "debugging")]
        debugger_interface: None,
    };

    /// Create a new [`Engine`].
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        // Create the new scripting Engine
        let mut engine = Self::new_raw();

        #[cfg(not(feature = "no_module"))]
        #[cfg(not(feature = "no_std"))]
        #[cfg(any(not(target_family = "wasm"), not(target_os = "unknown")))]
        {
            engine.module_resolver =
                Some(Box::new(crate::module::resolvers::FileModuleResolver::new()));
        }

        // Turn on the strings interner
        engine.set_max_strings_interned(MAX_STRINGS_INTERNED);

        // default print/debug implementations
        #[cfg(not(feature = "no_std"))]
        #[cfg(any(not(target_family = "wasm"), not(target_os = "unknown")))]
        {
            engine.print = Some(Box::new(|s| println!("{s}")));
            engine.debug = Some(Box::new(|s, source, pos| match (source, pos) {
                (Some(source), crate::Position::NONE) => println!("{source} | {s}"),
                #[cfg(not(feature = "no_position"))]
                (Some(source), pos) => println!("{source} @ {pos:?} | {s}"),
                (None, crate::Position::NONE) => println!("{s}"),
                #[cfg(not(feature = "no_position"))]
                (None, pos) => println!("{pos:?} | {s}"),
            }));
        }

        // Register the standard package
        engine.register_global_module(StandardPackage::new().as_shared_module());

        engine
    }

    /// Create a new [`Engine`] with minimal built-in functions.
    /// It returns a copy of [`Engine::RAW`].
    ///
    /// This is useful for creating a custom scripting engine with only the functions you need.
    ///
    /// Use [`register_global_module`][Engine::register_global_module] to add packages of functions.
    #[inline]
    #[must_use]
    pub const fn new_raw() -> Self {
        Self::RAW
    }

    /// Get an interned [string][ImmutableString].
    ///
    /// [`Engine`] keeps a cache of [`ImmutableString`] instances and tries to avoid new allocations
    /// and save memory when an existing instance is found.
    ///
    /// It is usually a good idea to intern strings if they are used frequently.
    #[inline]
    #[must_use]
    pub fn get_interned_string(
        &self,
        string: impl AsRef<str> + Into<ImmutableString>,
    ) -> ImmutableString {
        match self.interned_strings {
            Some(ref interner) => locked_write(interner).unwrap().get(string),
            None => string.into(),
        }
    }
    /// Get an interned property getter, creating one if it is not yet interned.
    #[cfg(not(feature = "no_object"))]
    #[inline]
    #[must_use]
    pub(crate) fn get_interned_getter(
        &self,
        text: impl AsRef<str> + Into<ImmutableString>,
    ) -> ImmutableString {
        match self.interned_strings {
            Some(ref interner) => locked_write(interner).unwrap().get_with_mapper(
                b'g',
                |s| make_getter(s.as_ref()).into(),
                text,
            ),
            None => make_getter(text.as_ref()).into(),
        }
    }

    /// Get an interned property setter, creating one if it is not yet interned.
    #[cfg(not(feature = "no_object"))]
    #[inline]
    #[must_use]
    pub(crate) fn get_interned_setter(
        &self,
        text: impl AsRef<str> + Into<ImmutableString>,
    ) -> ImmutableString {
        match self.interned_strings {
            Some(ref interner) => locked_write(interner).unwrap().get_with_mapper(
                b's',
                |s| make_setter(s.as_ref()).into(),
                text,
            ),
            None => make_setter(text.as_ref()).into(),
        }
    }

    /// Get an empty [`ImmutableString`] which refers to a shared instance.
    #[inline(always)]
    #[must_use]
    pub fn const_empty_string(&self) -> ImmutableString {
        self.get_interned_string("")
    }

    /// Is there a debugger interface registered with this [`Engine`]?
    #[cfg(feature = "debugging")]
    #[inline(always)]
    #[must_use]
    pub(crate) const fn is_debugger_registered(&self) -> bool {
        self.debugger_interface.is_some()
    }
}