Merge pull request #558 from schungx/master

Cleanup for 1.7.0.
This commit is contained in:
Stephen Chung 2022-05-04 09:23:07 +08:00 committed by GitHub
commit 4fff1d8e7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 38 additions and 60 deletions

View File

@ -15,11 +15,12 @@ Script-breaking changes
* _Strict Variables Mode_ no longer returns an error when an undeclared variable matches a variable/constant in the provided external `Scope`. * _Strict Variables Mode_ no longer returns an error when an undeclared variable matches a variable/constant in the provided external `Scope`.
Changes to unstable API's Potentially breaking API changes
------------------------- --------------------------------
* The `Engine::on_var` and `Engine::on_parse_token` API's are now marked unstable/volatile. * The `Engine::on_var` and `Engine::on_parse_token` API's are now marked unstable/volatile.
* The closures passed to `Engine::on_var`, `Engine::on_def_var` and `Engine::register_debugger` take `EvalContext` instead of `&EvalContext` or `&mut EvalContext`. * The closures passed to `Engine::on_var`, `Engine::on_def_var` and `Engine::register_debugger` take `EvalContext` instead of `&EvalContext` or `&mut EvalContext`.
* The following enum's are marked `non_exhaustive`: `AccessMode`, `FnAccess`, `FnNamespace`, `FnMetadata`, `OptimizationLevel`
New API New API
------- -------

View File

@ -331,7 +331,7 @@ impl Engine {
/// ///
/// The implementation function has the following signature: /// The implementation function has the following signature:
/// ///
/// > `Fn(symbols: &[ImmutableString], look_ahead: &str) -> Result<Option<ImmutableString>, ParseError>` /// `Fn(symbols: &[ImmutableString], look_ahead: &str) -> Result<Option<ImmutableString>, ParseError>`
/// ///
/// where: /// where:
/// * `symbols`: a slice of symbols that have been parsed so far, possibly containing `$expr$` and/or `$block$`; /// * `symbols`: a slice of symbols that have been parsed so far, possibly containing `$expr$` and/or `$block$`;

View File

@ -27,7 +27,7 @@ impl Engine {
/// ///
/// # Callback Function Signature /// # Callback Function Signature
/// ///
/// > `Fn(name: &str, index: usize, context: EvalContext) -> Result<Option<Dynamic>, Box<EvalAltResult>>` /// `Fn(name: &str, index: usize, context: EvalContext) -> Result<Option<Dynamic>, Box<EvalAltResult>>`
/// ///
/// where: /// where:
/// * `name`: name of the variable. /// * `name`: name of the variable.
@ -87,7 +87,7 @@ impl Engine {
/// ///
/// # Callback Function Signature /// # Callback Function Signature
/// ///
/// > `Fn(is_runtime: bool, info: VarInfo, context: EvalContext) -> Result<bool, Box<EvalAltResult>>` /// `Fn(is_runtime: bool, info: VarInfo, context: EvalContext) -> Result<bool, Box<EvalAltResult>>`
/// ///
/// where: /// where:
/// * `is_runtime`: `true` if the variable definition event happens during runtime, `false` if during compilation. /// * `is_runtime`: `true` if the variable definition event happens during runtime, `false` if during compilation.
@ -148,7 +148,7 @@ impl Engine {
/// ///
/// # Callback Function Signature /// # Callback Function Signature
/// ///
/// > `Fn(token: Token, pos: Position, state: &TokenizeState) -> Token` /// `Fn(token: Token, pos: Position, state: &TokenizeState) -> Token`
/// ///
/// where: /// where:
/// * [`token`][crate::tokenizer::Token]: current token parsed /// * [`token`][crate::tokenizer::Token]: current token parsed
@ -210,9 +210,7 @@ impl Engine {
/// ///
/// # Callback Function Signature /// # Callback Function Signature
/// ///
/// The callback function signature takes the following form: /// `Fn(counter: u64) -> Option<Dynamic>`
///
/// > `Fn(counter: u64) -> Option<Dynamic>`
/// ///
/// ## Return value /// ## Return value
/// ///
@ -295,7 +293,7 @@ impl Engine {
/// ///
/// The callback function signature passed takes the following form: /// The callback function signature passed takes the following form:
/// ///
/// > `Fn(text: &str, source: Option<&str>, pos: Position)` /// `Fn(text: &str, source: Option<&str>, pos: Position)`
/// ///
/// where: /// where:
/// * `text`: the text to display /// * `text`: the text to display

View File

@ -6,6 +6,7 @@ use std::prelude::v1::*;
/// A type representing the access mode of a function. /// A type representing the access mode of a function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub enum FnAccess { pub enum FnAccess {
/// Private function. /// Private function.
Private, Private,

View File

@ -60,12 +60,7 @@ fn print_current_source(
lines: &[String], lines: &[String],
window: (usize, usize), window: (usize, usize),
) { ) {
let current_source = &mut *context let current_source = &mut *context.tag_mut().write_lock::<ImmutableString>().unwrap();
.global_runtime_state_mut()
.debugger
.state_mut()
.write_lock::<ImmutableString>()
.unwrap();
let src = source.unwrap_or(""); let src = source.unwrap_or("");
if src != current_source { if src != current_source {
println!( println!(

View File

@ -249,8 +249,6 @@ impl fmt::Display for CallStackFrame {
pub struct Debugger { pub struct Debugger {
/// The current status command. /// The current status command.
pub(crate) status: DebuggerStatus, pub(crate) status: DebuggerStatus,
/// The current state.
state: Dynamic,
/// The current set of break-points. /// The current set of break-points.
break_points: Vec<BreakPoint>, break_points: Vec<BreakPoint>,
/// The current function call stack. /// The current function call stack.
@ -258,37 +256,16 @@ pub struct Debugger {
} }
impl Debugger { impl Debugger {
/// Create a new [`Debugger`] based on an [`Engine`]. /// Create a new [`Debugger`].
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn new(engine: &Engine) -> Self { pub fn new(status: DebuggerStatus) -> Self {
Self { Self {
status: if engine.debugger.is_some() { status,
DebuggerStatus::Init
} else {
DebuggerStatus::CONTINUE
},
state: if let Some((ref init, ..)) = engine.debugger {
init()
} else {
Dynamic::UNIT
},
break_points: Vec::new(), break_points: Vec::new(),
call_stack: Vec::new(), call_stack: Vec::new(),
} }
} }
/// Get a reference to the current state.
#[inline(always)]
#[must_use]
pub fn state(&self) -> &Dynamic {
&self.state
}
/// Get a mutable reference to the current state.
#[inline(always)]
#[must_use]
pub fn state_mut(&mut self) -> &mut Dynamic {
&mut self.state
}
/// Get the current call stack. /// Get the current call stack.
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]

View File

@ -97,9 +97,23 @@ impl GlobalRuntimeState<'_> {
#[cfg(not(feature = "no_module"))] #[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_function"))]
constants: None, constants: None,
#[cfg(not(feature = "debugging"))]
tag: Dynamic::UNIT, tag: Dynamic::UNIT,
#[cfg(feature = "debugging")] #[cfg(feature = "debugging")]
debugger: crate::eval::Debugger::new(_engine), tag: if let Some((ref init, ..)) = engine.debugger {
init()
} else {
Dynamic::UNIT
},
#[cfg(feature = "debugging")]
debugger: crate::eval::Debugger::new(if engine.debugger.is_some() {
crate::eval::DebuggerStatus::Init
} else {
crate::eval::DebuggerStatus::CONTINUE
}),
dummy: PhantomData::default(), dummy: PhantomData::default(),
} }
} }

View File

@ -23,6 +23,7 @@ use std::{
/// A type representing the namespace of a function. /// A type representing the namespace of a function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub enum FnNamespace { pub enum FnNamespace {
/// Module namespace only. /// Module namespace only.
/// ///
@ -34,6 +35,7 @@ pub enum FnNamespace {
/// A type containing all metadata for a registered function. /// A type containing all metadata for a registered function.
#[derive(Debug, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub struct FnMetadata { pub struct FnMetadata {
/// Function namespace. /// Function namespace.
pub namespace: FnNamespace, pub namespace: FnNamespace,

View File

@ -23,6 +23,7 @@ use std::{
/// Level of optimization performed. /// Level of optimization performed.
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)] #[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
#[non_exhaustive]
pub enum OptimizationLevel { pub enum OptimizationLevel {
/// No optimization performed. /// No optimization performed.
None, None,

View File

@ -127,6 +127,7 @@ impl dyn Variant {
/// _(internals)_ Modes of access. /// _(internals)_ Modes of access.
/// Exported under the `internals` feature only. /// Exported under the `internals` feature only.
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
#[non_exhaustive]
pub enum AccessMode { pub enum AccessMode {
/// Mutable. /// Mutable.
ReadWrite, ReadWrite,

View File

@ -56,17 +56,11 @@ fn test_debugger_state() -> Result<(), Box<EvalAltResult>> {
Dynamic::from_map(state) Dynamic::from_map(state)
}, },
|mut context, _, _, _, _| { |mut context, _, _, _, _| {
// Get global runtime state
let global = context.global_runtime_state_mut();
// Get debugger
let debugger = &mut global.debugger;
// Print debugger state - which is an object map // Print debugger state - which is an object map
println!("Current state = {}", debugger.state()); println!("Current state = {}", context.tag());
// Modify state // Modify state
let mut state = debugger.state_mut().write_lock::<Map>().unwrap(); let mut state = context.tag_mut().write_lock::<Map>().unwrap();
let hello = state.get("hello").unwrap().as_int().unwrap(); let hello = state.get("hello").unwrap().as_int().unwrap();
state.insert("hello".into(), (hello + 1).into()); state.insert("hello".into(), (hello + 1).into());
state.insert("foo".into(), true.into()); state.insert("foo".into(), true.into());

View File

@ -202,15 +202,9 @@ fn test_var_def_filter() -> Result<(), Box<EvalAltResult>> {
let ast = engine.compile("let x = 42;")?; let ast = engine.compile("let x = 42;")?;
engine.run_ast(&ast)?; engine.run_ast(&ast)?;
engine.on_def_var(|_, info, mut ctx| { engine.on_def_var(|_, info, _| match (info.name, info.nesting_level) {
if ctx.tag().is::<()>() {
*ctx.tag_mut() = rhai::Dynamic::ONE;
}
println!("Tag = {}", ctx.tag());
match (info.name, info.nesting_level) {
("x", 0 | 1) => Ok(false), ("x", 0 | 1) => Ok(false),
_ => Ok(true), _ => Ok(true),
}
}); });
assert_eq!( assert_eq!(