1use super::*;
5
6impl Interp {
7 pub(crate) fn mark_task_start(&mut self) {
14 if self.task_depth == 0 && self.depth == 0 {
15 self.task_start = self.steps;
16 }
17 }
18
19 #[inline(always)]
21 pub(crate) fn tick(&mut self) -> bool {
22 self.steps += 1;
23 if self.steps & 0x7FFF == 0 && self.cooperative_slice() {
24 return self.tick_abort_tab_kill();
25 }
26 self.steps.wrapping_sub(self.task_start) > self.max_steps && self.tick_abort()
27 }
28
29 #[cold]
32 #[inline(never)]
33 fn tick_abort_tab_kill(&mut self) -> bool {
34 if !self.aborted {
35 self.log_progress("ABORT tab kill");
36 }
37 self.aborted = true;
38 true
39 }
40
41 #[cold]
43 #[inline(never)]
44 fn cooperative_slice(&self) -> bool {
46 if self.steps & 0xFFFF == 0 {
47 self.prof_sample();
48 }
49 #[cfg(target_os = "none")]
51 crate::os_lib::platform::responsiveness_add(crate::os_lib::platform::Qty::JsSteps, 32_768);
52 crate::os_lib::platform::yield_now();
53 #[cfg(target_os = "none")]
55 crate::os_lib::platform::kill_checkpoint();
56 #[cfg(target_os = "none")]
57 return crate::os_lib::platform::kill_pending();
58 #[cfg(not(target_os = "none"))]
59 false
60 }
61
62 #[cold]
64 #[inline(never)]
65 fn prof_sample(&self) {
66 static PROF: spin::Mutex<alloc::collections::BTreeMap<usize, (u32, String)>> =
67 spin::Mutex::new(alloc::collections::BTreeMap::new());
68 static LAST: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
69 let Some(top) = self.call_names.last() else { return };
70 let (key, desc) = match top {
71 Value::Object(o) => {
72 let key = Rc::as_ptr(o) as *const u8 as usize;
73 let Ok(b) = o.try_borrow() else { return };
74 match &b.kind {
75 ObjKind::Function(f) => {
76 let body = f.body();
77 let k = Rc::as_ptr(body) as *const u8 as usize;
78 (k, body.source_head(90).unwrap_or_else(|| super::calls::func_diag_name(top)))
79 }
80 _ => (key, super::calls::func_diag_name(top)),
81 }
82 }
83 _ => (0, String::from("?")),
84 };
85 let mut prof = PROF.lock();
86 let e = prof.entry(key).or_insert((0, desc));
87 e.0 += 1;
88 let now = crate::os_lib::platform::now_ms();
89 if now.saturating_sub(LAST.load(core::sync::atomic::Ordering::Relaxed)) >= 20_000 {
90 LAST.store(now, core::sync::atomic::Ordering::Relaxed);
91 let total: u32 = prof.values().map(|v| v.0).sum();
92 let mut v: Vec<&(u32, String)> = prof.values().collect();
93 v.sort_by_key(|a| core::cmp::Reverse(a.0));
94 crate::warn!("[JSPROF][HOT] t={}s samples={} fns={}", now / 1000, total, prof.len());
95 for (n, d) in v.iter().take(12) {
96 crate::warn!("[JSPROF][HOT] {} {}", n, d);
97 }
98 prof.clear();
99 crate::os_lib::platform::pc_profile_dump();
100 let ps: Vec<u64> = crate::os_lib::ecma::parser::PARSE_STATS.iter().map(|a| a.swap(0, core::sync::atomic::Ordering::Relaxed)).collect();
101 crate::warn!("[JSPROF][PARSE] lazy={}B/{} eval={}B/{} program={}B/{}", ps.first().unwrap_or(&0), ps.get(3).unwrap_or(&0), ps.get(1).unwrap_or(&0), ps.get(4).unwrap_or(&0), ps.get(2).unwrap_or(&0), ps.get(5).unwrap_or(&0));
102 let lk: Vec<u64> = crate::os_lib::ecma::ast::LAZY_KIND.iter().map(|a| a.swap(0, core::sync::atomic::Ordering::Relaxed)).collect();
103 crate::warn!("[JSPROF][LAZY] once={}B cache={}B drop={}B", lk.first().unwrap_or(&0), lk.get(1).unwrap_or(&0), lk.get(2).unwrap_or(&0));
104 }
105 }
106
107 #[cold]
108 #[inline(never)]
109 fn tick_abort(&mut self) -> bool {
110 if !self.aborted {
111 self.log_progress("ABORT step budget");
112 }
113 self.aborted = true;
114 true
115 }
116
117 fn log_progress(&self, what: &str) {
118 let n = self.call_names.len();
119 let top = self.call_stack_names(4);
120 let (used, _) = crate::os_lib::platform::heap_stats();
121 crate::warn!(
122 "[JSPROF] {} steps={} depth={} t={}ms heap={}MB top={:?}",
123 what,
124 self.steps,
125 n,
126 crate::os_lib::platform::now_ms(),
127 used / (1024 * 1024),
128 top
129 );
130 }
131
132}
133
134pub(crate) fn note_engine_error<S: core::fmt::Debug>(msg: &str, callers: impl FnOnce() -> S) {
137 static SEEN: spin::Mutex<alloc::collections::BTreeMap<String, u32>> =
138 spin::Mutex::new(alloc::collections::BTreeMap::new());
139 let key: String = msg.chars().take(160).collect();
140 let mut seen = SEEN.lock();
141 if seen.len() >= 300 && !seen.contains_key(&key) {
142 return;
143 }
144 let n = seen.entry(key.clone()).or_insert(0);
145 *n += 1;
146 if n.is_power_of_two() {
148 crate::warn!("[JS][THROWN] t={}ms n={} {} at={:?}", crate::os_lib::platform::now_ms(), n, key, callers());
149 }
150}
151
152impl Interp {
153 pub(crate) fn note_thrown_value(&self, v: &Value) {
156 let repr = match v {
157 Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_)) => {
158 let b = o.borrow();
159 let ObjKind::Array(items) = &b.kind else { return };
160 let parts: Vec<String> = items
161 .iter()
162 .take(4)
163 .map(|x| match x {
164 Value::Number(_) | Value::Bool(_) | Value::Undefined | Value::Null => x.to_js_string(),
165 Value::Str(_) => alloc::format!("'{}'", x.to_js_string().chars().take(40).collect::<String>()),
166 _ => String::from("<obj>"),
167 })
168 .collect();
169 alloc::format!("throw [{}] len={}", parts.join(","), items.len())
170 }
171 Value::Object(o) => {
172 let b = o.borrow();
173 match (b.props.get("name"), b.props.get("message")) {
174 (n, Some(m)) => alloc::format!(
175 "throw {}: {}",
176 n.map(|n| n.to_js_string()).unwrap_or_default(),
177 m.to_js_string()
178 ),
179 _ => String::from("throw <object>"),
180 }
181 }
182 Value::Number(_) | Value::Bool(_) | Value::Undefined | Value::Null => {
183 alloc::format!("throw {}", v.to_js_string())
184 }
185 _ => String::from("throw <value>"),
186 };
187 note_engine_error(&repr, || self.call_stack_names(3));
188 }
189
190 pub fn error(&self, msg: impl Into<String>) -> Value {
192 self.throw(msg)
193 }
194
195 pub fn type_error(&self, msg: impl Into<String>) -> Value {
201 self.error_of_kind("TypeError", msg)
202 }
203
204 pub fn reference_error(&self, msg: impl Into<String>) -> Value {
206 self.error_of_kind("ReferenceError", msg)
207 }
208
209 pub fn syntax_error(&self, msg: impl Into<String>) -> Value {
211 self.error_of_kind("SyntaxError", msg)
212 }
213
214 pub fn range_error(&self, msg: impl Into<String>) -> Value {
216 self.error_of_kind("RangeError", msg)
217 }
218
219 pub(crate) fn error_of_kind(&self, kind: &str, msg: impl Into<String>) -> Value {
221 let err = self.throw(msg);
222 if let Value::Object(o) = &err {
223 let msg_str = o.borrow().props.get("message").map(|v| v.to_js_string()).unwrap_or_default();
224 o.borrow_mut().set_error_stack(super::super::builtins::build_error_stack(kind, &msg_str));
225 o.borrow_mut().props.insert(String::from("name").into(), Value::str(kind));
226 o.borrow_mut().hide_props(super::super::builtins::ERROR_OWN_PROPS);
227 if let Some(Value::Object(ctor)) = self.global.borrow().vars.get(kind) {
228 if let Some(Value::Object(proto)) = ctor.borrow().props.get("prototype") {
229 o.borrow_mut().proto = Some(proto.clone());
230 }
231 }
232 }
233 err
234 }
235
236 pub(crate) fn throw(&self, msg: impl Into<String>) -> Value {
237 let o = Obj::plain();
239 let msg: String = msg.into();
240 if msg.ends_with("is not defined") || msg.ends_with("is not a function") || msg.starts_with("Cannot read properties") {
242 note_engine_error(&msg, || {
244 self.call_names
245 .iter()
246 .rev()
247 .take(2)
248 .map(|f| f.to_js_string().chars().take(700).collect::<String>())
249 .collect::<Vec<_>>()
250 });
251 } else {
252 note_engine_error(&msg, || self.call_stack_names(3));
253 }
254 let mut stack_str = if msg.is_empty() {
263 String::from("Error")
264 } else {
265 alloc::format!("Error: {msg}")
266 };
267 for name in self.call_stack_names(12) {
268 stack_str.push_str("\n at ");
269 stack_str.push_str(&name);
270 }
271 o.borrow_mut().set_error_stack(stack_str);
272 o.borrow_mut()
273 .props
274 .insert(String::from("message").into(), Value::str(msg));
275 o.borrow_mut()
276 .props
277 .insert(String::from("name").into(), Value::str("Error"));
278 o.borrow_mut().hide_props(super::super::builtins::ERROR_OWN_PROPS);
279 if let Some(Value::Object(ctor)) = self.global.borrow().vars.get("Error") {
283 if let Some(Value::Object(proto)) = ctor.borrow().props.get("prototype") {
284 o.borrow_mut().proto = Some(proto.clone());
285 }
286 }
287 Value::Object(o)
288 }
289
290 pub(crate) fn eval_source(&mut self, source: &str) -> Result<Value, Value> {
296 crate::os_lib::ecma::parser::note_parse(1, source.len());
298 let mut parser = Parser::new(Lexer::new(source));
299 let (program, top_errs) = parser.parse_program_reporting();
302 if let Some(e) = top_errs.first() {
303 return Err(self.syntax_error(e.message.clone()));
304 }
305 if parser.error_count() > 0 {
312 let msg = parser.errors().first().map(|e| e.message.clone()).unwrap_or_default();
313 crate::warn!("[JS] eval(): SyntaxError: {}", msg.chars().take(160).collect::<String>());
314 return Err(self.syntax_error(msg));
315 }
316 let strict = body_has_use_strict(&program.body);
317 let scope = if strict {
318 Scope::child(self.global.clone())
319 } else {
320 self.global.clone()
321 };
322 let global_this = self.global.borrow().vars.get("globalThis").cloned().unwrap_or(Value::Undefined);
324 match self.exec_eval_statements(&program.body, &scope, &global_this, strict) {
325 Ok(Completion::Normal(v)) | Ok(Completion::Return(v)) => Ok(v),
326 Ok(_) => Ok(Value::Undefined),
327 Err(thrown) => Err(thrown),
328 }
329 }
330
331 pub fn eval_script_source(&mut self, source: &str) -> Result<Value, Value> {
333 crate::os_lib::ecma::parser::note_parse(1, source.len());
334 let mut parser = Parser::new(Lexer::new(source));
335 let (program, top_errs) = parser.parse_program_reporting();
336 if let Some(e) = top_errs.first() {
337 return Err(self.syntax_error(e.message.clone()));
338 }
339 if parser.error_count() > 0 {
340 let msg = parser.errors().first().map(|e| e.message.clone()).unwrap_or_default();
341 return Err(self.syntax_error(msg));
342 }
343 let scope = self.global.clone();
344 let global_this = self.global.borrow().vars.get("globalThis").cloned().unwrap_or(Value::Undefined);
345 match self.exec_top_statements(&program.body, &scope, &global_this) {
346 Ok(Completion::Normal(v)) | Ok(Completion::Return(v)) => Ok(v),
347 Ok(_) => Ok(Value::Undefined),
348 Err(thrown) => Err(thrown),
349 }
350 }
351
352 pub(crate) fn eval_source_in(
354 &mut self,
355 source: &str,
356 scope: &Rc<RefCell<Scope>>,
357 this: &Value,
358 ) -> Result<Value, Value> {
359 crate::os_lib::ecma::parser::note_parse(1, source.len());
361 let mut parser = Parser::new(Lexer::new(source));
362 parser.strict = self.strict;
363 if let Some(ctx) = self.eval_ctx_stack.last() {
364 parser.apply_eval_ctx(ctx);
365 }
366 let (program, errors) = parser.parse_program_reporting();
367 if let Some(err) = errors.first() {
368 let msg = err.message.clone();
369 crate::warn!("[JS] direct eval(): SyntaxError: {}", msg.chars().take(160).collect::<String>());
370 return Err(self.syntax_error(msg));
371 }
372 let eval_strict = body_has_use_strict(&program.body) || self.strict;
373 let eval_scope = if eval_strict {
374 Scope::child(scope.clone())
375 } else {
376 let sc = Scope::block(scope.clone());
377 sc.borrow_mut().is_eval = true;
378 sc
379 };
380 match self.exec_eval_statements(&program.body, &eval_scope, this, eval_strict) {
381 Ok(Completion::Normal(v)) | Ok(Completion::Return(v)) => Ok(v),
382 Ok(_) => Ok(Value::Undefined),
383 Err(thrown) => Err(thrown),
384 }
385 }
386
387 fn exec_eval_statements(
389 &mut self,
390 stmts: &[Statement],
391 eval_scope: &Rc<RefCell<Scope>>,
392 this: &Value,
393 eval_strict: bool,
394 ) -> Result<Completion, Value> {
395 let prev_strict = self.strict;
396 self.strict = eval_strict;
397 let r = (|| -> Result<Completion, Value> {
398 let var_sc = if eval_strict {
399 eval_scope.clone()
400 } else {
401 var_scope(eval_scope)
402 };
403 let var_names = var_names_of(stmts);
404 let top_func_names = top_function_names(stmts);
405 let top_lex_names = collect_top_lexical_names(stmts);
406
407 if !eval_strict {
408 let active_params = self.active_param_names.last();
409 let var_is_param = var_sc.borrow().is_param;
410 let var_is_global = Rc::ptr_eq(&var_sc, &self.global);
411 for n in var_names.iter().chain(top_func_names.iter()) {
412 if top_lex_names.iter().any(|l| l == n) {
413 return Err(self.syntax_error(alloc::format!(
414 "Identifier '{}' has already been declared",
415 n
416 )));
417 }
418 if var_is_param && active_params.is_some_and(|ps| ps.iter().any(|p| p == n)) {
419 return Err(self.syntax_error(alloc::format!(
420 "Identifier '{}' has already been declared",
421 n
422 )));
423 }
424 if has_intervening_lex_binding(eval_scope, &var_sc, n) {
425 return Err(self.syntax_error(alloc::format!(
426 "Identifier '{}' has already been declared",
427 n
428 )));
429 }
430 if var_is_global && self.global_lexicals.borrow().contains(n) {
431 return Err(self.syntax_error(alloc::format!(
432 "Identifier '{}' has already been declared",
433 n
434 )));
435 }
436 }
437 }
438
439 if !eval_strict && !top_lex_names.is_empty() {
440 let mut eb = eval_scope.borrow_mut();
441 eb.tdz = Some(top_lex_names.clone().into_boxed_slice());
442 eb.annex_b_skip = Some(top_lex_names.clone().into_boxed_slice());
443 }
444 let annex_b_funcs = if eval_strict {
445 Vec::new()
446 } else {
447 annex_b_eval_func_names(stmts, &top_lex_names)
448 };
449
450 if Rc::ptr_eq(&var_sc, &self.global) {
451 self.hoist_global_declarations_impl(stmts, &var_sc, this, Some(&var_names), true)?;
452 if !eval_strict && !annex_b_funcs.is_empty() {
453 let g_obj = self.global_object();
454 for fname in &annex_b_funcs {
455 if var_names.iter().any(|v| v == fname)
456 || top_func_names.iter().any(|f| f == fname)
457 {
458 continue;
459 }
460 if has_intervening_lex_binding(eval_scope, &var_sc, fname)
461 || self.global_lexicals.borrow().contains(fname)
462 {
463 continue;
464 }
465 if let Some(ref w) = g_obj {
466 if !can_declare_global_var(w, fname) {
467 continue;
468 }
469 let exists = {
470 let wb = w.borrow();
471 wb.props.contains_key(fname.as_ref()) || wb.has_accessor(fname.as_ref())
472 };
473 if !exists {
474 if !var_sc.borrow().vars.contains_key(fname) {
475 var_sc.borrow_mut().vars.insert(fname.clone(), Value::Undefined);
476 }
477 let mut wb = w.borrow_mut();
478 wb.props.insert(fname.into(), Value::Undefined);
479 wb.insert_attr(
480 fname.as_ref(),
481 PropertyAttributes {
482 writable: true,
483 enumerable: true,
484 configurable: true,
485 },
486 );
487 }
488 } else if !var_sc.borrow().vars.contains_key(fname) {
489 var_sc.borrow_mut().vars.insert(fname.clone(), Value::Undefined);
490 }
491 }
492 }
493 } else {
494 if !var_names.is_empty() {
495 let mut vsc = var_sc.borrow_mut();
496 for n in &var_names {
497 if !vsc.vars.contains_key(n) {
498 vsc.vars.insert(n.clone(), Value::Undefined);
499 }
500 }
501 }
502 for s in stmts {
503 let fdecl = match s {
504 Statement::FunctionDeclaration { .. } => Some(s),
505 Statement::ExportDecl { declaration, .. }
506 if matches!(**declaration, Statement::FunctionDeclaration { .. }) =>
507 {
508 Some(&**declaration)
509 }
510 _ => None,
511 };
512 if let Some(Statement::FunctionDeclaration {
513 name,
514 params,
515 body,
516 is_async,
517 is_generator,
518 }) = fdecl
519 {
520 let f = self.make_function(
521 Some(name.to_string()),
522 params.clone(),
523 body.clone(),
524 false,
525 *is_async,
526 *is_generator,
527 eval_scope,
528 this,
529 );
530 scope_declare(&var_sc, name, f.clone());
531 if !Rc::ptr_eq(&var_sc, eval_scope) {
532 scope_declare(eval_scope, name, f);
533 }
534 }
535 }
536 if !eval_strict && !annex_b_funcs.is_empty() {
537 let active_params = self.active_param_names.last();
538 let var_is_param = var_sc.borrow().is_param;
539 for fname in &annex_b_funcs {
540 if var_names.iter().any(|v| v == fname)
541 || top_func_names.iter().any(|f| f == fname)
542 {
543 continue;
544 }
545 if has_intervening_lex_binding(eval_scope, &var_sc, fname) {
546 continue;
547 }
548 if var_is_param && active_params.is_some_and(|ps| ps.iter().any(|p| p == fname)) {
549 continue;
550 }
551 let mut vsc = var_sc.borrow_mut();
552 if !vsc.vars.contains_key(fname) {
553 vsc.vars.insert(fname.clone(), Value::Undefined);
554 }
555 }
556 }
557 }
558 self.exec_statements_prehoisted(stmts, eval_scope, this)
559 })();
560 self.strict = prev_strict;
561 r
562 }
563
564 pub(crate) fn exec_top_statements(
568 &mut self,
569 stmts: &[Statement],
570 scope: &Rc<RefCell<Scope>>,
571 this: &Value,
572 ) -> Result<Completion, Value> {
573 self.exec_top_statements_strict(stmts, scope, this, false)
574 }
575
576 pub(crate) fn exec_top_statements_strict(
578 &mut self,
579 stmts: &[Statement],
580 scope: &Rc<RefCell<Scope>>,
581 this: &Value,
582 inherit_strict: bool,
583 ) -> Result<Completion, Value> {
584 let prev_strict = self.strict;
585 self.strict = body_has_use_strict(stmts) || (inherit_strict && prev_strict);
586 let r = if Rc::ptr_eq(scope, &self.global) {
587 self.hoist_global_declarations_impl(stmts, scope, this, None, false)
588 .and_then(|_| self.exec_statements_prehoisted(stmts, scope, this))
589 } else {
590 self.hoist_declarations(stmts, scope, this, None);
591 self.exec_statements_prehoisted(stmts, scope, this)
592 };
593 self.strict = prev_strict;
594 r
595 }
596
597 pub(crate) fn exec_statements(
598 &mut self,
599 stmts: &[Statement],
600 scope: &Rc<RefCell<Scope>>,
601 this: &Value,
602 ) -> Result<Completion, Value> {
603 self.exec_statements_hoisted(stmts, scope, this, None)
604 }
605
606 pub(crate) fn exec_statements_hoisted(
608 &mut self,
609 stmts: &[Statement],
610 scope: &Rc<RefCell<Scope>>,
611 this: &Value,
612 hoisted: Option<&[Rc<str>]>,
613 ) -> Result<Completion, Value> {
614 self.hoist_declarations(stmts, scope, this, hoisted);
615 self.exec_statements_prehoisted(stmts, scope, this)
616 }
617
618 pub(crate) fn exec_statements_prehoisted(
620 &mut self,
621 stmts: &[Statement],
622 scope: &Rc<RefCell<Scope>>,
623 this: &Value,
624 ) -> Result<Completion, Value> {
625 let mut disposables: Vec<(Value, bool)> = Vec::new();
632 let mut last = Value::Undefined;
633 let mut outcome: Result<Completion, Value> = Ok(Completion::Normal(Value::Undefined));
634 for s in stmts {
635 if let Statement::VarDeclaration { kind, decls } = s {
636 if matches!(kind, VarKind::Using | VarKind::AwaitUsing) {
637 let is_await = matches!(kind, VarKind::AwaitUsing);
638 if let Err(e) = self.exec_using_decl(decls, is_await, scope, this, &mut disposables) {
639 outcome = Err(e);
640 break;
641 }
642 last = Value::Undefined;
643 continue;
644 }
645 }
646 match self.exec_stmt(s, scope, this) {
647 Ok(Completion::Normal(v)) => {
648 if !matches!(
650 s,
651 Statement::VarDeclaration { .. } | Statement::FunctionDeclaration { .. } | Statement::Empty
652 ) {
653 last = v;
654 }
655 }
656 Ok(other) => {
657 outcome = Ok(other);
658 break;
659 }
660 Err(e) => {
661 outcome = Err(e);
662 break;
663 }
664 }
665 }
666 if disposables.is_empty() {
667 return match outcome {
668 Ok(Completion::Normal(_)) => Ok(Completion::Normal(last)),
669 other => other,
670 };
671 }
672 self.finish_disposables(disposables, outcome, last)
673 }
674
675 #[inline(never)]
678 fn hoist_global_declarations_impl(
679 &mut self,
680 stmts: &[Statement],
681 scope: &Rc<RefCell<Scope>>,
682 this: &Value,
683 hoisted: Option<&[Rc<str>]>,
684 is_eval: bool,
685 ) -> Result<(), Value> {
686 let collected: Vec<Rc<str>>;
687 let var_names: &[Rc<str>] = match hoisted {
688 Some(h) => h,
689 None => {
690 collected = var_names_of(stmts);
691 &collected
692 }
693 };
694 let func_names = top_function_names(stmts);
695
696 if !is_eval {
697 let lex_names = collect_top_lexical_names(stmts);
698 if !lex_names.is_empty() {
699 let mut gl = self.global_lexicals.borrow_mut();
700 for ln in lex_names {
701 gl.insert(ln);
702 }
703 }
704 }
705
706 let g_obj = self.global_object();
707 if let Some(ref w) = g_obj {
708 for fname in &func_names {
709 if self.global_lexicals.borrow().contains(fname) {
710 return Err(self.syntax_error(alloc::format!(
711 "Identifier '{}' has already been declared",
712 fname
713 )));
714 }
715 if !can_declare_global_function(w, fname) {
716 return Err(self.type_error(alloc::format!(
717 "Cannot declare global function '{}'",
718 fname
719 )));
720 }
721 }
722 for vname in var_names {
723 if func_names.iter().any(|f| f == vname) {
724 continue;
725 }
726 if self.global_lexicals.borrow().contains(vname) {
727 return Err(self.syntax_error(alloc::format!(
728 "Identifier '{}' has already been declared",
729 vname
730 )));
731 }
732 if !can_declare_global_var(w, vname) {
733 return Err(self.type_error(alloc::format!(
734 "Cannot declare global variable '{}'",
735 vname
736 )));
737 }
738 }
739 }
740
741 if !var_names.is_empty() {
743 for n in var_names {
744 if func_names.iter().any(|f| f == n) {
745 continue;
746 }
747 if let Some(ref w) = g_obj {
748 let (has_prop, has_acc, existing_val) = {
749 let wb = w.borrow();
750 (
751 wb.props.contains_key(n.as_ref()),
752 wb.has_accessor(n.as_ref()),
753 wb.props.get(n.as_ref()).cloned(),
754 )
755 };
756 if has_prop || has_acc {
757 let mut sc = scope.borrow_mut();
759 if !sc.vars.contains_key(n) {
760 if let Some(v) = existing_val {
761 sc.vars.insert(n.clone(), v);
762 }
763 }
764 } else {
765 let init = {
766 let mut sc = scope.borrow_mut();
767 match sc.vars.get(n).cloned() {
768 Some(v) => v,
769 None => {
770 sc.vars.insert(n.clone(), Value::Undefined);
771 Value::Undefined
772 }
773 }
774 };
775 let mut wb = w.borrow_mut();
776 wb.props.insert(n.into(), init);
777 wb.insert_attr(
778 n.as_ref(),
779 PropertyAttributes {
780 writable: true,
781 enumerable: true,
782 configurable: is_eval,
783 },
784 );
785 }
786 } else {
787 let mut sc = scope.borrow_mut();
788 if !sc.vars.contains_key(n) {
789 sc.vars.insert(n.clone(), Value::Undefined);
790 }
791 }
792 }
793 }
794
795 self.hoist_top_global_function_decls(stmts, scope, this, is_eval);
797 Ok(())
798 }
799
800 #[inline(never)]
802 fn hoist_top_global_function_decls(
803 &mut self,
804 stmts: &[Statement],
805 scope: &Rc<RefCell<Scope>>,
806 this: &Value,
807 is_eval: bool,
808 ) {
809 for s in stmts {
810 let fdecl = match s {
811 Statement::FunctionDeclaration { .. } => Some(s),
812 Statement::ExportDecl { declaration, .. }
813 if matches!(**declaration, Statement::FunctionDeclaration { .. }) =>
814 {
815 Some(&**declaration)
816 }
817 _ => None,
818 };
819 if let Some(Statement::FunctionDeclaration {
820 name,
821 params,
822 body,
823 is_async,
824 is_generator,
825 }) = fdecl
826 {
827 let f = self.make_function(
828 Some(name.to_string()),
829 params.clone(),
830 body.clone(),
831 false,
832 *is_async,
833 *is_generator,
834 scope,
835 this,
836 );
837 scope.borrow_mut().vars.insert(name.clone(), f.clone());
838 if let Some(w) = self.global_object() {
839 sync_global_function_binding(&w, name, f, is_eval);
840 }
841 }
842 }
843 }
844
845 #[inline(never)]
849 pub(crate) fn hoist_declarations(
850 &mut self,
851 stmts: &[Statement],
852 scope: &Rc<RefCell<Scope>>,
853 this: &Value,
854 hoisted: Option<&[Rc<str>]>,
855 ) {
856 if scope.borrow().is_block {
857 let lex = collect_top_lexical_names(stmts);
858 if !lex.is_empty() {
859 scope.borrow_mut().tdz = Some(lex.into_boxed_slice());
860 }
861 } else {
862 let collected: Vec<Rc<str>>;
863 let names: &[Rc<str>] = match hoisted {
864 Some(h) => h,
865 None => {
866 collected = var_names_of(stmts);
867 &collected
868 }
869 };
870 if !names.is_empty() {
871 let is_global = scope.borrow().parent.is_none();
872 let window = if is_global {
873 match scope_get(scope, "globalThis") {
874 Some(Value::Object(w)) => Some(w),
875 _ => None,
876 }
877 } else {
878 None
879 };
880 let mut sc = scope.borrow_mut();
881 for n in names {
882 if sc.vars.contains_key(n) {
883 continue;
884 }
885 let init = window
886 .as_ref()
887 .and_then(|w| w.borrow().props.get(n).cloned())
888 .unwrap_or(Value::Undefined);
889 sc.vars.insert(n.clone(), init);
890 }
891 }
892 }
893 self.hoist_function_decls(stmts, scope, this);
894 }
895
896 #[inline(never)]
898 pub(crate) fn hoist_function_decls(
899 &mut self,
900 stmts: &[Statement],
901 scope: &Rc<RefCell<Scope>>,
902 this: &Value,
903 ) {
904 let is_block = scope.borrow().is_block;
905 let is_scope_global = Rc::ptr_eq(scope, &self.global);
906 for s in stmts {
907 let fdecl = match s {
908 Statement::FunctionDeclaration { .. } => Some(s),
909 Statement::ExportDecl { declaration, .. }
910 if matches!(**declaration, Statement::FunctionDeclaration { .. }) =>
911 {
912 Some(&**declaration)
913 }
914 _ => None,
915 };
916 if let Some(Statement::FunctionDeclaration {
917 name,
918 params,
919 body,
920 is_async,
921 is_generator,
922 }) = fdecl
923 {
924 let f = self.make_function(
925 Some(name.to_string()),
926 params.clone(),
927 body.clone(),
928 false,
929 *is_async,
930 *is_generator,
931 scope,
932 this,
933 );
934 if is_block {
935 let vs = var_scope(scope);
936 let shadowed = has_intervening_lex_binding(scope, &vs, name) || vs.borrow().annex_b_skips(name);
937 if !self.strict && !shadowed {
938 if Rc::ptr_eq(&vs, &self.global) {
939 if let Some(w) = self.global_object() {
940 if can_declare_global_var(&w, name) && !self.global_lexicals.borrow().contains(name) {
941 vs.borrow_mut().vars.insert(name.clone(), f.clone());
942 sync_annex_b_global_function(&w, name, f.clone());
943 }
944 } else {
945 vs.borrow_mut().vars.insert(name.clone(), f.clone());
946 }
947 } else {
948 scope_declare(&vs, name, f.clone());
949 let mut cur = scope.borrow().parent.clone();
952 while let Some(sc) = cur {
953 if Rc::ptr_eq(&sc, &vs) {
954 break;
955 }
956 let next = {
957 let mut b = sc.borrow_mut();
958 let in_tdz = b.tdz.as_ref().is_some_and(|t| t.iter().any(|n| n == name));
959 if !in_tdz && b.vars.contains_key(name) {
960 b.vars.insert(name.clone(), f.clone());
961 }
962 b.parent.clone()
963 };
964 cur = next;
965 }
966 }
967 }
968 scope_declare(scope, name, f);
969 } else if is_scope_global {
970 scope.borrow_mut().vars.insert(name.clone(), f.clone());
973 if let Some(w) = self.global_object() {
974 sync_annex_b_global_function(&w, name, f);
975 }
976 } else {
977 scope_declare(scope, name, f);
978 }
979 }
980 }
981 }
982
983 fn sync_global_var_binding(&self, name: &Rc<str>) {
985 let Some(val) = self.global.borrow().vars.get(name).cloned() else { return };
986 if let Some(orig) = self.sync_global_prop_if_present(name, &val) {
987 self.global.borrow_mut().vars.insert(name.clone(), orig);
988 }
989 }
990
991 #[inline(never)]
992 fn exec_using_decl(
993 &mut self,
994 decls: &[(Pattern, Option<Expression>)],
995 is_await: bool,
996 scope: &Rc<RefCell<Scope>>,
997 this: &Value,
998 disposables: &mut Vec<(Value, bool)>,
999 ) -> Result<(), Value> {
1000 let is_global = Rc::ptr_eq(scope, &self.global);
1001 for (pat, init) in decls {
1002 let v = match init {
1003 Some(e) => self.eval(e, scope, this)?,
1004 None => Value::Undefined,
1005 };
1006 if is_global {
1007 let mut lex_names = Vec::new();
1008 collect_pattern_names(pat, &mut lex_names);
1009 if !lex_names.is_empty() {
1010 let mut gl = self.global_lexicals.borrow_mut();
1011 for n in lex_names {
1012 gl.insert(n);
1013 }
1014 }
1015 }
1016 self.bind_pattern(pat, v.clone(), scope, this)?;
1017 if !matches!(v, Value::Undefined | Value::Null) {
1018 disposables.push((v, is_await));
1019 }
1020 }
1021 Ok(())
1022 }
1023
1024 #[inline(never)]
1025 fn finish_disposables(
1026 &mut self,
1027 disposables: Vec<(Value, bool)>,
1028 outcome: Result<Completion, Value>,
1029 last: Value,
1030 ) -> Result<Completion, Value> {
1031 let mut pending_err: Option<Value> = match &outcome {
1032 Err(e) => Some(e.clone()),
1033 _ => None,
1034 };
1035 for (resource, is_await) in disposables.into_iter().rev() {
1036 let key = if is_await {
1037 "Symbol(Symbol.asyncDispose)"
1038 } else {
1039 "Symbol(Symbol.dispose)"
1040 };
1041 let method = match self.get_property(&resource, key) {
1042 Ok(m) => m,
1043 Err(e) => {
1044 pending_err = Some(self.chain_suppressed(pending_err, e));
1045 continue;
1046 }
1047 };
1048 if matches!(method, Value::Undefined | Value::Null) {
1049 continue;
1050 }
1051 let call_result = self.call_value(&method, resource, &[]);
1052 let dispose_result = match call_result {
1053 Ok(v) if is_await => self.await_value(v),
1054 other => other,
1055 };
1056 if let Err(e) = dispose_result {
1057 pending_err = Some(self.chain_suppressed(pending_err, e));
1058 }
1059 }
1060 if let Some(e) = pending_err {
1061 return Err(e);
1062 }
1063 match outcome {
1064 Ok(Completion::Normal(_)) => Ok(Completion::Normal(last)),
1065 other => other,
1066 }
1067 }
1068
1069 pub(crate) fn exec_stmt(
1070 &mut self,
1071 stmt: &Statement,
1072 scope: &Rc<RefCell<Scope>>,
1073 this: &Value,
1074 ) -> Result<Completion, Value> {
1075 if self.tick() {
1076 return Err(Value::Undefined);
1077 }
1078 let gen_stmt_idx = if let Some(r) = &mut self.gen_replay {
1079 if r.gen_depth == self.depth {
1080 let idx = r.stmt_cursor;
1081 if let Some(Some((end_stmt, end_scope, end_ctx, end_counter, val))) =
1082 r.done_stmts.get(idx).cloned()
1083 {
1084 r.stmt_cursor = end_stmt;
1085 r.scope_cursor = end_scope;
1086 r.counter = end_counter;
1087 if let Some(ctx_obj) = r.gen_ctx.as_ref() {
1088 if let ObjKind::Array(items) = &mut ctx_obj.borrow_mut().kind {
1089 if items.len() >= 2 {
1090 items[1] = Value::Number(end_ctx as f64);
1091 }
1092 }
1093 }
1094 return Ok(Completion::Normal(val));
1095 }
1096 r.stmt_cursor += 1;
1097 if idx >= r.done_stmts.len() {
1098 r.done_stmts.resize(idx + 1, None);
1099 }
1100 Some(idx)
1101 } else {
1102 None
1103 }
1104 } else {
1105 None
1106 };
1107 let res = self.exec_stmt_inner(stmt, scope, this);
1108 if let (Some(idx), Ok(Completion::Normal(v))) = (gen_stmt_idx, &res) {
1109 if let Some(r) = &mut self.gen_replay {
1110 if r.gen_depth == self.depth && !r.suspending && r.returning.is_none() {
1111 let end_stmt = r.stmt_cursor;
1112 let end_scope = r.scope_cursor;
1113 let end_counter = r.counter;
1114 let end_ctx = r
1115 .gen_ctx
1116 .as_ref()
1117 .and_then(|ctx_obj| match &ctx_obj.borrow().kind {
1118 ObjKind::Array(items) => match items.get(1) {
1119 Some(Value::Number(n)) => Some(*n as usize),
1120 _ => None,
1121 },
1122 _ => None,
1123 })
1124 .unwrap_or(0);
1125 if let Some(slot) = r.done_stmts.get_mut(idx) {
1126 *slot = Some((end_stmt, end_scope, end_ctx, end_counter, v.clone()));
1127 }
1128 }
1129 }
1130 }
1131 res
1132 }
1133
1134 fn eval_gen_cached(
1137 &mut self,
1138 expr: &Expression,
1139 scope: &Rc<RefCell<Scope>>,
1140 this: &Value,
1141 ) -> EvalResult {
1142 let gen_idx = if let Some(r) = &mut self.gen_replay {
1143 if r.gen_depth == self.depth {
1144 let idx = r.stmt_cursor;
1145 if let Some(Some((end_stmt, end_scope, end_ctx, end_counter, val))) =
1146 r.done_stmts.get(idx).cloned()
1147 {
1148 r.stmt_cursor = end_stmt;
1149 r.scope_cursor = end_scope;
1150 r.counter = end_counter;
1151 if let Some(ctx_obj) = r.gen_ctx.as_ref() {
1152 if let ObjKind::Array(items) = &mut ctx_obj.borrow_mut().kind {
1153 if items.len() >= 2 {
1154 items[1] = Value::Number(end_ctx as f64);
1155 }
1156 }
1157 }
1158 return Ok(val);
1159 }
1160 r.stmt_cursor += 1;
1161 if idx >= r.done_stmts.len() {
1162 r.done_stmts.resize(idx + 1, None);
1163 }
1164 Some(idx)
1165 } else {
1166 None
1167 }
1168 } else {
1169 None
1170 };
1171 let res = self.eval(expr, scope, this);
1172 if let (Some(idx), Ok(v)) = (gen_idx, &res) {
1173 if let Some(r) = &mut self.gen_replay {
1174 if r.gen_depth == self.depth && !r.suspending && r.returning.is_none() {
1175 let end_stmt = r.stmt_cursor;
1176 let end_scope = r.scope_cursor;
1177 let end_counter = r.counter;
1178 let end_ctx = r
1179 .gen_ctx
1180 .as_ref()
1181 .and_then(|ctx_obj| match &ctx_obj.borrow().kind {
1182 ObjKind::Array(items) => match items.get(1) {
1183 Some(Value::Number(n)) => Some(*n as usize),
1184 _ => None,
1185 },
1186 _ => None,
1187 })
1188 .unwrap_or(0);
1189 if let Some(slot) = r.done_stmts.get_mut(idx) {
1190 *slot = Some((end_stmt, end_scope, end_ctx, end_counter, v.clone()));
1191 }
1192 }
1193 }
1194 }
1195 res
1196 }
1197
1198 fn exec_stmt_inner(
1199 &mut self,
1200 stmt: &Statement,
1201 scope: &Rc<RefCell<Scope>>,
1202 this: &Value,
1203 ) -> Result<Completion, Value> {
1204 match stmt {
1205 Statement::Empty => Ok(Completion::Normal(Value::Undefined)),
1206 Statement::Expression(e) => {
1207 let v = self.eval(e, scope, this)?;
1208 Ok(Completion::Normal(v))
1209 }
1210 Statement::VarDeclaration { kind, decls } => {
1211 self.exec_var_decl(kind, decls, scope, this)
1212 }
1213 Statement::Block(body) => self.exec_block(body, scope, this),
1214 Statement::FunctionDeclaration { .. } => {
1215 Ok(Completion::Normal(Value::Undefined))
1217 }
1218 Statement::If {
1219 test,
1220 consequent,
1221 alternate,
1222 } => {
1223 if self.eval(test, scope, this)?.truthy() {
1224 if matches!(&**consequent, Statement::FunctionDeclaration { .. }) {
1225 let bs = self.alloc_block_scope(scope.clone());
1226 self.hoist_function_decls(core::slice::from_ref(consequent), &bs, this);
1227 self.recycle_block_scope(bs);
1228 Ok(Completion::Normal(Value::Undefined))
1229 } else {
1230 self.exec_stmt(consequent, scope, this)
1231 }
1232 } else if let Some(alt) = alternate {
1233 if matches!(&**alt, Statement::FunctionDeclaration { .. }) {
1234 let bs = self.alloc_block_scope(scope.clone());
1235 self.hoist_function_decls(core::slice::from_ref(alt), &bs, this);
1236 self.recycle_block_scope(bs);
1237 Ok(Completion::Normal(Value::Undefined))
1238 } else {
1239 self.exec_stmt(alt, scope, this)
1240 }
1241 } else {
1242 Ok(Completion::Normal(Value::Undefined))
1243 }
1244 }
1245 Statement::While { test, body } => self.exec_while(test, body, scope, this),
1246 Statement::DoWhile { body, test } => self.exec_do_while(body, test, scope, this),
1247 Statement::For {
1248 init,
1249 test,
1250 update,
1251 body,
1252 } => self.exec_for(
1253 init.as_deref(),
1254 test.as_deref(),
1255 update.as_deref(),
1256 body,
1257 scope,
1258 this,
1259 ),
1260 Statement::ForIn {
1261 decl_kind,
1262 pattern,
1263 object,
1264 body,
1265 of,
1266 is_await,
1267 } => self.exec_for_in(decl_kind, pattern, object, body, *of, *is_await, scope, this),
1268 Statement::Return(e) => {
1269 let v = match e {
1270 Some(e) => self.eval(e, scope, this)?,
1271 None => Value::Undefined,
1272 };
1273 Ok(Completion::Return(v))
1274 }
1275 Statement::Break(label) => Ok(Completion::Break(label.clone())),
1276 Statement::Continue(label) => Ok(Completion::Continue(label.clone())),
1277 Statement::Labeled(label, inner) => self.exec_labeled(label, inner, scope, this),
1278 Statement::With { object, body } => {
1279 let ov = self.eval(object, scope, this)?;
1280 if matches!(ov, Value::Undefined | Value::Null) {
1281 return Err(self.type_error(alloc::format!(
1282 "Cannot convert {} to object",
1283 ov.to_js_string()
1284 )));
1285 }
1286 let obj_val = if matches!(ov, Value::Object(_)) {
1287 ov
1288 } else {
1289 super::super::builtins::object_ctor(self, Value::Undefined, core::slice::from_ref(&ov))?
1290 };
1291 let Value::Object(wobj) = obj_val else {
1292 return Err(self.type_error("with expression is not an object"));
1293 };
1294 let wscope = Scope::new_with(scope.clone(), wobj);
1295 self.exec_stmt(body, &wscope, this)
1296 }
1297 Statement::Switch {
1298 discriminant,
1299 cases,
1300 } => self.exec_switch(discriminant, cases, scope, this),
1301 Statement::Throw(e) => {
1302 let v = self.eval(e, scope, this)?;
1303 self.note_thrown_value(&v);
1304 Err(v)
1305 }
1306 Statement::Try(t) => self.exec_try(t, scope, this),
1307 Statement::InitPrivateBrand(brand) => {
1308 let eff_this = self.resolve_this(scope, this)?;
1309 if let Value::Object(o) = eff_this {
1310 if o.borrow().has_private_brand(*brand) {
1311 return Err(self.type_error("Cannot initialize private methods of class twice on the same object"));
1312 }
1313 if o.borrow().is_non_extensible() {
1314 return Err(self.type_error("Cannot define private methods on a non-extensible object"));
1315 }
1316 o.borrow_mut().add_private_brand(*brand);
1317 }
1318 Ok(Completion::Normal(Value::Undefined))
1319 }
1320 Statement::InitPrivateField { brand, name, init } => {
1321 let eff_this = self.resolve_this(scope, this)?;
1322 let val = match init {
1323 Some(e) => self.eval(e, scope, &eff_this)?,
1324 None => Value::Undefined,
1325 };
1326 let Value::Object(o) = eff_this else {
1327 return Err(self.type_error("Cannot define private field on non-object"));
1328 };
1329 if o.borrow().is_non_extensible() {
1330 return Err(self.type_error("Cannot define private field on a non-extensible object"));
1331 }
1332 if !o.borrow_mut().define_private_field(*brand, name.clone(), val) {
1333 return Err(self.type_error(alloc::format!(
1334 "Cannot initialize private field {} twice on the same object",
1335 name
1336 )));
1337 }
1338 Ok(Completion::Normal(Value::Undefined))
1339 }
1340 Statement::InitPublicField { key, init } => {
1341 let eff_this = self.resolve_this(scope, this)?;
1342 let val = match init {
1343 Some(e) => {
1344 let v = self.eval(e, scope, &eff_this)?;
1345 if matches!(&**e, Expression::Function { name: None, .. } | Expression::Class { name: None, .. }) {
1346 infer_function_name(&v, &super::fn_name_from_key(key));
1347 }
1348 v
1349 }
1350 None => Value::Undefined,
1351 };
1352 self.define_public_field(&eff_this, key, val)?;
1353 Ok(Completion::Normal(Value::Undefined))
1354 }
1355 Statement::ClassFieldInit { stmts, priv_names } => {
1356 self.eval_ctx_stack.push(crate::os_lib::ecma::ast::EvalSyntaxCtx {
1357 in_function: false,
1358 allow_super_call: false,
1359 allow_super_prop: true,
1360 in_field_init: true,
1361 in_static_block: false,
1362 private_names: priv_names.clone(),
1363 });
1364 let res = self.exec_statements_prehoisted(stmts, scope, this);
1365 self.eval_ctx_stack.pop();
1366 res
1367 }
1368 Statement::Import(_)
1369 | Statement::ExportDefault(_)
1370 | Statement::ExportDecl { .. }
1371 | Statement::ExportNamed { .. }
1372 | Statement::ExportAll { .. } => self.exec_module_stmt(stmt, scope, this),
1373 }
1374 }
1375
1376 pub(crate) fn define_public_field(&mut self, target: &Value, key: &str, val: Value) -> Result<(), Value> {
1378 if let Value::Object(o) = target {
1379 let mut b = o.borrow_mut();
1380 if matches!(b.kind, ObjKind::Plain)
1381 && !b.is_frozen()
1382 && !b.is_sealed()
1383 && !b.is_non_extensible()
1384 && b.primitive().is_none()
1385 && !b.has_accessor(key)
1386 && b.get_attr(key).is_none()
1387 {
1388 b.props.insert(key.into(), val);
1389 return Ok(());
1390 }
1391 }
1392 super::super::builtins::create_data_property_or_throw(self, target, key, val)
1393 }
1394
1395 #[inline(never)]
1396 fn exec_var_decl(
1397 &mut self,
1398 kind: &VarKind,
1399 decls: &[(Pattern, Option<Expression>)],
1400 scope: &Rc<RefCell<Scope>>,
1401 this: &Value,
1402 ) -> Result<Completion, Value> {
1403 let is_var = matches!(kind, VarKind::Var);
1404 let target = if is_var { var_scope(scope) } else { scope.clone() };
1405 let is_global = Rc::ptr_eq(&target, &self.global);
1406 for (pat, init) in decls {
1407 if init.is_none() && is_var {
1408 if let Pattern::Identifier(name) = pat {
1409 if target.borrow().vars.contains_key(name) {
1410 continue;
1411 }
1412 }
1413 }
1414 let with_target = if is_var && init.is_some() && scope.borrow().has_with {
1415 if let Pattern::Identifier(name) = pat {
1416 self.resolve_with_scope(scope, name)?
1417 } else {
1418 None
1419 }
1420 } else {
1421 None
1422 };
1423 let v = match init {
1424 Some(e) => self.eval(e, scope, this)?,
1425 None => Value::Undefined,
1426 };
1427 if let Pattern::Identifier(name) = pat {
1428 infer_function_name(&v, name);
1429 }
1430 if let (Some((wobj, _)), Pattern::Identifier(name)) = (with_target, pat) {
1431 self.with_set_mutable_binding(&wobj, name, v)?;
1432 continue;
1433 }
1434 if is_global && !is_var {
1435 let mut lex_names = Vec::new();
1437 collect_pattern_names(pat, &mut lex_names);
1438 if !lex_names.is_empty() {
1439 let mut gl = self.global_lexicals.borrow_mut();
1440 for n in lex_names {
1441 gl.insert(n);
1442 }
1443 }
1444 }
1445 if is_global && is_var {
1446 if let Pattern::Identifier(name) = pat {
1447 if let Some(w) = self.global_object() {
1448 if w.borrow().has_accessor(name.as_ref()) {
1449 self.set_property(&Value::Object(w), name, v);
1450 continue;
1451 }
1452 if w.borrow().get_attr(name.as_ref()).is_some_and(|a| !a.writable) {
1453 continue;
1454 }
1455 }
1456 }
1457 }
1458 self.bind_pattern(pat, v, &target, this)?;
1459 if is_global && is_var {
1460 let mut names = Vec::new();
1461 collect_pattern_names(pat, &mut names);
1462 for n in &names {
1463 self.sync_global_var_binding(n);
1464 }
1465 }
1466 }
1467 Ok(Completion::Normal(Value::Undefined))
1468 }
1469
1470 #[inline(never)]
1471 fn exec_block(
1472 &mut self,
1473 body: &[Statement],
1474 scope: &Rc<RefCell<Scope>>,
1475 this: &Value,
1476 ) -> Result<Completion, Value> {
1477 if block_has_lexical(body) {
1478 let inner = self.alloc_block_scope(scope.clone());
1479 let res = self.exec_statements(body, &inner, this);
1480 self.recycle_block_scope(inner);
1481 res
1482 } else {
1483 self.exec_statements_hoisted(body, scope, this, Some(&[]))
1484 }
1485 }
1486
1487 #[inline(never)]
1488 fn exec_while(
1489 &mut self,
1490 test: &Expression,
1491 body: &Statement,
1492 scope: &Rc<RefCell<Scope>>,
1493 this: &Value,
1494 ) -> Result<Completion, Value> {
1495 let own_label = self.pending_label.take();
1496 while self.eval_gen_cached(test, scope, this)?.truthy() {
1497 if self.tick() {
1498 return Err(Value::Undefined);
1499 }
1500 match self.exec_stmt(body, scope, this)? {
1501 Completion::Break(lbl) if lbl.is_none() || lbl == own_label => break,
1502 Completion::Break(lbl) => return Ok(Completion::Break(lbl)),
1503 Completion::Continue(lbl) if lbl.is_none() || lbl == own_label => {}
1504 Completion::Continue(lbl) => return Ok(Completion::Continue(lbl)),
1505 Completion::Normal(_) => {}
1506 ret @ Completion::Return(_) => return Ok(ret),
1507 }
1508 }
1509 Ok(Completion::Normal(Value::Undefined))
1510 }
1511
1512 #[inline(never)]
1513 fn exec_do_while(
1514 &mut self,
1515 body: &Statement,
1516 test: &Expression,
1517 scope: &Rc<RefCell<Scope>>,
1518 this: &Value,
1519 ) -> Result<Completion, Value> {
1520 let own_label = self.pending_label.take();
1521 loop {
1522 if self.tick() {
1523 return Err(Value::Undefined);
1524 }
1525 match self.exec_stmt(body, scope, this)? {
1526 Completion::Break(lbl) if lbl.is_none() || lbl == own_label => break,
1527 Completion::Break(lbl) => return Ok(Completion::Break(lbl)),
1528 Completion::Continue(lbl) if lbl.is_none() || lbl == own_label => {}
1529 Completion::Continue(lbl) => return Ok(Completion::Continue(lbl)),
1530 Completion::Normal(_) => {}
1531 ret @ Completion::Return(_) => return Ok(ret),
1532 }
1533 if !self.eval_gen_cached(test, scope, this)?.truthy() {
1534 break;
1535 }
1536 }
1537 Ok(Completion::Normal(Value::Undefined))
1538 }
1539
1540 #[inline(never)]
1541 fn exec_labeled(
1542 &mut self,
1543 label: &Rc<str>,
1544 inner: &Statement,
1545 scope: &Rc<RefCell<Scope>>,
1546 this: &Value,
1547 ) -> Result<Completion, Value> {
1548 self.pending_label = if matches!(
1549 inner,
1550 Statement::While { .. } | Statement::DoWhile { .. } | Statement::For { .. } | Statement::ForIn { .. }
1551 ) {
1552 Some(label.clone())
1553 } else {
1554 None
1555 };
1556 match self.exec_stmt(inner, scope, this)? {
1557 Completion::Break(Some(lbl)) if lbl == *label => {
1558 Ok(Completion::Normal(Value::Undefined))
1559 }
1560 other => Ok(other),
1561 }
1562 }
1563
1564 #[inline(never)]
1565 fn exec_for(
1566 &mut self,
1567 init: Option<&Statement>,
1568 test: Option<&Expression>,
1569 update: Option<&Expression>,
1570 body: &Statement,
1571 scope: &Rc<RefCell<Scope>>,
1572 this: &Value,
1573 ) -> Result<Completion, Value> {
1574 let own_label = self.pending_label.take();
1575 let is_let_like = matches!(
1576 init,
1577 Some(Statement::VarDeclaration {
1578 kind: VarKind::Let | VarKind::Const,
1579 ..
1580 })
1581 );
1582 let mut loop_scope = if is_let_like {
1583 self.alloc_block_scope(scope.clone())
1584 } else {
1585 scope.clone()
1586 };
1587 if let Some(init) = init {
1588 self.exec_stmt(init, &loop_scope, this)?;
1589 }
1590 let let_names: Vec<Rc<str>> = if is_let_like {
1591 loop_scope.borrow().vars.keys().cloned().collect()
1592 } else {
1593 Vec::new()
1594 };
1595 let loop_res = (|| -> Result<Completion, Value> {
1596 loop {
1597 if let Some(t) = test {
1598 if !self.eval_gen_cached(t, &loop_scope, this)?.truthy() {
1599 break;
1600 }
1601 }
1602 if self.tick() {
1603 return Err(Value::Undefined);
1604 }
1605 match self.exec_stmt(body, &loop_scope, this)? {
1606 Completion::Break(lbl) if lbl.is_none() || lbl == own_label => break,
1607 Completion::Break(lbl) => return Ok(Completion::Break(lbl)),
1608 Completion::Continue(lbl) if lbl.is_none() || lbl == own_label => {}
1609 Completion::Continue(lbl) => return Ok(Completion::Continue(lbl)),
1610 Completion::Normal(_) => {}
1611 ret @ Completion::Return(_) => return Ok(ret),
1612 }
1613 if is_let_like && Rc::strong_count(&loop_scope) > 1 {
1614 let already_saved = matches!(
1615 &self.gen_replay,
1616 Some(r) if r.gen_depth == self.depth && r.scope_cursor < r.saved_scopes.len()
1617 );
1618 let next_scope = self.alloc_block_scope(scope.clone());
1619 if !already_saved {
1620 for name in &let_names {
1621 let v = scope_get(&loop_scope, name).unwrap_or(Value::Undefined);
1622 next_scope.borrow_mut().vars.insert(name.clone(), v);
1623 }
1624 }
1625 loop_scope = next_scope;
1626 }
1627 if let Some(u) = update {
1628 self.eval_gen_cached(u, &loop_scope, this)?;
1629 }
1630 }
1631 Ok(Completion::Normal(Value::Undefined))
1632 })();
1633 if is_let_like {
1634 self.recycle_block_scope(loop_scope);
1635 }
1636 loop_res
1637 }
1638
1639 #[inline(never)]
1640 #[allow(clippy::too_many_arguments)]
1641 fn exec_for_in(
1642 &mut self,
1643 decl_kind: &Option<VarKind>,
1644 pattern: &Pattern,
1645 object: &Expression,
1646 body: &Statement,
1647 of: bool,
1648 is_await: bool,
1649 scope: &Rc<RefCell<Scope>>,
1650 this: &Value,
1651 ) -> Result<Completion, Value> {
1652 let own_label = self.pending_label.take();
1653 let is_let_like = matches!(
1654 decl_kind,
1655 Some(VarKind::Let | VarKind::Const | VarKind::Using | VarKind::AwaitUsing)
1656 );
1657 let obj = match self.forof_preset.take() {
1659 Some(v) => v,
1660 None => {
1661 if is_let_like {
1662 let tdz_scope = self.alloc_block_scope(scope.clone());
1663 let mut names = Vec::new();
1664 collect_pattern_names(pattern, &mut names);
1665 if !names.is_empty() {
1666 tdz_scope.borrow_mut().tdz = Some(names.into_boxed_slice());
1667 }
1668 let res = self.eval(object, &tdz_scope, this);
1669 self.recycle_block_scope(tdz_scope);
1670 res?
1671 } else {
1672 self.eval(object, scope, this)?
1673 }
1674 }
1675 };
1676 let mut iter_scope_slot: Option<Rc<RefCell<Scope>>> = None;
1677
1678 if of && is_await {
1679 let async_iter_method = self.get_property(&obj, "Symbol(Symbol.asyncIterator)")?;
1680 if !matches!(async_iter_method, Value::Undefined | Value::Null) {
1681 let iterator = self.call_value(&async_iter_method, obj, &[])?;
1682 loop {
1683 if self.tick() {
1684 return Err(Value::Undefined);
1685 }
1686 let next_fn = self.get_property(&iterator, "next")?;
1687 let result = self.call_value(&next_fn, iterator.clone(), &[])?;
1688 let awaited = self.await_value(result)?;
1689 let done = self.get_property(&awaited, "done")?.truthy();
1690 if done {
1691 break;
1692 }
1693 let value = self.get_property(&awaited, "value")?;
1694 let iter_scope = if is_let_like {
1695 match &iter_scope_slot {
1696 Some(sc) if Rc::strong_count(sc) == 1 => {
1697 sc.borrow_mut().vars.clear_keep_capacity();
1698 sc.clone()
1699 }
1700 _ => {
1701 let sc = self.alloc_block_scope(scope.clone());
1702 iter_scope_slot = Some(sc.clone());
1703 sc
1704 }
1705 }
1706 } else {
1707 scope.clone()
1708 };
1709 self.bind_pattern(pattern, value, &iter_scope, this)?;
1710 if matches!(decl_kind, Some(VarKind::Var)) && Rc::ptr_eq(&iter_scope, &self.global) {
1711 self.sync_global_pattern(pattern);
1712 }
1713 match self.exec_stmt(body, &iter_scope, this)? {
1714 Completion::Break(lbl) if lbl.is_none() || lbl == own_label => break,
1715 Completion::Break(lbl) => return Ok(Completion::Break(lbl)),
1716 Completion::Continue(lbl) if lbl.is_none() || lbl == own_label => {}
1717 Completion::Continue(lbl) => return Ok(Completion::Continue(lbl)),
1718 Completion::Normal(_) => {}
1719 ret @ Completion::Return(_) => return Ok(ret),
1720 }
1721 }
1722 if let Some(sc) = iter_scope_slot {
1723 self.recycle_block_scope(sc);
1724 }
1725 return Ok(Completion::Normal(Value::Undefined));
1726 }
1727 if let Some((iterator, next_fn)) = self.open_lazy_iterator(&obj)? {
1728 let loop_res: Result<Option<Completion>, Value> = (|| {
1729 loop {
1730 if self.tick() {
1731 return Err(Value::Undefined);
1732 }
1733 let Some(item) = self.iter_step_once(&next_fn, &iterator)? else {
1734 break;
1735 };
1736 let awaited = match self.await_value(item) {
1737 Ok(v) => v,
1738 Err(e) => {
1739 let _ = self.iterator_close(&iterator);
1740 return Err(e);
1741 }
1742 };
1743 let iter_scope = if is_let_like {
1744 match &iter_scope_slot {
1745 Some(sc) if Rc::strong_count(sc) == 1 => {
1746 sc.borrow_mut().vars.clear_keep_capacity();
1747 sc.clone()
1748 }
1749 _ => {
1750 let sc = self.alloc_block_scope(scope.clone());
1751 iter_scope_slot = Some(sc.clone());
1752 sc
1753 }
1754 }
1755 } else {
1756 scope.clone()
1757 };
1758 if let Err(e) = self.bind_pattern(pattern, awaited, &iter_scope, this) {
1759 let _ = self.iterator_close(&iterator);
1760 return Err(e);
1761 }
1762 if matches!(decl_kind, Some(VarKind::Var)) && Rc::ptr_eq(&iter_scope, &self.global) {
1763 self.sync_global_pattern(pattern);
1764 }
1765 match self.exec_stmt(body, &iter_scope, this) {
1766 Ok(Completion::Break(lbl)) if lbl.is_none() || lbl == own_label => {
1767 self.iterator_close(&iterator)?;
1768 break;
1769 }
1770 Ok(Completion::Break(lbl)) => {
1771 self.iterator_close(&iterator)?;
1772 return Ok(Some(Completion::Break(lbl)));
1773 }
1774 Ok(Completion::Continue(lbl)) if lbl.is_none() || lbl == own_label => {}
1775 Ok(Completion::Continue(lbl)) => {
1776 self.iterator_close(&iterator)?;
1777 return Ok(Some(Completion::Continue(lbl)));
1778 }
1779 Ok(Completion::Normal(_)) => {}
1780 Ok(ret @ Completion::Return(_)) => {
1781 self.iterator_close(&iterator)?;
1782 return Ok(Some(ret));
1783 }
1784 Err(e) => {
1785 let _ = self.iterator_close(&iterator);
1786 return Err(e);
1787 }
1788 }
1789 }
1790 Ok(None)
1791 })();
1792 if let Some(sc) = iter_scope_slot {
1793 self.recycle_block_scope(sc);
1794 }
1795 return match loop_res? {
1796 Some(c) => Ok(c),
1797 None => Ok(Completion::Normal(Value::Undefined)),
1798 };
1799 }
1800 let items = self.iterate_values(&obj, true)?;
1801 for item in items {
1802 if self.tick() {
1803 return Err(Value::Undefined);
1804 }
1805 let awaited = self.await_value(item)?;
1806 let iter_scope = if is_let_like {
1807 match &iter_scope_slot {
1808 Some(sc) if Rc::strong_count(sc) == 1 => {
1809 sc.borrow_mut().vars.clear_keep_capacity();
1810 sc.clone()
1811 }
1812 _ => {
1813 let sc = self.alloc_block_scope(scope.clone());
1814 iter_scope_slot = Some(sc.clone());
1815 sc
1816 }
1817 }
1818 } else {
1819 scope.clone()
1820 };
1821 self.bind_pattern(pattern, awaited, &iter_scope, this)?;
1822 if matches!(decl_kind, Some(VarKind::Var)) && Rc::ptr_eq(&iter_scope, &self.global) {
1823 self.sync_global_pattern(pattern);
1824 }
1825 match self.exec_stmt(body, &iter_scope, this)? {
1826 Completion::Break(lbl) if lbl.is_none() || lbl == own_label => break,
1827 Completion::Break(lbl) => return Ok(Completion::Break(lbl)),
1828 Completion::Continue(lbl) if lbl.is_none() || lbl == own_label => {}
1829 Completion::Continue(lbl) => return Ok(Completion::Continue(lbl)),
1830 Completion::Normal(_) => {}
1831 ret @ Completion::Return(_) => return Ok(ret),
1832 }
1833 }
1834 if let Some(sc) = iter_scope_slot {
1835 self.recycle_block_scope(sc);
1836 }
1837 return Ok(Completion::Normal(Value::Undefined));
1838 }
1839 if of {
1842 if let Some((iterator, next_fn)) = self.open_lazy_iterator(&obj)? {
1843 return self.for_of_lazy(
1844 &iterator, &next_fn, decl_kind, pattern, body, is_let_like, own_label, scope, this,
1845 );
1846 }
1847 }
1848 let mut deferred = None;
1849 let mut cptn = Value::Undefined;
1850 let items = self.iterate_values_deferred(&obj, of, &mut deferred)?;
1851 for item in items {
1852 if self.tick() {
1853 return Err(Value::Undefined);
1854 }
1855 let iter_scope = if is_let_like {
1856 match &iter_scope_slot {
1857 Some(sc) if Rc::strong_count(sc) == 1 => {
1858 sc.borrow_mut().vars.clear_keep_capacity();
1859 sc.clone()
1860 }
1861 _ => {
1862 let sc = self.alloc_block_scope(scope.clone());
1863 iter_scope_slot = Some(sc.clone());
1864 sc
1865 }
1866 }
1867 } else {
1868 scope.clone()
1869 };
1870 self.bind_pattern(pattern, item, &iter_scope, this)?;
1871 if matches!(decl_kind, Some(VarKind::Var)) && Rc::ptr_eq(&iter_scope, &self.global) {
1872 self.sync_global_pattern(pattern);
1873 }
1874 match self.exec_stmt(body, &iter_scope, this)? {
1875 Completion::Break(lbl) if lbl.is_none() || lbl == own_label => {
1876 deferred = None;
1877 break;
1878 }
1879 Completion::Break(lbl) => return Ok(Completion::Break(lbl)),
1880 Completion::Continue(lbl) if lbl.is_none() || lbl == own_label => {}
1881 Completion::Continue(lbl) => return Ok(Completion::Continue(lbl)),
1882 Completion::Normal(v) => {
1883 if of && !matches!(v, Value::Undefined) {
1884 cptn = v;
1885 }
1886 }
1887 ret @ Completion::Return(_) => return Ok(ret),
1888 }
1889 }
1890 if let Some(sc) = iter_scope_slot {
1891 self.recycle_block_scope(sc);
1892 }
1893 if let Some(e) = deferred {
1894 return Err(e);
1895 }
1896 Ok(Completion::Normal(if of { cptn } else { Value::Undefined }))
1897 }
1898
1899 #[inline(never)]
1901 #[allow(clippy::too_many_arguments)]
1902 fn for_of_lazy(
1903 &mut self,
1904 iterator: &Value,
1905 next_fn: &Value,
1906 decl_kind: &Option<VarKind>,
1907 pattern: &Pattern,
1908 body: &Statement,
1909 is_let_like: bool,
1910 own_label: Option<Rc<str>>,
1911 scope: &Rc<RefCell<Scope>>,
1912 this: &Value,
1913 ) -> Result<Completion, Value> {
1914 let mut iter_scope_slot: Option<Rc<RefCell<Scope>>> = None;
1915 let mut cptn = Value::Undefined;
1916 let result = loop {
1917 if self.tick() {
1918 return Err(Value::Undefined);
1919 }
1920 let item = match self.iter_step_once(next_fn, iterator) {
1922 Ok(Some(v)) => v,
1923 Ok(None) => break Ok(Completion::Normal(cptn.clone())),
1924 Err(e) => break Err(e),
1925 };
1926 let iter_scope = if is_let_like {
1927 match &iter_scope_slot {
1928 Some(sc) if Rc::strong_count(sc) == 1 => {
1929 sc.borrow_mut().vars.clear_keep_capacity();
1930 sc.clone()
1931 }
1932 _ => {
1933 let sc = self.alloc_block_scope(scope.clone());
1934 iter_scope_slot = Some(sc.clone());
1935 sc
1936 }
1937 }
1938 } else {
1939 scope.clone()
1940 };
1941 let step = (|| -> Result<Completion, Value> {
1942 self.bind_pattern(pattern, item, &iter_scope, this)?;
1943 if matches!(decl_kind, Some(VarKind::Var)) && Rc::ptr_eq(&iter_scope, &self.global) {
1944 self.sync_global_pattern(pattern);
1945 }
1946 self.exec_stmt(body, &iter_scope, this)
1947 })();
1948 match step {
1949 Err(e) => {
1950 if self.aborted || self.is_suspending() || self.is_gen_returning() {
1952 break Err(e);
1953 }
1954 let _ = self.iterator_close(iterator);
1955 break Err(e);
1956 }
1957 Ok(Completion::Continue(lbl)) if lbl.is_none() || lbl == own_label => {}
1958 Ok(Completion::Normal(v)) => {
1959 if !matches!(v, Value::Undefined) {
1960 cptn = v;
1961 }
1962 }
1963 Ok(Completion::Break(lbl)) if lbl.is_none() || lbl == own_label => {
1964 break self.iterator_close(iterator).map(|_| Completion::Normal(cptn.clone()));
1965 }
1966 Ok(other) => {
1967 break self.iterator_close(iterator).map(|_| other);
1969 }
1970 }
1971 };
1972 if let Some(sc) = iter_scope_slot {
1973 self.recycle_block_scope(sc);
1974 }
1975 result
1976 }
1977
1978 #[inline(never)]
1979 fn exec_switch(
1980 &mut self,
1981 discriminant: &Expression,
1982 cases: &[SwitchCase],
1983 scope: &Rc<RefCell<Scope>>,
1984 this: &Value,
1985 ) -> Result<Completion, Value> {
1986 let d = self.eval(discriminant, scope, this)?;
1987 let has_lex = cases.iter().any(|c| super::block_has_lexical(&c.body));
1988 let switch_sc = if has_lex {
1989 let sc = self.alloc_block_scope(scope.clone());
1990 let mut lex = Vec::new();
1991 for c in cases {
1992 lex.extend(collect_top_lexical_names(&c.body));
1993 }
1994 if !lex.is_empty() {
1995 sc.borrow_mut().tdz = Some(lex.into_boxed_slice());
1996 }
1997 for c in cases {
1998 self.hoist_function_decls(&c.body, &sc, this);
1999 }
2000 Some(sc)
2001 } else {
2002 None
2003 };
2004 let run_sc = switch_sc.as_ref().unwrap_or(scope);
2005 let res = (|| -> Result<Completion, Value> {
2006 let mut start = None;
2007 for (i, c) in cases.iter().enumerate() {
2008 if let Some(test) = &c.test {
2009 let tv = self.eval(test, run_sc, this)?;
2010 if d.strict_eq(&tv) {
2011 start = Some(i);
2012 break;
2013 }
2014 }
2015 }
2016 if start.is_none() {
2017 start = cases.iter().position(|c| c.test.is_none());
2018 }
2019 if let Some(s) = start {
2020 for c in &cases[s..] {
2021 let c_res = if switch_sc.is_some() {
2022 self.exec_statements_prehoisted(&c.body, run_sc, this)?
2023 } else {
2024 self.exec_statements(&c.body, run_sc, this)?
2025 };
2026 match c_res {
2027 Completion::Break(None) => return Ok(Completion::Normal(Value::Undefined)),
2028 Completion::Normal(_) => {}
2029 other => return Ok(other),
2030 }
2031 }
2032 }
2033 Ok(Completion::Normal(Value::Undefined))
2034 })();
2035 if let Some(sc) = switch_sc {
2036 self.recycle_block_scope(sc);
2037 }
2038 res
2039 }
2040
2041 #[inline(never)]
2042 fn exec_try(
2043 &mut self,
2044 t: &crate::os_lib::ecma::ast::TryStmt,
2045 scope: &Rc<RefCell<Scope>>,
2046 this: &Value,
2047 ) -> Result<Completion, Value> {
2048 let crate::os_lib::ecma::ast::TryStmt {
2049 block,
2050 catch_param,
2051 catch_block,
2052 finally_block,
2053 } = t;
2054 let result = self.exec_statements(block, scope, this);
2055 let after_catch = match result {
2056 Err(thrown) if !self.aborted && !self.is_suspending() && !self.is_gen_returning() => {
2057 if let Some(cb) = catch_block {
2058 let is_simple_catch = matches!(catch_param.as_deref(), Some(Pattern::Identifier(_)));
2059 let catch_sc = Scope::block(scope.clone());
2060 if is_simple_catch {
2061 catch_sc.borrow_mut().is_catch = true;
2062 }
2063 if let Some(p) = catch_param {
2064 self.bind_pattern(p, thrown, &catch_sc, this)?;
2065 }
2066 if is_simple_catch {
2067 let inner = self.alloc_block_scope(catch_sc);
2068 let res = self.exec_statements(cb, &inner, this);
2069 self.recycle_block_scope(inner);
2070 res
2071 } else {
2072 self.exec_statements(cb, &catch_sc, this)
2073 }
2074 } else {
2075 Err(thrown)
2076 }
2077 }
2078 other => other,
2079 };
2080 if self.is_suspending() {
2081 return after_catch;
2082 }
2083 if let Some(fb) = finally_block {
2084 let fin = self.exec_statements(fb, scope, this)?;
2085 if let Completion::Return(_) | Completion::Break(_) | Completion::Continue(_) = fin {
2086 if let Some(r) = &mut self.gen_replay {
2087 r.returning = None;
2088 }
2089 return Ok(fin);
2090 }
2091 }
2092 after_catch
2093 }
2094
2095 #[inline(never)]
2096 fn exec_module_stmt(
2097 &mut self,
2098 stmt: &Statement,
2099 scope: &Rc<RefCell<Scope>>,
2100 this: &Value,
2101 ) -> Result<Completion, Value> {
2102 match stmt {
2103 Statement::Import(decl) => {
2104 let ImportDecl {
2105 source,
2106 default,
2107 namespace,
2108 named,
2109 side_effect_only,
2110 } = &**decl;
2111 let exports = self.load_module(source)?;
2112 if !side_effect_only {
2113 let exp = exports.borrow();
2114 if let Some(local) = default {
2115 let v = exp.get("default").cloned().unwrap_or(Value::Undefined);
2116 scope_declare(scope, local, v);
2117 }
2118 if let Some(ns) = namespace {
2119 let o = Obj::plain();
2120 {
2121 let mut ob = o.borrow_mut();
2122 for (k, v) in exp.iter() {
2123 ob.props.insert(k.clone().into(), v.clone());
2124 }
2125 }
2126 scope_declare(scope, ns, Value::Object(o));
2127 }
2128 for (orig, local) in named {
2129 let v = exp.get(orig).cloned().unwrap_or(Value::Undefined);
2130 scope_declare(scope, local, v);
2131 }
2132 }
2133 Ok(Completion::Normal(Value::Undefined))
2134 }
2135 Statement::ExportDefault(expr) => {
2136 let v = self.eval(expr, scope, this)?;
2137 self.record_export(scope, "default", v);
2138 Ok(Completion::Normal(Value::Undefined))
2139 }
2140 Statement::ExportDecl { declaration, names } => {
2141 let c = self.exec_stmt(declaration, scope, this)?;
2142 for name in names {
2143 let v = scope_get(scope, name).unwrap_or(Value::Undefined);
2144 self.record_export(scope, name, v);
2145 }
2146 Ok(c)
2147 }
2148 Statement::ExportNamed { specifiers, source } => {
2149 match source {
2150 Some(src) => {
2151 let exports = self.load_module(src)?;
2152 for (orig, public) in specifiers {
2153 if orig == "*" {
2154 let ns = self.module_namespace(src)?;
2155 self.record_export(scope, public, ns);
2156 continue;
2157 }
2158 let exp = exports.borrow();
2159 if let Some(v) = exp.get(orig.as_str()).cloned() {
2162 self.record_export(scope, public, v);
2163 }
2164 }
2165 }
2166 None => {
2167 for (local, public) in specifiers {
2168 let v = scope_get(scope, local).unwrap_or(Value::Undefined);
2169 self.record_export(scope, public, v);
2170 }
2171 }
2172 }
2173 Ok(Completion::Normal(Value::Undefined))
2174 }
2175 Statement::ExportAll { source } => {
2176 let exports = self.load_module(source)?;
2177 let exp = exports.borrow();
2178 for (k, v) in exp.iter() {
2179 if k != "default" {
2180 self.record_export(scope, k, v.clone());
2181 }
2182 }
2183 Ok(Completion::Normal(Value::Undefined))
2184 }
2185 _ => Ok(Completion::Normal(Value::Undefined)),
2186 }
2187 }
2188
2189 pub(crate) fn record_export(&mut self, scope: &Rc<RefCell<Scope>>, name: &str, val: Value) {
2192 if let Some(Value::Object(o)) = scope_get(scope, MODULE_EXPORTS_KEY) {
2194 o.borrow_mut().props.insert(String::from(name).into(), val);
2195 }
2196 }
2197
2198 fn module_body(&self, specifier: &str) -> Option<Vec<Statement>> {
2200 let src = self.modules.borrow().get(specifier).map(|r| r.source.clone())?;
2201 Some(Parser::new_lazy(Lexer::new(&src)).parse_program().body)
2202 }
2203
2204 fn resolve_export(
2207 &self,
2208 specifier: &str,
2209 name: &str,
2210 visited: &mut Vec<(String, String)>,
2211 ) -> Result<Option<(String, String)>, ()> {
2212 if visited.iter().any(|(m, n)| m == specifier && n == name) {
2213 return Ok(None);
2214 }
2215 visited.push((String::from(specifier), String::from(name)));
2216 let Some(body) = self.module_body(specifier) else {
2217 return Ok(Some((String::from(specifier), String::from(name))));
2218 };
2219 for st in &body {
2220 match st {
2221 Statement::ExportDecl { names, .. } if names.iter().any(|n| n == name) => {
2222 return Ok(Some((String::from(specifier), String::from(name))));
2223 }
2224 Statement::ExportDefault(_) if name == "default" => {
2225 return Ok(Some((String::from(specifier), String::from(name))));
2226 }
2227 Statement::ExportNamed { specifiers, source } => {
2228 for (orig, exported) in specifiers {
2229 if exported == name {
2230 return match source {
2231 None => Ok(Some((String::from(specifier), String::from(name)))),
2232 Some(src) => {
2233 if orig == "*" {
2234 Ok(Some((src.clone(), String::from("*namespace*"))))
2235 } else {
2236 self.resolve_export(src, orig, visited)
2237 }
2238 }
2239 };
2240 }
2241 }
2242 }
2243 _ => {}
2244 }
2245 }
2246 if name == "default" {
2247 return Ok(None);
2248 }
2249 let mut star: Option<(String, String)> = None;
2250 for st in &body {
2251 if let Statement::ExportAll { source } = st {
2252 if let Some(r) = self.resolve_export(source, name, visited)? {
2253 match &star {
2254 None => star = Some(r),
2255 Some(prev) if *prev == r => {}
2256 Some(_) => return Err(()),
2257 }
2258 }
2259 }
2260 }
2261 Ok(star)
2262 }
2263
2264 fn link_check(&mut self, specifier: &str, seen: &mut Vec<String>) -> Result<(), Value> {
2267 if seen.iter().any(|m| m == specifier) {
2268 return Ok(());
2269 }
2270 seen.push(String::from(specifier));
2271 let Some(body) = self.module_body(specifier) else { return Ok(()) };
2272 for st in &body {
2273 match st {
2274 Statement::ExportNamed { specifiers, source: Some(src) } => {
2275 for (_, exported) in specifiers {
2276 match self.resolve_export(specifier, exported, &mut Vec::new()) {
2277 Ok(Some(_)) => {}
2278 _ => {
2279 return Err(self.syntax_error(alloc::format!(
2280 "The requested module '{}' does not provide an export named '{}'",
2281 src, exported
2282 )))
2283 }
2284 }
2285 }
2286 self.link_check(src, seen)?;
2287 }
2288 Statement::ExportAll { source } => self.link_check(source, seen)?,
2289 Statement::Import(decl) if self.modules.borrow().contains_key(decl.source.as_str()) => {
2290 for (orig, _) in &decl.named {
2291 match self.resolve_export(&decl.source, orig, &mut Vec::new()) {
2292 Ok(Some(_)) => {}
2293 _ => {
2294 return Err(self.syntax_error(alloc::format!(
2295 "The requested module '{}' does not provide an export named '{}'",
2296 decl.source, orig
2297 )))
2298 }
2299 }
2300 }
2301 let src = decl.source.clone();
2302 self.link_check(&src, seen)?;
2303 }
2304 _ => {}
2305 }
2306 }
2307 Ok(())
2308 }
2309
2310 pub(crate) fn module_namespace(&mut self, specifier: &str) -> EvalResult {
2312 if let Some(Some(ns)) = self.modules.borrow().get(specifier).map(|r| r.namespace.clone()) {
2313 return Ok(ns);
2314 }
2315 let exports = self.load_module(specifier)?;
2316 let ns = Obj::plain();
2317 {
2318 let mut nb = ns.borrow_mut();
2319 nb.set_null_proto(true);
2320 for (k, v) in exports.borrow().iter() {
2321 nb.props.insert(k.clone().into(), v.clone());
2322 }
2323 nb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("Module"));
2324 nb.hide_props(&["Symbol(Symbol.toStringTag)"]);
2325 nb.set_non_extensible(true);
2326 nb.set_frozen(true);
2328 }
2329 let nsv = Value::Object(ns);
2330 if let Some(rec) = self.modules.borrow_mut().get_mut(specifier) {
2331 rec.namespace = Some(nsv.clone());
2332 }
2333 Ok(nsv)
2334 }
2335
2336 pub(crate) fn load_module_checked(
2338 &mut self,
2339 specifier: &str,
2340 ) -> Result<Rc<RefCell<BTreeMap<String, Value>>>, Value> {
2341 let pending = match self.modules.borrow().get(specifier) {
2342 Some(rec) if rec.exports.is_none() => Some(rec.source.clone()),
2343 _ => None,
2344 };
2345 let pending_link = pending.is_some();
2346 if let Some(src) = pending {
2347 let (_, errs) = Parser::new_lazy(Lexer::new(&src)).parse_program_reporting();
2348 if let Some(e) = errs.first() {
2349 return Err(self.syntax_error(e.message.clone()));
2350 }
2351 }
2352 if pending_link {
2353 self.link_check(specifier, &mut Vec::new())?;
2354 }
2355 let r = self.load_module(specifier);
2356 if r.is_err() {
2357 if let Some(rec) = self.modules.borrow_mut().get_mut(specifier) {
2359 rec.exports = None;
2360 }
2361 }
2362 r
2363 }
2364
2365 pub(crate) fn load_module(
2368 &mut self,
2369 specifier: &str,
2370 ) -> Result<Rc<RefCell<BTreeMap<String, Value>>>, Value> {
2371 if let Some(rec) = self.modules.borrow().get(specifier) {
2373 if let Some(ex) = &rec.exports {
2374 return Ok(ex.clone());
2375 }
2376 }
2377 let source = match self.modules.borrow().get(specifier) {
2379 Some(rec) => rec.source.clone(),
2380 None => {
2381 let empty = Rc::new(RefCell::new(BTreeMap::new()));
2382 return Ok(empty);
2383 }
2384 };
2385 let exports = Rc::new(RefCell::new(BTreeMap::new()));
2387 if let Some(rec) = self.modules.borrow_mut().get_mut(specifier) {
2388 rec.exports = Some(exports.clone());
2389 }
2390 let module_scope = Scope::child(self.global.clone());
2393 let collector = Obj::plain();
2394 scope_declare(
2395 &module_scope,
2396 MODULE_EXPORTS_KEY,
2397 Value::Object(collector.clone()),
2398 );
2399 let program = Parser::new_lazy(Lexer::new(&source)).parse_program();
2400 let _ = self.exec_statements(&program.body, &module_scope, &Value::Undefined)?;
2401 {
2403 let cb = collector.borrow();
2404 let mut ex = exports.borrow_mut();
2405 for (k, v) in cb.props.iter() {
2406 ex.insert(k.clone().into(), v.clone());
2407 }
2408 }
2409 for st in &program.body {
2411 if let Statement::ExportNamed { specifiers, source: Some(src) } = st {
2412 for (orig, public) in specifiers {
2413 if orig == "*" || exports.borrow().contains_key(public.as_str()) {
2414 continue;
2415 }
2416 let src_ex = self.load_module(src)?;
2417 let v = src_ex.borrow().get(orig.as_str()).cloned().unwrap_or(Value::Undefined);
2418 exports.borrow_mut().insert(public.clone(), v);
2419 }
2420 }
2421 }
2422 Ok(exports)
2423 }
2424
2425}
2426
2427pub(crate) fn var_names_of(stmts: &[Statement]) -> Vec<Rc<str>> {
2435 let mut all: Vec<Rc<str>> = Vec::new();
2436 collect_var_names(stmts, &mut all);
2437 if all.len() <= 8 {
2438 let mut out: Vec<Rc<str>> = Vec::with_capacity(all.len());
2439 for n in all {
2440 if !out.contains(&n) {
2441 out.push(n);
2442 }
2443 }
2444 return out;
2445 }
2446 let mut seen: indexmap::IndexMap<Rc<str>, (), core::hash::BuildHasherDefault<super::super::value::FnvHasher>> =
2447 indexmap::IndexMap::with_capacity_and_hasher(all.len(), Default::default());
2448 for n in all {
2449 seen.insert(n, ());
2450 }
2451 seen.into_keys().collect()
2452}
2453
2454fn collect_var_names(stmts: &[Statement], out: &mut Vec<Rc<str>>) {
2455 for s in stmts {
2456 collect_var_names_stmt(s, out);
2457 }
2458}
2459
2460fn collect_var_names_stmt(s: &Statement, out: &mut Vec<Rc<str>>) {
2461 match s {
2462 Statement::VarDeclaration { kind: VarKind::Var, decls, .. } => {
2463 for (pat, _) in decls {
2464 collect_pattern_names(pat, out);
2465 }
2466 }
2467 Statement::Block(body) => collect_var_names(body, out),
2468 Statement::If { consequent, alternate, .. } => {
2469 collect_var_names_stmt(consequent, out);
2470 if let Some(a) = alternate {
2471 collect_var_names_stmt(a, out);
2472 }
2473 }
2474 Statement::While { body, .. } | Statement::DoWhile { body, .. } => collect_var_names_stmt(body, out),
2475 Statement::For { init, body, .. } => {
2476 if let Some(i) = init {
2477 collect_var_names_stmt(i, out);
2478 }
2479 collect_var_names_stmt(body, out);
2480 }
2481 Statement::ForIn { decl_kind, pattern, body, .. } => {
2482 if matches!(decl_kind, Some(VarKind::Var)) {
2483 collect_pattern_names(pattern, out);
2484 }
2485 collect_var_names_stmt(body, out);
2486 }
2487 Statement::Labeled(_, body) | Statement::With { body, .. } => collect_var_names_stmt(body, out),
2488 Statement::Switch { cases, .. } => {
2489 for c in cases {
2490 collect_var_names(&c.body, out);
2491 }
2492 }
2493 Statement::Try(t) => {
2494 let (block, catch_block, finally_block) = (&t.block, &t.catch_block, &t.finally_block);
2495 collect_var_names(block, out);
2496 if let Some(b) = catch_block {
2497 collect_var_names(b, out);
2498 }
2499 if let Some(b) = finally_block {
2500 collect_var_names(b, out);
2501 }
2502 }
2503 Statement::ExportDecl { declaration, .. } => collect_var_names_stmt(declaration, out),
2504 _ => {}
2505 }
2506}
2507
2508pub(crate) fn collect_pattern_names(p: &Pattern, out: &mut Vec<Rc<str>>) {
2509 match p {
2510 Pattern::Identifier(n) => {
2511 out.push(n.clone());
2512 }
2513 Pattern::Object(props) => {
2514 for pr in props {
2515 collect_pattern_names(&pr.value, out);
2516 }
2517 }
2518 Pattern::Array(elems) => {
2519 for e in elems {
2520 if let Some(pat) = &e.pattern {
2521 collect_pattern_names(pat, out);
2522 }
2523 }
2524 }
2525 Pattern::Expr(_) => {}
2526 }
2527}
2528
2529impl Interp {
2530 fn sync_global_pattern(&self, pat: &Pattern) {
2531 if let Pattern::Identifier(name) = pat {
2532 self.sync_global_var_binding(name);
2533 return;
2534 }
2535 let mut names = Vec::new();
2536 collect_pattern_names(pat, &mut names);
2537 for n in &names {
2538 self.sync_global_var_binding(n);
2539 }
2540 }
2541}
2542
2543fn body_has_use_strict(stmts: &[Statement]) -> bool {
2545 for s in stmts {
2546 match s {
2547 Statement::Expression(Expression::Str(lit)) => {
2548 if lit == "use strict" {
2549 return true;
2550 }
2551 }
2552 _ => break,
2553 }
2554 }
2555 false
2556}
2557
2558fn can_declare_global_function(g_obj: &ObjRef, name: &str) -> bool {
2560 let b = g_obj.borrow();
2561 let has_prop = b.props.contains_key(name);
2562 let has_acc = b.has_accessor(name);
2563 if !has_prop && !has_acc {
2564 return !b.is_frozen() && !b.is_sealed() && !b.is_non_extensible();
2565 }
2566 let attr = b.get_attr_or_default(name);
2567 if attr.configurable {
2568 return true;
2569 }
2570 !has_acc && has_prop && attr.writable && b.is_enumerable(name)
2571}
2572
2573fn can_declare_global_var(g_obj: &ObjRef, name: &str) -> bool {
2575 let b = g_obj.borrow();
2576 if b.props.contains_key(name) || b.has_accessor(name) {
2577 return true;
2578 }
2579 !b.is_frozen() && !b.is_sealed() && !b.is_non_extensible()
2580}
2581
2582fn sync_global_function_binding(g_obj: &ObjRef, name: &Rc<str>, func: Value, is_eval: bool) {
2585 let mut gb = g_obj.borrow_mut();
2586 let exists = gb.props.contains_key(name.as_ref()) || gb.has_accessor(name.as_ref());
2587 let configurable = !exists || gb.get_attr_or_default(name).configurable;
2588 if configurable {
2589 gb.remove_accessor(name);
2590 gb.props.insert(name.into(), func);
2591 gb.insert_attr(
2592 name.as_ref(),
2593 PropertyAttributes {
2594 writable: true,
2595 enumerable: true,
2596 configurable: is_eval,
2597 },
2598 );
2599 } else {
2600 gb.props.insert(name.into(), func);
2602 }
2603}
2604
2605fn sync_annex_b_global_function(g_obj: &ObjRef, name: &Rc<str>, func: Value) {
2608 let mut gb = g_obj.borrow_mut();
2609 let exists = gb.props.contains_key(name.as_ref()) || gb.has_accessor(name.as_ref());
2610 if exists {
2611 if !gb.has_accessor(name.as_ref()) && gb.get_attr(name).is_none_or(|a| a.writable) {
2612 gb.props.insert(name.into(), func);
2613 }
2614 } else if !gb.is_frozen() && !gb.is_sealed() && !gb.is_non_extensible() {
2615 gb.props.insert(name.into(), func);
2616 gb.insert_attr(
2617 name.as_ref(),
2618 PropertyAttributes {
2619 writable: true,
2620 enumerable: true,
2621 configurable: false,
2622 },
2623 );
2624 }
2625}
2626
2627fn top_function_names(stmts: &[Statement]) -> Vec<Rc<str>> {
2628 let mut out = Vec::new();
2629 for s in stmts {
2630 let fdecl = match s {
2631 Statement::FunctionDeclaration { .. } => Some(s),
2632 Statement::ExportDecl { declaration, .. }
2633 if matches!(**declaration, Statement::FunctionDeclaration { .. }) =>
2634 {
2635 Some(&**declaration)
2636 }
2637 _ => None,
2638 };
2639 if let Some(Statement::FunctionDeclaration { name, .. }) = fdecl {
2640 if !out.iter().any(|n| n == name) {
2641 out.push(name.clone());
2642 }
2643 }
2644 }
2645 out
2646}
2647
2648pub(crate) fn collect_top_lexical_names(stmts: &[Statement]) -> Vec<Rc<str>> {
2649 let mut out = Vec::new();
2650 for s in stmts {
2651 match s {
2652 Statement::VarDeclaration { kind, decls } if !matches!(kind, VarKind::Var) => {
2653 for (pat, _) in decls {
2654 collect_pattern_names(pat, &mut out);
2655 }
2656 }
2657 _ => {}
2658 }
2659 }
2660 out
2661}
2662
2663fn has_intervening_lex_binding(
2664 eval_scope: &Rc<RefCell<Scope>>,
2665 var_sc: &Rc<RefCell<Scope>>,
2666 name: &str,
2667) -> bool {
2668 let mut cur = eval_scope.borrow().parent.clone();
2669 while let Some(sc) = cur {
2670 if Rc::ptr_eq(&sc, var_sc) {
2671 break;
2672 }
2673 let b = sc.borrow();
2674 if b.is_eval {
2675 if b.annex_b_skips(name)
2676 || b.tdz.as_ref().is_some_and(|t| t.iter().any(|n| &**n == name))
2677 {
2678 return true;
2679 }
2680 } else if b.is_block
2681 && !b.is_catch
2682 && (b.vars.contains_key(name)
2683 || b.tdz.as_ref().is_some_and(|t| t.iter().any(|n| &**n == name)))
2684 {
2685 return true;
2686 }
2687 cur = b.parent.clone();
2688 }
2689 false
2690}
2691
2692fn annex_b_eval_func_names(stmts: &[Statement], top_lex: &[Rc<str>]) -> Vec<Rc<str>> {
2693 let mut out = Vec::new();
2694 let mut shadowed = top_lex.to_vec();
2695 for s in stmts {
2696 match s {
2697 Statement::FunctionDeclaration { .. } | Statement::VarDeclaration { .. } => {}
2698 _ => collect_annex_b_stmt(s, &mut shadowed, &mut out),
2699 }
2700 }
2701 out
2702}
2703
2704fn collect_annex_b_stmt(s: &Statement, shadowed: &mut Vec<Rc<str>>, out: &mut Vec<Rc<str>>) {
2705 match s {
2706 Statement::FunctionDeclaration { name, .. }
2707 if !shadowed.iter().any(|x| x == name) && !out.iter().any(|x| x == name) =>
2708 {
2709 out.push(name.clone());
2710 }
2711 Statement::Block(body) => collect_annex_b_block(body, shadowed, out),
2712 Statement::If { consequent, alternate, .. } => {
2713 collect_annex_b_stmt(consequent, shadowed, out);
2714 if let Some(a) = alternate {
2715 collect_annex_b_stmt(a, shadowed, out);
2716 }
2717 }
2718 Statement::While { body, .. } | Statement::DoWhile { body, .. } => {
2719 let base = shadowed.len();
2720 if let Statement::Block(b) = &**body {
2721 collect_annex_b_block(b, shadowed, out);
2722 } else {
2723 collect_annex_b_stmt(body, shadowed, out);
2724 }
2725 shadowed.truncate(base);
2726 }
2727 Statement::For { init, body, .. } => {
2728 let base = shadowed.len();
2729 if let Some(init_s) = init {
2730 if let Statement::VarDeclaration { kind, decls } = &**init_s {
2731 if !matches!(kind, VarKind::Var) {
2732 for (pat, _) in decls {
2733 collect_pattern_names(pat, shadowed);
2734 }
2735 }
2736 }
2737 }
2738 collect_annex_b_stmt(body, shadowed, out);
2739 shadowed.truncate(base);
2740 }
2741 Statement::ForIn { decl_kind, pattern, body, .. } => {
2742 let base = shadowed.len();
2743 if matches!(decl_kind, Some(VarKind::Let | VarKind::Const | VarKind::Using | VarKind::AwaitUsing)) {
2744 collect_pattern_names(pattern, shadowed);
2745 }
2746 collect_annex_b_stmt(body, shadowed, out);
2747 shadowed.truncate(base);
2748 }
2749 Statement::Labeled(_, inner) | Statement::With { body: inner, .. } => collect_annex_b_stmt(inner, shadowed, out),
2750 Statement::Switch { cases, .. } => {
2751 let base = shadowed.len();
2752 for c in cases {
2753 for st in &c.body {
2754 if let Statement::VarDeclaration { kind, decls } = st {
2755 if !matches!(kind, VarKind::Var) {
2756 for (pat, _) in decls {
2757 collect_pattern_names(pat, shadowed);
2758 }
2759 }
2760 }
2761 }
2762 }
2763 for c in cases {
2764 for st in &c.body {
2765 collect_annex_b_stmt(st, shadowed, out);
2766 }
2767 }
2768 shadowed.truncate(base);
2769 }
2770 Statement::Try(t) => {
2771 collect_annex_b_block(&t.block, shadowed, out);
2772 if let Some(cb) = &t.catch_block {
2773 let base = shadowed.len();
2774 if let Some(cp) = &t.catch_param {
2775 if !matches!(&**cp, Pattern::Identifier(_)) {
2777 collect_pattern_names(cp, shadowed);
2778 }
2779 }
2780 collect_annex_b_block(cb, shadowed, out);
2781 shadowed.truncate(base);
2782 }
2783 if let Some(fb) = &t.finally_block {
2784 collect_annex_b_block(fb, shadowed, out);
2785 }
2786 }
2787 _ => {}
2788 }
2789}
2790
2791fn collect_annex_b_block(stmts: &[Statement], shadowed: &mut Vec<Rc<str>>, out: &mut Vec<Rc<str>>) {
2792 let base = shadowed.len();
2793 for st in stmts {
2794 if let Statement::VarDeclaration { kind, decls } = st {
2795 if !matches!(kind, VarKind::Var) {
2796 for (pat, _) in decls {
2797 collect_pattern_names(pat, shadowed);
2798 }
2799 }
2800 }
2801 }
2802 for st in stmts {
2803 collect_annex_b_stmt(st, shadowed, out);
2804 }
2805 shadowed.truncate(base);
2806}
2807
2808fn stmt_has_nested_fn_decl(s: &Statement) -> bool {
2809 match s {
2810 Statement::FunctionDeclaration { .. } => true,
2811 Statement::Block(b) => b.iter().any(stmt_has_nested_fn_decl),
2812 Statement::If { consequent, alternate, .. } => {
2813 stmt_has_nested_fn_decl(consequent)
2814 || alternate.as_ref().is_some_and(|a| stmt_has_nested_fn_decl(a))
2815 }
2816 Statement::While { body, .. } | Statement::DoWhile { body, .. } | Statement::Labeled(_, body) | Statement::With { body, .. } => {
2817 stmt_has_nested_fn_decl(body)
2818 }
2819 Statement::For { body, .. } | Statement::ForIn { body, .. } => stmt_has_nested_fn_decl(body),
2820 Statement::Switch { cases, .. } => cases.iter().any(|c| c.body.iter().any(stmt_has_nested_fn_decl)),
2821 Statement::Try(t) => {
2822 t.block.iter().any(stmt_has_nested_fn_decl)
2823 || t.catch_block.as_ref().is_some_and(|b| b.iter().any(stmt_has_nested_fn_decl))
2824 || t.finally_block.as_ref().is_some_and(|b| b.iter().any(stmt_has_nested_fn_decl))
2825 }
2826 _ => false,
2827 }
2828}
2829
2830pub(crate) fn maybe_record_annex_b_skip(
2831 stmts: &[Statement],
2832 params: &[crate::os_lib::ecma::ast::Param],
2833 scope: &Rc<RefCell<Scope>>,
2834) {
2835 let has_nested = stmts.iter().any(|s| {
2836 !matches!(s, Statement::FunctionDeclaration { .. }) && stmt_has_nested_fn_decl(s)
2837 });
2838 if !has_nested {
2839 return;
2840 }
2841 let mut skip = collect_top_lexical_names(stmts);
2842 for p in params {
2843 collect_pattern_names(&p.pattern, &mut skip);
2844 }
2845 if !skip.is_empty() {
2846 scope.borrow_mut().annex_b_skip = Some(skip.into_boxed_slice());
2847 }
2848}