Skip to content

Commit

Permalink
Simplify code.
Browse files Browse the repository at this point in the history
  • Loading branch information
schungx committed Oct 26, 2023
1 parent 5aefae6 commit eba22d5
Show file tree
Hide file tree
Showing 24 changed files with 129 additions and 237 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Potentially breaking changes
* `ImmutableString` now derefs to `&str` instead of `&SmartString`. Normally this should not be a breaking change.
* Traits implemented by `ImmutableString` are cleaned up. However, I cannot guarantee that there are absolutely no breaking changes, although I try to be careful.
* `EvalContext::new`, `FloatWrapper` and `ConditionalExpr` are now exported only under `internals`.
* `AST::clear_doc` is removed.

Deprecated API's
----------------
Expand Down
6 changes: 2 additions & 4 deletions src/api/call_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,8 @@ impl Engine {
global.lib.push(ast.shared_lib().clone());

#[cfg(not(feature = "no_module"))]
let orig_embedded_module_resolver = std::mem::replace(
&mut global.embedded_module_resolver,
ast.resolver().cloned(),
);
let orig_embedded_module_resolver =
std::mem::replace(&mut global.embedded_module_resolver, ast.resolver.clone());

let rewind_scope = options.rewind_scope;

Expand Down
9 changes: 6 additions & 3 deletions src/api/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl Engine {
resolver: &StaticModuleResolver,
imports: &mut BTreeSet<crate::Identifier>,
) {
ast.walk(&mut |path| match path.last().unwrap() {
ast._walk(&mut |path| match path.last().unwrap() {
// Collect all `import` statements with a string constant path
ASTNode::Stmt(Stmt::Import(x, ..)) => match x.0 {
Expr::StringConstant(ref s, ..)
Expand Down Expand Up @@ -144,7 +144,7 @@ impl Engine {

resolver.insert(path, module);
}
ast.set_resolver(resolver);
ast.resolver = Some(resolver.into());
}

Ok(ast)
Expand Down Expand Up @@ -234,7 +234,10 @@ impl Engine {
let state = &mut ParseState::new(scope, interned_strings, tc);
let mut _ast = self.parse(stream.peekable(), state, optimization_level)?;
#[cfg(feature = "metadata")]
_ast.set_doc(&state.tokenizer_control.borrow().global_comments);
{
let global_comments = &state.tokenizer_control.borrow().global_comments;
_ast.doc = global_comments.into();
}
Ok(_ast)
}
/// Compile a string containing an expression into an [`AST`],
Expand Down
4 changes: 2 additions & 2 deletions src/api/custom_syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ impl Engine {
// Make it a custom keyword/symbol if it is disabled or reserved
if (self.is_symbol_disabled(s)
|| token.as_ref().map_or(false, Token::is_reserved))
&& !self.is_custom_keyword(s)
&& !self.custom_keywords.contains_key(s)
{
self.custom_keywords.insert(s.into(), None);
}
Expand All @@ -289,7 +289,7 @@ impl Engine {
// Make it a custom keyword/symbol if it is disabled or reserved
if self.is_symbol_disabled(s)
|| (token.as_ref().map_or(false, Token::is_reserved)
&& !self.is_custom_keyword(s))
&& !self.custom_keywords.contains_key(s))
{
self.custom_keywords.insert(s.into(), None);
}
Expand Down
3 changes: 2 additions & 1 deletion src/api/definitions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,8 @@ impl Module {
!f.metadata.name.contains('$') && !is_valid_function_name(&f.metadata.name);

#[cfg(not(feature = "no_custom_syntax"))]
let operator = operator || def.engine.is_custom_keyword(&f.metadata.name);
let operator =
operator || def.engine.custom_keywords.contains_key(&f.metadata.name);

f.write_definition(writer, def, operator)?;
}
Expand Down
6 changes: 2 additions & 4 deletions src/api/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,8 @@ impl Engine {
global.lib.push(ast.shared_lib().clone());

#[cfg(not(feature = "no_module"))]
let orig_embedded_module_resolver = mem::replace(
&mut global.embedded_module_resolver,
ast.resolver().cloned(),
);
let orig_embedded_module_resolver =
mem::replace(&mut global.embedded_module_resolver, ast.resolver.clone());

defer! { global => move |g| {
#[cfg(not(feature = "no_module"))]
Expand Down
4 changes: 2 additions & 2 deletions src/api/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,8 @@ impl Engine {
#[inline(never)]
#[must_use]
pub(crate) fn make_type_mismatch_err<T>(&self, typ: &str, pos: Position) -> RhaiError {
let t = self.map_type_name(type_name::<T>()).into();
ERR::ErrorMismatchDataType(t, typ.into(), pos).into()
ERR::ErrorMismatchDataType(self.map_type_name(type_name::<T>()).into(), typ.into(), pos)
.into()
}

/// Compact a script to eliminate insignificant whitespaces and comments.
Expand Down
8 changes: 0 additions & 8 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,6 @@ impl Engine {

Ok(self)
}
/// Is a keyword registered as a custom keyword?
///
/// Not available under `no_custom_syntax`.
#[cfg(not(feature = "no_custom_syntax"))]
#[inline(always)]
pub(crate) fn is_custom_keyword(&self, keyword: &str) -> bool {
self.custom_keywords.contains_key(keyword)
}

/// Get the default value of the custom state for each evaluation run.
#[inline(always)]
Expand Down
4 changes: 3 additions & 1 deletion src/api/optimize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ impl Engine {
);

#[cfg(feature = "metadata")]
_new_ast.set_doc(std::mem::take(ast.doc_mut()));
{
_new_ast.doc = std::mem::take(&mut ast.doc);
}

_new_ast
}
Expand Down
2 changes: 1 addition & 1 deletion src/api/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ impl Engine {

#[cfg(not(feature = "no_module"))]
{
global.embedded_module_resolver = ast.resolver().cloned();
global.embedded_module_resolver = ast.resolver.clone();
}

let _ = self.eval_global_statements(global, caches, scope, ast.statements(), true)?;
Expand Down
85 changes: 14 additions & 71 deletions src/ast/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ pub struct AST {
lib: crate::SharedModule,
/// Embedded module resolver, if any.
#[cfg(not(feature = "no_module"))]
resolver: Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
pub(crate) resolver: Option<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
/// [`AST`] documentation.
#[cfg(feature = "metadata")]
doc: crate::SmartString,
pub(crate) doc: crate::SmartString,
}

impl Default for AST {
Expand Down Expand Up @@ -206,28 +206,6 @@ impl AST {
pub fn doc(&self) -> &str {
&self.doc
}
/// Get a mutable reference to the documentation.
#[cfg(feature = "metadata")]
#[inline(always)]
#[must_use]
#[allow(dead_code)]
pub(crate) fn doc_mut(&mut self) -> &mut crate::SmartString {
&mut self.doc
}
/// Set the documentation.
#[cfg(feature = "metadata")]
#[inline(always)]
pub(crate) fn set_doc(&mut self, doc: impl Into<crate::SmartString>) {
self.doc = doc.into();
}
/// Clear the documentation.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn clear_doc(&mut self) -> &mut Self {
self.doc.clear();
self
}
/// Get the statements.
#[cfg(not(feature = "internals"))]
#[inline(always)]
Expand Down Expand Up @@ -278,16 +256,6 @@ impl AST {
pub const fn shared_lib(&self) -> &crate::SharedModule {
&self.lib
}
/// Get the embedded [module resolver][crate::ModuleResolver].
#[cfg(not(feature = "internals"))]
#[cfg(not(feature = "no_module"))]
#[inline(always)]
#[must_use]
pub(crate) const fn resolver(
&self,
) -> Option<&crate::Shared<crate::module::resolvers::StaticModuleResolver>> {
self.resolver.as_ref()
}
/// _(internals)_ Get the embedded [module resolver][crate::ModuleResolver].
/// Exported under the `internals` feature only.
///
Expand All @@ -301,16 +269,6 @@ impl AST {
) -> Option<&crate::Shared<crate::module::resolvers::StaticModuleResolver>> {
self.resolver.as_ref()
}
/// Set the embedded [module resolver][crate::ModuleResolver].
#[cfg(not(feature = "no_module"))]
#[inline(always)]
pub(crate) fn set_resolver(
&mut self,
resolver: impl Into<crate::Shared<crate::module::resolvers::StaticModuleResolver>>,
) -> &mut Self {
self.resolver = Some(resolver.into());
self
}
/// Clone the [`AST`]'s functions into a new [`AST`].
/// No statements are cloned.
///
Expand Down Expand Up @@ -574,23 +532,18 @@ impl AST {

#[cfg(not(feature = "no_module"))]
match (
self.resolver().map_or(true, |r| r.is_empty()),
other.resolver().map_or(true, |r| r.is_empty()),
self.resolver.as_deref().map_or(true, |r| r.is_empty()),
other.resolver.as_deref().map_or(true, |r| r.is_empty()),
) {
(true, true) => (),
(false, true) => {
_ast.set_resolver(self.resolver().unwrap().clone());
}
(true, false) => {
_ast.set_resolver(other.resolver().unwrap().clone());
}
(false, true) => _ast.resolver = self.resolver.clone(),
(true, false) => _ast.resolver = other.resolver.clone(),
(false, false) => {
let mut resolver = self.resolver().unwrap().as_ref().clone();
let other_resolver = other.resolver().unwrap().as_ref().clone();
for (k, v) in other_resolver {
resolver.insert(k, crate::func::shared_take_or_clone(v));
let mut resolver = self.resolver.as_deref().unwrap().clone();
for (k, v) in other.resolver.as_deref().unwrap() {
resolver.insert(k.clone(), v.as_ref().clone());
}
_ast.set_resolver(resolver);
_ast.resolver = Some(resolver.into());
}
}

Expand Down Expand Up @@ -673,13 +626,11 @@ impl AST {
) -> &mut Self {
#[cfg(not(feature = "no_module"))]
match (
self.resolver().map_or(true, |r| r.is_empty()),
other.resolver().map_or(true, |r| r.is_empty()),
self.resolver.as_deref().map_or(true, |r| r.is_empty()),
other.resolver.as_deref().map_or(true, |r| r.is_empty()),
) {
(_, true) => (),
(true, false) => {
self.set_resolver(other.resolver.unwrap());
}
(true, false) => self.resolver = other.resolver.clone(),
(false, false) => {
let resolver = crate::func::shared_make_mut(self.resolver.as_mut().unwrap());
let other_resolver = crate::func::shared_take_or_clone(other.resolver.unwrap());
Expand Down Expand Up @@ -876,14 +827,6 @@ impl AST {
_ => None,
})
}
/// Recursively walk the [`AST`], including function bodies (if any).
/// Return `false` from the callback to terminate the walk.
#[cfg(not(feature = "internals"))]
#[cfg(not(feature = "no_module"))]
#[inline(always)]
pub(crate) fn walk(&self, on_node: &mut (impl FnMut(&[ASTNode]) -> bool + ?Sized)) -> bool {
self._walk(on_node)
}
/// _(internals)_ Recursively walk the [`AST`], including function bodies (if any).
/// Return `false` from the callback to terminate the walk.
/// Exported under the `internals` feature only.
Expand All @@ -894,7 +837,7 @@ impl AST {
}
/// Recursively walk the [`AST`], including function bodies (if any).
/// Return `false` from the callback to terminate the walk.
fn _walk(&self, on_node: &mut (impl FnMut(&[ASTNode]) -> bool + ?Sized)) -> bool {
pub(crate) fn _walk(&self, on_node: &mut (impl FnMut(&[ASTNode]) -> bool + ?Sized)) -> bool {
let path = &mut Vec::new();

for stmt in self.statements() {
Expand Down
5 changes: 4 additions & 1 deletion src/ast/ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ impl fmt::Debug for Ident {
#[inline(never)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.name)?;
self.pos.debug_print(f)
if !self.pos.is_none() {
write!(f, " @ {:?}", self.pos)?;
}
Ok(())
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/eval/eval_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl<'a, 's, 'ps, 'g, 'c, 't> EvalContext<'a, 's, 'ps, 'g, 'c, 't> {
#[cfg(not(feature = "no_function"))]
#[inline]
pub fn iter_namespaces(&self) -> impl Iterator<Item = &crate::Module> {
self.global.lib.iter().map(AsRef::as_ref)
self.global.lib.iter().map(<_>::as_ref)
}
/// _(internals)_ The current set of namespaces containing definitions of all script-defined functions.
/// Exported under the `internals` feature only.
Expand Down
10 changes: 7 additions & 3 deletions src/eval/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,13 @@ pub fn search_scope_only<'s>(
.flat_map(|m| m.iter_script_fn())
.find_map(|(_, _, f, _, func)| if f == &v.3 { Some(func) } else { None })
{
let mut fn_ptr = crate::FnPtr::new_unchecked(v.3.clone(), Vec::new());
fn_ptr.set_fn_def(Some(fn_def.clone()));
let val: Dynamic = fn_ptr.into();
let val: Dynamic = crate::FnPtr {
name: v.3.clone(),
curry: Vec::new(),
environ: None,
fn_def: Some(fn_def.clone()),
}
.into();
return Ok(val.into());
}

Expand Down
Loading

0 comments on commit eba22d5

Please sign in to comment.