diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index f13677ca52..488823940a 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -33,6 +33,13 @@ use pattern::Mode; /// enough for a 1 MiB stack. pub(crate) const MAX_DEPTH: u32 = 600; +#[cfg(test)] +thread_local! { + /// Tests: the top-level function names that deciding the variables of block functions has + /// gathered or looked up. + pub(crate) static FUN_DECL_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Why code could not be compiled. #[derive(Debug)] pub(crate) enum CompileFail { @@ -409,6 +416,7 @@ impl<'a> FnCompiler<'a> { | Stmt::DefaultXmlNamespace(_) => {} } } + let mut top_names: Option> = None; for (k, scope, id) in annex { let mut cur = Some(scope); let mut clash = params.contains(&k) || *k == *key_of("arguments"); @@ -422,7 +430,18 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + if seen.contains(&k) { + continue; + } + // The top-level function names, gathered the first time a block function needs them. + let top = top_names.get_or_insert_with(|| { + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + out.fun_decls.len() as u64)); + out.fun_decls.iter().map(|(name, _)| name).collect::>() + }); + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + 1)); + if !top.contains(&k) && annex_seen.insert(k.clone()) { out.annex_vars.push(k); } } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index ec43bfe327..ebefd33e66 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -203,6 +203,19 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); } +#[test] +fn block_function_variables_look_up_each_top_level_function_name_once() { + // 1,000 top-level functions and 1,000 block functions: each block function's variable is + // decided with one lookup in the names gathered once, not by comparing it with every + // top-level function. + let top = (0..1_000).map(|i| format!("function t{i}() {{ return {i}; }}")).collect::(); + let blocks = (0..1_000).map(|i| format!("{{ function b{i}() {{ return {i}; }} }}")).collect::(); + crate::compiler::FUN_DECL_CHECKS.with(|c| c.set(0)); + assert_eq!(run(&format!("{top}{blocks}t999() + b999()")), JsValue::Number(1_998.0)); + let checks = crate::compiler::FUN_DECL_CHECKS.with(std::cell::Cell::get); + assert_eq!(checks, 2_000, "top-level function names gathered and looked up for 1,000 block functions"); +} + #[test] fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() { // A parameter between the eval code and its variable environment has the name, so the block