rhai/api/optimize.rs
1//! Module that defines the script optimization API of [`Engine`].
2#![cfg(not(feature = "no_optimize"))]
3
4use crate::{Engine, OptimizationLevel, Scope, AST};
5#[cfg(feature = "no_std")]
6use std::prelude::v1::*;
7
8impl Engine {
9 /// Control whether and how the [`Engine`] will optimize an [`AST`] after compilation.
10 ///
11 /// Not available under `no_optimize`.
12 #[inline(always)]
13 pub fn set_optimization_level(&mut self, optimization_level: OptimizationLevel) -> &mut Self {
14 self.optimization_level = optimization_level;
15 self
16 }
17
18 /// The current optimization level.
19 /// It controls whether and how the [`Engine`] will optimize an [`AST`] after compilation.
20 ///
21 /// Not available under `no_optimize`.
22 #[inline(always)]
23 #[must_use]
24 pub const fn optimization_level(&self) -> OptimizationLevel {
25 self.optimization_level
26 }
27
28 /// Optimize the [`AST`] with constants defined in an external Scope.
29 /// An optimized copy of the [`AST`] is returned while the original [`AST`] is consumed.
30 ///
31 /// Not available under `no_optimize`.
32 ///
33 /// Although optimization is performed by default during compilation, sometimes it is necessary
34 /// to _re_-optimize an [`AST`].
35 ///
36 /// For example, when working with constants that are passed in via an external scope,
37 /// it will be more efficient to optimize the [`AST`] once again to take advantage of the new constants.
38 ///
39 /// With this method, it is no longer necessary to recompile a large script.
40 /// The script [`AST`] can be compiled just once.
41 ///
42 /// Before evaluation, constants are passed into the [`Engine`] via an external scope
43 /// (i.e. with [`Scope::push_constant`][Scope::push_constant]).
44 ///
45 /// Then, the [`AST`] is cloned and the copy re-optimized before running.
46 #[inline]
47 #[must_use]
48 pub fn optimize_ast(
49 &self,
50 scope: &Scope,
51 ast: AST,
52 optimization_level: OptimizationLevel,
53 ) -> AST {
54 let mut ast = ast;
55
56 let mut _new_ast = self.optimize_into_ast(
57 Some(scope),
58 std::mem::take(ast.statements_mut()).to_vec().into(),
59 #[cfg(not(feature = "no_function"))]
60 ast.shared_lib()
61 .iter_fn()
62 .map(|(f, _)| f.get_script_fn_def().unwrap())
63 .cloned()
64 .collect::<Vec<_>>(),
65 optimization_level,
66 );
67
68 #[cfg(feature = "metadata")]
69 {
70 _new_ast.doc = std::mem::take(&mut ast.doc);
71 }
72
73 _new_ast
74 }
75}