Avoid unnecessarily creating Scope.

This commit is contained in:
Stephen Chung 2023-01-11 11:42:46 +08:00
parent 6d64a75bd2
commit ea3efe654c
10 changed files with 40 additions and 32 deletions

View File

@ -202,7 +202,11 @@ impl Engine {
scope: &Scope, scope: &Scope,
scripts: impl AsRef<[S]>, scripts: impl AsRef<[S]>,
) -> ParseResult<AST> { ) -> ParseResult<AST> {
self.compile_with_scope_and_optimization_level(scope, scripts, self.optimization_level) self.compile_with_scope_and_optimization_level(
Some(scope),
scripts,
self.optimization_level,
)
} }
/// Join a list of strings and compile into an [`AST`] using own scope at a specific optimization level. /// Join a list of strings and compile into an [`AST`] using own scope at a specific optimization level.
/// ///
@ -214,7 +218,7 @@ impl Engine {
#[inline] #[inline]
pub(crate) fn compile_with_scope_and_optimization_level<S: AsRef<str>>( pub(crate) fn compile_with_scope_and_optimization_level<S: AsRef<str>>(
&self, &self,
scope: &Scope, scope: Option<&Scope>,
scripts: impl AsRef<[S]>, scripts: impl AsRef<[S]>,
optimization_level: OptimizationLevel, optimization_level: OptimizationLevel,
) -> ParseResult<AST> { ) -> ParseResult<AST> {
@ -291,7 +295,7 @@ impl Engine {
let scripts = [script]; let scripts = [script];
let (stream, t) = self.lex_raw(&scripts, self.token_mapper.as_deref()); let (stream, t) = self.lex_raw(&scripts, self.token_mapper.as_deref());
let interned_strings = &mut *locked_write(&self.interned_strings); let interned_strings = &mut *locked_write(&self.interned_strings);
let state = &mut ParseState::new(scope, interned_strings, t); let state = &mut ParseState::new(Some(scope), interned_strings, t);
self.parse_global_expr(stream.peekable(), state, |_| {}, self.optimization_level) self.parse_global_expr(stream.peekable(), state, |_| {}, self.optimization_level)
} }
} }

View File

@ -69,7 +69,7 @@ impl Engine {
script: &str, script: &str,
) -> RhaiResultOf<T> { ) -> RhaiResultOf<T> {
let ast = self.compile_with_scope_and_optimization_level( let ast = self.compile_with_scope_and_optimization_level(
scope, Some(scope),
[script], [script],
self.optimization_level, self.optimization_level,
)?; )?;
@ -123,7 +123,7 @@ impl Engine {
let (stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref()); let (stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref());
let state = &mut ParseState::new(scope, interned_strings, tc); let state = &mut ParseState::new(Some(scope), interned_strings, tc);
// No need to optimize a lone expression // No need to optimize a lone expression
self.parse_global_expr( self.parse_global_expr(

View File

@ -4,7 +4,7 @@ use crate::parser::{ParseResult, ParseState};
use crate::types::StringsInterner; use crate::types::StringsInterner;
use crate::{ use crate::{
Engine, ExclusiveRange, FnPtr, ImmutableString, InclusiveRange, OptimizationLevel, Position, Engine, ExclusiveRange, FnPtr, ImmutableString, InclusiveRange, OptimizationLevel, Position,
RhaiError, Scope, SmartString, ERR, RhaiError, SmartString, ERR,
}; };
use std::any::type_name; use std::any::type_name;
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
@ -282,9 +282,8 @@ impl Engine {
let (mut stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref()); let (mut stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref());
tc.borrow_mut().compressed = Some(String::new()); tc.borrow_mut().compressed = Some(String::new());
stream.state.last_token = Some(SmartString::new_const()); stream.state.last_token = Some(SmartString::new_const());
let scope = Scope::new();
let mut interner = StringsInterner::new(); let mut interner = StringsInterner::new();
let mut state = ParseState::new(&scope, &mut interner, tc); let mut state = ParseState::new(None, &mut interner, tc);
let mut _ast = self.parse( let mut _ast = self.parse(
stream.peekable(), stream.peekable(),
&mut state, &mut state,

View File

@ -4,7 +4,7 @@
use crate::func::native::locked_write; use crate::func::native::locked_write;
use crate::parser::{ParseSettingFlags, ParseState}; use crate::parser::{ParseSettingFlags, ParseState};
use crate::tokenizer::Token; use crate::tokenizer::Token;
use crate::{Engine, LexError, Map, OptimizationLevel, RhaiResultOf, Scope}; use crate::{Engine, LexError, Map, OptimizationLevel, RhaiResultOf};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
use std::prelude::v1::*; use std::prelude::v1::*;
@ -115,9 +115,8 @@ impl Engine {
); );
let ast = { let ast = {
let scope = Scope::new();
let interned_strings = &mut *locked_write(&self.interned_strings); let interned_strings = &mut *locked_write(&self.interned_strings);
let state = &mut ParseState::new(&scope, interned_strings, tokenizer_control); let state = &mut ParseState::new(None, interned_strings, tokenizer_control);
self.parse_global_expr( self.parse_global_expr(
stream.peekable(), stream.peekable(),

View File

@ -52,7 +52,7 @@ impl Engine {
let mut ast = ast; let mut ast = ast;
let mut _new_ast = self.optimize_into_ast( let mut _new_ast = self.optimize_into_ast(
scope, Some(scope),
ast.take_statements(), ast.take_statements(),
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
ast.shared_lib() ast.shared_lib()

View File

@ -60,7 +60,7 @@ impl Engine {
let ast = { let ast = {
let (stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref()); let (stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref());
let interned_strings = &mut *locked_write(&self.interned_strings); let interned_strings = &mut *locked_write(&self.interned_strings);
let state = &mut ParseState::new(scope, interned_strings, tc); let state = &mut ParseState::new(Some(scope), interned_strings, tc);
self.parse(stream.peekable(), state, self.optimization_level)? self.parse(stream.peekable(), state, self.optimization_level)?
}; };
self.run_ast_with_scope(scope, &ast) self.run_ast_with_scope(scope, &ast)

View File

@ -298,7 +298,7 @@ impl Engine {
let source = global.source(); let source = global.source();
let context = &(self, FUNC_TO_STRING, source, &*global, pos).into(); let context = &(self, FUNC_TO_STRING, source, &*global, pos).into();
let display = print_with_func(FUNC_TO_STRING, context, item); let display = print_with_func(FUNC_TO_STRING, context, item);
write!(concat, "{}", display).unwrap(); write!(concat, "{display}").unwrap();
} }
#[cfg(not(feature = "unchecked"))] #[cfg(not(feature = "unchecked"))]

View File

@ -1518,7 +1518,7 @@ impl Engine {
// Compile the script text // Compile the script text
// No optimizations because we only run it once // No optimizations because we only run it once
let ast = self.compile_with_scope_and_optimization_level( let ast = self.compile_with_scope_and_optimization_level(
&Scope::new(), None,
[script], [script],
#[cfg(not(feature = "no_optimize"))] #[cfg(not(feature = "no_optimize"))]
OptimizationLevel::None, OptimizationLevel::None,

View File

@ -1288,7 +1288,7 @@ impl Engine {
fn optimize_top_level( fn optimize_top_level(
&self, &self,
statements: StmtBlockContainer, statements: StmtBlockContainer,
scope: &Scope, scope: Option<&Scope>,
lib: &[crate::SharedModule], lib: &[crate::SharedModule],
optimization_level: OptimizationLevel, optimization_level: OptimizationLevel,
) -> StmtBlockContainer { ) -> StmtBlockContainer {
@ -1309,11 +1309,13 @@ impl Engine {
} }
// Add constants and variables from the scope // Add constants and variables from the scope
for (name, constant, value) in scope.iter() { if let Some(scope) = scope {
if constant { for (name, constant, value) in scope.iter() {
state.push_var(name, AccessMode::ReadOnly, Some(value)); if constant {
} else { state.push_var(name, AccessMode::ReadOnly, Some(value));
state.push_var(name, AccessMode::ReadWrite, None); } else {
state.push_var(name, AccessMode::ReadWrite, None);
}
} }
} }
@ -1323,7 +1325,7 @@ impl Engine {
/// Optimize a collection of statements and functions into an [`AST`]. /// Optimize a collection of statements and functions into an [`AST`].
pub(crate) fn optimize_into_ast( pub(crate) fn optimize_into_ast(
&self, &self,
scope: &Scope, scope: Option<&Scope>,
statements: StmtBlockContainer, statements: StmtBlockContainer,
#[cfg(not(feature = "no_function"))] functions: StaticVec< #[cfg(not(feature = "no_function"))] functions: StaticVec<
crate::Shared<crate::ast::ScriptFnDef>, crate::Shared<crate::ast::ScriptFnDef>,

View File

@ -55,7 +55,7 @@ pub struct ParseState<'e, 's> {
/// Strings interner. /// Strings interner.
pub interned_strings: &'s mut StringsInterner, pub interned_strings: &'s mut StringsInterner,
/// External [scope][Scope] with constants. /// External [scope][Scope] with constants.
pub scope: &'e Scope<'e>, pub external_constants: Option<&'e Scope<'e>>,
/// Global runtime state. /// Global runtime state.
pub global: Option<Box<GlobalRuntimeState>>, pub global: Option<Box<GlobalRuntimeState>>,
/// Encapsulates a local stack with variable names to simulate an actual runtime scope. /// Encapsulates a local stack with variable names to simulate an actual runtime scope.
@ -87,7 +87,7 @@ impl fmt::Debug for ParseState<'_, '_> {
f.field("tokenizer_control", &self.tokenizer_control) f.field("tokenizer_control", &self.tokenizer_control)
.field("interned_strings", &self.interned_strings) .field("interned_strings", &self.interned_strings)
.field("scope", &self.scope) .field("external_constants_scope", &self.external_constants)
.field("global", &self.global) .field("global", &self.global)
.field("stack", &self.stack) .field("stack", &self.stack)
.field("block_stack_len", &self.block_stack_len); .field("block_stack_len", &self.block_stack_len);
@ -109,7 +109,7 @@ impl<'e, 's> ParseState<'e, 's> {
#[inline] #[inline]
#[must_use] #[must_use]
pub fn new( pub fn new(
scope: &'e Scope, external_constants: Option<&'e Scope>,
interned_strings: &'s mut StringsInterner, interned_strings: &'s mut StringsInterner,
tokenizer_control: TokenizerControl, tokenizer_control: TokenizerControl,
) -> Self { ) -> Self {
@ -121,7 +121,7 @@ impl<'e, 's> ParseState<'e, 's> {
#[cfg(not(feature = "no_closure"))] #[cfg(not(feature = "no_closure"))]
allow_capture: true, allow_capture: true,
interned_strings, interned_strings,
scope, external_constants,
global: None, global: None,
stack: None, stack: None,
block_stack_len: 0, block_stack_len: 0,
@ -1416,7 +1416,7 @@ impl Engine {
// Build new parse state // Build new parse state
let new_interner = &mut StringsInterner::new(); let new_interner = &mut StringsInterner::new();
let new_state = &mut ParseState::new( let new_state = &mut ParseState::new(
state.scope, state.external_constants,
new_interner, new_interner,
state.tokenizer_control.clone(), state.tokenizer_control.clone(),
); );
@ -1476,7 +1476,9 @@ impl Engine {
&& index.is_none() && index.is_none()
&& !settings.has_flag(ParseSettingFlags::CLOSURE_SCOPE) && !settings.has_flag(ParseSettingFlags::CLOSURE_SCOPE)
&& settings.has_option(LangOptions::STRICT_VAR) && settings.has_option(LangOptions::STRICT_VAR)
&& !state.scope.contains(name) && !state
.external_constants
.map_or(false, |scope| scope.contains(name))
{ {
// If the parent scope is not inside another capturing closure // If the parent scope is not inside another capturing closure
// then we can conclude that the captured variable doesn't exist. // then we can conclude that the captured variable doesn't exist.
@ -1624,7 +1626,9 @@ impl Engine {
&& !is_func && !is_func
&& index.is_none() && index.is_none()
&& settings.has_option(LangOptions::STRICT_VAR) && settings.has_option(LangOptions::STRICT_VAR)
&& !state.scope.contains(&s) && !state
.external_constants
.map_or(false, |scope| scope.contains(&s))
{ {
return Err( return Err(
PERR::VariableUndefined(s.to_string()).into_err(settings.pos) PERR::VariableUndefined(s.to_string()).into_err(settings.pos)
@ -3298,7 +3302,7 @@ impl Engine {
(Token::Fn, pos) => { (Token::Fn, pos) => {
// Build new parse state // Build new parse state
let new_state = &mut ParseState::new( let new_state = &mut ParseState::new(
state.scope, state.external_constants,
state.interned_strings, state.interned_strings,
state.tokenizer_control.clone(), state.tokenizer_control.clone(),
); );
@ -3848,7 +3852,7 @@ impl Engine {
#[cfg(not(feature = "no_optimize"))] #[cfg(not(feature = "no_optimize"))]
return Ok(self.optimize_into_ast( return Ok(self.optimize_into_ast(
state.scope, state.external_constants,
statements, statements,
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
functions.into_iter().map(|(.., v)| v).collect(), functions.into_iter().map(|(.., v)| v).collect(),
@ -3934,7 +3938,7 @@ impl Engine {
#[cfg(not(feature = "no_optimize"))] #[cfg(not(feature = "no_optimize"))]
return Ok(self.optimize_into_ast( return Ok(self.optimize_into_ast(
state.scope, state.external_constants,
statements, statements,
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
_lib, _lib,