From d9916fcc9c4eb55ff746d5e742068cfbbacb0199 Mon Sep 17 00:00:00 2001 From: 54k1 <59379616+54k1@users.noreply.github.com> Date: Sat, 9 Jan 2021 00:17:59 +0530 Subject: [PATCH] Modify environment binding behaviour of function (#1010) * Modify environment binding behaviour of function * Add basic test --- .../ast/node/declaration/function_decl/mod.rs | 25 +++++++++++-------- boa/src/syntax/ast/node/declaration/mod.rs | 3 +++ boa/src/syntax/ast/node/declaration/tests.rs | 12 +++++++++ 3 files changed, 30 insertions(+), 10 deletions(-) create mode 100644 boa/src/syntax/ast/node/declaration/tests.rs diff --git a/boa/src/syntax/ast/node/declaration/function_decl/mod.rs b/boa/src/syntax/ast/node/declaration/function_decl/mod.rs index 9309ce2e1e..999faebdd4 100644 --- a/boa/src/syntax/ast/node/declaration/function_decl/mod.rs +++ b/boa/src/syntax/ast/node/declaration/function_decl/mod.rs @@ -94,18 +94,23 @@ impl Executable for FunctionDecl { // Set the name and assign it in the current environment val.set_field("name", self.name(), context)?; - context - .realm_mut() - .environment - .create_mutable_binding(self.name().to_owned(), false, VariableScope::Function) - .map_err(|e| e.to_error(context))?; - context - .realm_mut() - .environment - .initialize_binding(self.name(), val) - .map_err(|e| e.to_error(context))?; + let environment = &mut context.realm_mut().environment; + if environment.has_binding(self.name()) { + environment + .set_mutable_binding(self.name(), val, true) + .map_err(|e| e.to_error(context))?; + } else { + environment + .create_mutable_binding(self.name().to_owned(), false, VariableScope::Function) + .map_err(|e| e.to_error(context))?; + context + .realm_mut() + .environment + .initialize_binding(self.name(), val) + .map_err(|e| e.to_error(context))?; + } Ok(Value::undefined()) } } diff --git a/boa/src/syntax/ast/node/declaration/mod.rs b/boa/src/syntax/ast/node/declaration/mod.rs index a256a75e87..ac5a0dbbb9 100644 --- a/boa/src/syntax/ast/node/declaration/mod.rs +++ b/boa/src/syntax/ast/node/declaration/mod.rs @@ -19,3 +19,6 @@ pub use self::{ let_decl_list::{LetDecl, LetDeclList}, var_decl_list::{VarDecl, VarDeclList}, }; + +#[cfg(test)] +mod tests; diff --git a/boa/src/syntax/ast/node/declaration/tests.rs b/boa/src/syntax/ast/node/declaration/tests.rs new file mode 100644 index 0000000000..a98ac86f52 --- /dev/null +++ b/boa/src/syntax/ast/node/declaration/tests.rs @@ -0,0 +1,12 @@ +use crate::exec; + +#[test] +fn duplicate_function_name() { + let scenario = r#" + function f () {} + function f () {return 12;} + f() + "#; + + assert_eq!(&exec(scenario), "12"); +}