1use alloc::boxed::Box;
11use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
12use alloc::format;
13use alloc::rc::Rc;
14use alloc::string::String;
15use alloc::string::ToString;
16use alloc::vec::Vec;
17use core::cell::RefCell;
18
19use super::ast::*;
20use super::lexer::Lexer;
21use super::parser::Parser;
22use super::value::*;
23
24const DEFAULT_MAX_STEPS: u64 = 100_000_000;
27const PUMP_MICROTASK_STEPS: u64 = 3_000_000;
29const DEFAULT_MAX_DEPTH: u32 = 2000;
30pub(crate) const JS_STACK_BUDGET: usize = 640 * 1024;
32pub(crate) const JS_STACK_MARGIN: usize = 128 * 1024;
34
35pub(crate) fn js_stack_window() -> (usize, usize) {
37 let sp = current_sp();
38 match crate::os_lib::platform::stack_bounds() {
39 Some((lo, hi)) => (lo + JS_STACK_MARGIN, hi),
40 None => (sp.saturating_sub(JS_STACK_BUDGET), sp + 64 * 1024),
41 }
42}
43
44#[inline(always)]
46pub(crate) fn current_sp() -> usize {
47 let sp: usize;
48 unsafe { core::arch::asm!("mov {}, sp", out(reg) sp, options(nomem, nostack, preserves_flags)) };
50 sp
51}
52
53const MODULE_EXPORTS_KEY: &str = "\u{0}module.exports";
56
57pub struct ModuleRecord {
61 pub source: String,
62 pub exports: Option<Rc<RefCell<BTreeMap<String, Value>>>>,
63 pub namespace: Option<Value>,
65}
66
67pub type ModuleRegistry = Rc<RefCell<BTreeMap<String, ModuleRecord>>>;
69
70pub struct Scope {
72 pub vars: super::value::VarMap<Value>,
75 pub parent: Option<Rc<RefCell<Scope>>>,
76 pub is_block: bool,
79 pub is_param: bool,
81 pub is_catch: bool,
83 pub(crate) annex_b_skip: Option<alloc::boxed::Box<[Rc<str>]>>,
85 pub(crate) tdz: Option<alloc::boxed::Box<[Rc<str>]>>,
87 pub(crate) this_barrier: bool,
89 pub(crate) derived_this: Option<Rc<RefCell<Option<Value>>>>,
91 pub(crate) with_obj: Option<super::value::ObjRef>,
93 pub(crate) has_with: bool,
95 pub(crate) is_eval: bool,
97 pub gc_slot: u32,
99}
100
101impl Drop for Scope {
102 fn drop(&mut self) {
103 super::cycle_gc::untrack_scope(self.gc_slot);
104 }
105}
106
107impl Scope {
108 #[inline]
109 pub(crate) fn annex_b_skips(&self, name: &str) -> bool {
110 self.annex_b_skip
111 .as_ref()
112 .is_some_and(|list| list.iter().any(|n| &**n == name))
113 }
114
115 pub fn new_root() -> Rc<RefCell<Scope>> {
116 super::cycle_gc::track_scope(Rc::new(RefCell::new(Scope {
117 vars: super::value::VarMap::default(),
118 parent: None,
119 is_block: false,
120 is_param: false,
121 is_catch: false,
122 annex_b_skip: None,
123 tdz: None,
124 this_barrier: false,
125 derived_this: None,
126 with_obj: None,
127 has_with: false,
128 is_eval: false,
129 gc_slot: super::cycle_gc::NO_SLOT,
130 })))
131 }
132 pub fn child(parent: Rc<RefCell<Scope>>) -> Rc<RefCell<Scope>> {
133 let has_with = parent.borrow().has_with;
134 super::cycle_gc::track_scope(Rc::new(RefCell::new(Scope {
135 vars: super::value::VarMap::default(),
136 parent: Some(parent),
137 is_block: false,
138 is_param: false,
139 is_catch: false,
140 annex_b_skip: None,
141 tdz: None,
142 this_barrier: false,
143 derived_this: None,
144 with_obj: None,
145 has_with,
146 is_eval: false,
147 gc_slot: super::cycle_gc::NO_SLOT,
148 })))
149 }
150 pub fn child_with_capacity(parent: Rc<RefCell<Scope>>, n: usize) -> Rc<RefCell<Scope>> {
154 let has_with = parent.borrow().has_with;
155 super::cycle_gc::track_scope(Rc::new(RefCell::new(Scope {
156 vars: super::value::VarMap::with_capacity(n),
157 parent: Some(parent),
158 is_block: false,
159 is_param: false,
160 is_catch: false,
161 annex_b_skip: None,
162 tdz: None,
163 this_barrier: false,
164 derived_this: None,
165 with_obj: None,
166 has_with,
167 is_eval: false,
168 gc_slot: super::cycle_gc::NO_SLOT,
169 })))
170 }
171 pub fn block(parent: Rc<RefCell<Scope>>) -> Rc<RefCell<Scope>> {
173 let has_with = parent.borrow().has_with;
174 super::cycle_gc::track_scope(Rc::new(RefCell::new(Scope {
175 vars: super::value::VarMap::default(),
176 parent: Some(parent),
177 is_block: true,
178 is_param: false,
179 is_catch: false,
180 annex_b_skip: None,
181 tdz: None,
182 this_barrier: false,
183 derived_this: None,
184 with_obj: None,
185 has_with,
186 is_eval: false,
187 gc_slot: super::cycle_gc::NO_SLOT,
188 })))
189 }
190 pub fn new_with(parent: Rc<RefCell<Scope>>, obj: super::value::ObjRef) -> Rc<RefCell<Scope>> {
192 super::cycle_gc::track_scope(Rc::new(RefCell::new(Scope {
193 vars: super::value::VarMap::default(),
194 parent: Some(parent),
195 is_block: false,
196 is_param: false,
197 is_catch: false,
198 annex_b_skip: None,
199 tdz: None,
200 this_barrier: false,
201 derived_this: None,
202 with_obj: Some(obj),
203 has_with: true,
204 is_eval: false,
205 gc_slot: super::cycle_gc::NO_SLOT,
206 })))
207 }
208}
209
210pub(crate) fn var_scope(scope: &Rc<RefCell<Scope>>) -> Rc<RefCell<Scope>> {
212 let mut cur = scope.clone();
213 loop {
214 let next = {
215 let b = cur.borrow();
216 if !b.is_block && b.with_obj.is_none() {
217 None
218 } else {
219 b.parent.clone()
220 }
221 };
222 match next {
223 Some(p) => cur = p,
224 None => return cur,
225 }
226 }
227}
228
229pub(crate) fn block_has_lexical(stmts: &[Statement]) -> bool {
231 stmts.iter().any(|s| {
232 matches!(
233 s,
234 Statement::FunctionDeclaration { .. }
235 | Statement::VarDeclaration {
236 kind: VarKind::Let | VarKind::Const | VarKind::Using | VarKind::AwaitUsing,
237 ..
238 }
239 )
240 })
241}
242
243pub(crate) fn scope_get(scope: &Rc<RefCell<Scope>>, name: &str) -> Option<Value> {
244 let mut cur = scope.clone();
245 loop {
246 let b = cur.borrow();
247 if let Some(v) = b.vars.get(name) {
248 return Some(v.clone());
249 }
250 let next = b.parent.clone();
251 drop(b);
252 match next {
253 Some(p) => cur = p,
254 None => return None,
255 }
256 }
257}
258
259pub(crate) fn scope_get_tdz(scope: &Rc<RefCell<Scope>>, name: &str) -> Result<Option<Value>, ()> {
260 let mut cur = scope.clone();
261 loop {
262 let b = cur.borrow();
263 if let Some(v) = b.vars.get(name) {
264 return Ok(Some(v.clone()));
265 }
266 if b.tdz.as_ref().is_some_and(|t| t.iter().any(|n| &**n == name)) {
267 return Err(());
268 }
269 let next = b.parent.clone();
270 drop(b);
271 match next {
272 Some(p) => cur = p,
273 None => return Ok(None),
274 }
275 }
276}
277
278pub(crate) fn scope_derived_this(scope: &Rc<RefCell<Scope>>) -> Option<Rc<RefCell<Option<Value>>>> {
279 let mut cur = scope.clone();
280 loop {
281 let b = cur.borrow();
282 if let Some(dt) = &b.derived_this {
283 return Some(dt.clone());
284 }
285 if b.this_barrier {
286 return None;
287 }
288 let next = b.parent.clone();
289 drop(b);
290 match next {
291 Some(p) => cur = p,
292 None => return None,
293 }
294 }
295}
296
297#[inline]
299fn scope_global_object(scope: &Scope) -> Option<ObjRef> {
300 match scope.vars.get("globalThis") {
301 Some(Value::Object(o)) => Some(o.clone()),
302 _ => None,
303 }
304}
305
306fn scope_assign(scope: &Rc<RefCell<Scope>>, name: &str, val: Value) -> bool {
308 let mut cur = scope.clone();
309 loop {
310 let sync_global = {
311 let mut b = cur.borrow_mut();
314 if b.parent.is_some() {
315 if let Some(slot) = b.vars.get_mut(name) {
316 *slot = val;
317 return true;
318 }
319 None
320 } else if !b.vars.contains_key(name) {
321 None
322 } else if let Some(w) = scope_global_object(&b) {
323 if w.borrow().get_attr(name).is_some_and(|a| !a.writable) {
324 return true;
325 }
326 if let Some(slot) = b.vars.get_mut(name) {
327 *slot = val.clone();
328 }
329 Some(w)
330 } else {
331 if let Some(slot) = b.vars.get_mut(name) {
332 *slot = val;
333 }
334 return true;
335 }
336 };
337 if let Some(w) = sync_global {
338 let mut wb = w.borrow_mut();
339 if let Some(pslot) = wb.props.get_mut(name) {
342 *pslot = val;
343 }
344 return true;
345 }
346 let next = cur.borrow().parent.clone();
347 match next {
348 Some(p) => cur = p,
349 None => return false,
350 }
351 }
352}
353
354fn scope_declare(scope: &Rc<RefCell<Scope>>, name: &str, val: Value) {
355 let sync_global = {
356 let mut b = scope.borrow_mut();
357 if b.parent.is_none() {
358 if let Some(w) = scope_global_object(&b) {
359 let can_write = {
360 let wb = w.borrow();
361 if wb.props.contains_key(name) {
362 wb.get_attr(name).is_none_or(|a| a.writable)
363 } else if wb.has_accessor(name) {
364 false
365 } else {
366 !wb.is_frozen() && !wb.is_sealed() && !wb.is_non_extensible()
367 }
368 };
369 if !can_write {
370 return;
371 }
372 b.vars.insert(name.into(), val.clone());
373 Some((w, val))
374 } else {
375 b.vars.insert(name.into(), val);
376 None
377 }
378 } else {
379 b.vars.insert(name.into(), val);
380 return;
381 }
382 };
383 if let Some((w, v)) = sync_global {
384 let mut wb = w.borrow_mut();
385 if let Some(pslot) = wb.props.get_mut(name) {
386 *pslot = v;
387 } else {
388 wb.props.insert(name.into(), v);
389 }
390 }
391}
392
393pub(crate) fn infer_function_name(v: &Value, name: &str) {
398 if let Value::Object(o) = v {
399 if let ObjKind::Function(fd) = &mut o.borrow_mut().kind {
400 if fd.name().is_empty() {
401 if name.starts_with("Symbol(") {
402 fd.set_name(&fn_name_from_key(name));
403 } else {
404 fd.set_name(name);
405 }
406 }
407 }
408 }
409}
410
411pub(crate) fn fn_name_from_key(key: &str) -> alloc::string::String {
414 if let Some(inner) = key.strip_prefix("Symbol(").and_then(|r| r.strip_suffix(')')).filter(|i| !i.is_empty()) {
415 if inner.strip_prefix('@').is_some_and(|d| d.bytes().all(|b| b.is_ascii_digit())) {
416 return alloc::string::String::new();
417 }
418 let desc = match inner.rsplit_once(",@") {
419 Some((d, id)) if !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()) => d,
420 _ => inner,
421 };
422 return alloc::format!("[{}]", desc);
423 }
424 alloc::string::String::from(key)
425}
426
427pub(crate) fn name_default_value(v: &Value, def: &Expression, target: &crate::os_lib::ecma::ast::Pattern) {
430 let anon = matches!(def, Expression::Function { name: None, .. } | Expression::Class { name: None, .. });
431 if anon {
432 if let crate::os_lib::ecma::ast::Pattern::Identifier(n) = target {
433 infer_function_name(v, n);
434 }
435 }
436}
437
438#[derive(Clone)]
444pub struct TimerTask {
445 pub cb: Value,
446 pub args: Vec<Value>,
447 pub id: u64,
448 pub due_ms: u64,
449 pub period_ms: Option<u64>,
450}
451
452pub(crate) enum Completion {
454 Normal(Value),
455 Return(Value),
456 Break(Option<Rc<str>>),
457 Continue(Option<Rc<str>>),
458}
459
460struct GenReplay {
465 sent: Vec<super::value::GenCompletion>,
467 counter: usize,
469 target: usize,
471 suspending: bool,
473 yielded: Value,
475 returning: Option<Value>,
477 gen_depth: u32,
479 stmt_cursor: usize,
481 done_stmts: Vec<Option<super::value::DoneStmtEntry>>,
483 scope_cursor: usize,
485 saved_scopes: Vec<Rc<RefCell<Scope>>>,
487 gen_ctx: Option<super::value::ObjRef>,
489}
490
491pub(crate) type WeakMapIndex =
492 Rc<RefCell<BTreeMap<usize, (alloc::rc::Weak<RefCell<Obj>>, BTreeMap<usize, usize>)>>>;
493
494pub struct JsRuntime {
496 pub max_steps: u64,
498 pub global: Rc<RefCell<Scope>>,
499 pub out: String,
501 pub microtasks: Rc<RefCell<VecDeque<Job>>>,
503 pub macrotasks: Rc<RefCell<VecDeque<TimerTask>>>,
505 pub clock_skew: Rc<core::cell::Cell<u64>>,
507 pub base_url: String,
509 pub modules: ModuleRegistry,
511 pub builtin_fn_cache: Rc<RefCell<BTreeMap<usize, Value>>>,
513 pub units_cache: Rc<RefCell<super::builtins::UnitsCache>>,
515 pub(crate) wm_index: WeakMapIndex,
517 pub(crate) global_lexicals: Rc<RefCell<BTreeSet<Rc<str>>>>,
520 pub last_syntax_errors: Vec<super::parser::ParseError>,
527 pub last_thrown: Option<Value>,
530 pub runtime_id: u64,
533 pub(crate) host: &'static super::host::HostHooks,
535 pub(crate) host_state: Rc<dyn core::any::Any>,
537 pub(crate) private_brand_seq: Rc<core::cell::Cell<u64>>,
539}
540
541static NEXT_RUNTIME_ID: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(1);
543
544impl JsRuntime {
545 pub fn new_ecma() -> Self {
547 Self::new_with_host(
548 &super::host::NULL_HOST_HOOKS,
549 Rc::new(()),
550 |_| {},
551 )
552 }
553
554 pub fn new_with_host(
556 host: &'static super::host::HostHooks,
557 host_state: Rc<dyn core::any::Any>,
558 install_extra: fn(&Rc<RefCell<Scope>>),
559 ) -> Self {
560 let global = Scope::new_root();
561 super::builtins::install(&global);
562 install_extra(&global);
563 let mut rt = JsRuntime {
564 max_steps: DEFAULT_MAX_STEPS,
565 global,
566 out: String::new(),
567 microtasks: Rc::new(RefCell::new(VecDeque::new())),
568 macrotasks: Rc::new(RefCell::new(VecDeque::new())),
569 clock_skew: Rc::new(core::cell::Cell::new(0)),
570 base_url: String::new(),
571 modules: Rc::new(RefCell::new(BTreeMap::new())),
572 builtin_fn_cache: Rc::new(RefCell::new(BTreeMap::new())),
573 units_cache: Rc::new(RefCell::new(super::builtins::UnitsCache::default())),
574 wm_index: Rc::new(RefCell::new(BTreeMap::new())),
575 global_lexicals: Rc::new(RefCell::new(BTreeSet::new())),
576 last_syntax_errors: Vec::new(),
577 last_thrown: None,
578 runtime_id: NEXT_RUNTIME_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed),
579 host,
580 host_state,
581 private_brand_seq: Rc::new(core::cell::Cell::new(1)),
582 };
583 super::builtins::populate_builtin_protos(&rt.global);
584 rt.seed_builtin_fn_cache();
585 super::builtins::mark_builtin_props(&rt.global);
586 if let Some(Value::Object(g_obj)) = rt.global.borrow().vars.get("globalThis").cloned() {
588 let fixed = PropertyAttributes {
589 writable: false,
590 enumerable: false,
591 configurable: false,
592 };
593 let builtin_attr = PropertyAttributes {
594 writable: true,
595 enumerable: false,
596 configurable: true,
597 };
598 let globals: Vec<(String, Value)> = rt
599 .global
600 .borrow()
601 .vars
602 .iter()
603 .filter(|(k, _)| !k.starts_with('%') && !k.starts_with('\0'))
604 .map(|(k, v)| (k.to_string(), v.clone()))
605 .collect();
606 let mut gb = g_obj.borrow_mut();
607 for (k, v) in globals {
608 if !gb.props.contains_key(k.as_str()) {
609 let attr = if matches!(k.as_str(), "NaN" | "Infinity" | "undefined") {
610 fixed
611 } else {
612 builtin_attr
613 };
614 gb.props.insert(k.clone().into(), v);
615 gb.insert_attr(k, attr);
616 }
617 }
618 }
619 (rt.host.init_runtime)(&mut rt);
620 rt
621 }
622
623 fn seed_builtin_fn_cache(&mut self) {
628 let mut cache = self.builtin_fn_cache.borrow_mut();
629 for ctor in ["Array", "String", "Object", "Function", "Number", "Boolean", "BigInt", "Promise", "Date", "Map", "Set"] {
630 let Some(proto) = super::builtins::global_proto_obj(&self.global, ctor) else { continue };
631 let b = proto.borrow();
632 for (_, v) in b.props.iter() {
633 if let Value::Object(f) = v {
634 if let ObjKind::Native { func, .. } = &f.borrow().kind {
635 cache.entry(*func as usize).or_insert_with(|| v.clone());
636 }
637 }
638 }
639 }
640 }
641
642 pub(crate) fn new_interp(&self) -> Interp {
643 let base_url = (self.host.current_base_url)(&self.global)
646 .filter(|s| !s.is_empty())
647 .unwrap_or_else(|| self.base_url.clone());
648 let host_state = (self.host.new_interp_state)(self.host_state.as_ref());
649 Interp {
650 steps: 0,
651 max_steps: self.max_steps,
652 task_start: 0,
653 task_depth: 0,
654 microtask_step_cap: PUMP_MICROTASK_STEPS.min(self.max_steps / 10),
655 vm_stack: Vec::new(),
656 window_pos: 0,
657 strict: false,
658 host: self.host,
659 host_state,
660 implicit_globals: Vec::new(),
661 arg_pool: Vec::new(),
662 scope_pool: Vec::new(),
663 depth: 0,
664 max_depth: DEFAULT_MAX_DEPTH,
665 stack_limit: js_stack_window(),
666 aborted: false,
667 out: String::new(),
668 microtasks: self.microtasks.clone(),
669 gen_replay: None,
670 macrotasks: self.macrotasks.clone(),
671 clock_skew: self.clock_skew.clone(),
672 base_url,
673 global: self.global.clone(),
674 modules: self.modules.clone(),
675 builtin_fn_cache: self.builtin_fn_cache.clone(),
676 runtime_id: self.runtime_id,
677 units_cache: self.units_cache.clone(),
678 wm_index: self.wm_index.clone(),
679 global_lexicals: self.global_lexicals.clone(),
680 pending_label: None,
681 pending_new_target: None,
682 forof_preset: None,
683 join_stack: Vec::new(),
684 new_target_stack: Vec::new(),
685 derived_this_stack: Vec::new(),
686 call_names: Vec::new(),
687 active_param_names: Vec::new(),
688 eval_ctx_stack: Vec::new(),
689 private_brand_seq: self.private_brand_seq.clone(),
690 }
691 }
692
693 pub fn define_module(&mut self, specifier: &str, source: &str) {
696 self.modules.borrow_mut().insert(
697 String::from(specifier),
698 ModuleRecord {
699 source: String::from(source),
700 exports: None,
701 namespace: None,
702 },
703 );
704 }
705
706 pub fn eval_module(&mut self, specifier: &str, source: &str) -> Result<Value, String> {
709 self.define_module(specifier, source);
710 let mut interp = self.new_interp();
711 let res = match interp.load_module(specifier) {
712 Ok(_) => Ok(Value::Undefined),
713 Err(e) => Err(e.to_js_string()),
714 };
715 interp.run_event_loop();
716 self.out.push_str(&interp.out);
717 res
718 }
719
720 pub fn pump_timers(&mut self, budget_ms: u64) -> bool {
723 let interp = self.new_interp();
724 let async_io = (self.host.has_ready_async_io)(self.host_state.as_ref());
729 if !async_io && !interp.has_due_timer() && self.microtasks.borrow().is_empty() {
730 return false;
731 }
732 let mut interp = interp;
733 interp.microtask_step_cap = PUMP_MICROTASK_STEPS.min(self.max_steps / 10);
735 interp.run_event_loop_for(budget_ms);
736 if (self.host.pump_async_io)(&mut interp) {
738 interp.run_microtasks();
739 }
740 (self.host.after_pump)(&mut interp);
741 self.out.push_str(&interp.out);
742 true
743 }
744
745 pub fn has_due_timers(&self) -> bool {
747 if (self.host.has_ready_async_io)(self.host_state.as_ref()) {
748 return true;
749 }
750 if self.microtasks.try_borrow().is_ok_and(|q| !q.is_empty()) {
751 return true;
752 }
753 let now = crate::os_lib::platform::now_ms().wrapping_add(self.clock_skew.get());
754 self.macrotasks.try_borrow().is_ok_and(|q| q.iter().any(|t| t.due_ms <= now))
755 }
756
757 pub fn fast_forward_timers(&mut self, max_ms: u64) {
759 let mut interp = self.new_interp();
760 let start = interp.timer_now();
761 loop {
762 interp.run_microtasks();
763 if interp.aborted {
764 break;
765 }
766 let next = interp.macrotasks.borrow().iter().map(|t| t.due_ms).min();
767 let Some(due) = next else { break };
768 if due.saturating_sub(start) > max_ms {
769 break;
770 }
771 interp.run_timer(true);
772 }
773 self.out.push_str(&interp.out);
774 }
775
776 pub fn eval(&mut self, source: &str) -> Result<Value, String> {
782 let is_large = source.len() >= 65_536;
783 #[cfg(target_os = "none")]
786 let heap_before = if is_large { crate::os_lib::platform::heap_stats().0 } else { 0 };
787 #[cfg(target_os = "none")]
788 let t_parse0 = crate::os_lib::platform::now_ms();
789 let parser = Parser::new_lazy(Lexer::new(source));
790 #[cfg(target_os = "none")]
793 let parser = crate::os_lib::platform::kill_owned(parser);
794 let mut parser = parser;
795 let program = parser.parse_program();
796 #[cfg(target_os = "none")]
797 let program = crate::os_lib::platform::kill_owned(program);
798 #[cfg(target_os = "none")]
799 let t_parse = crate::os_lib::platform::now_ms().saturating_sub(t_parse0);
800 #[cfg(target_os = "none")]
801 if is_large {
802 let (u, t) = crate::os_lib::platform::heap_stats();
803 crate::warn!(
804 "[JS][MEM] 大きなスクリプト len={} 解析前={}MB 解析後={}MB / {}MB 解析={}ms",
805 source.len(),
806 heap_before >> 20,
807 u >> 20,
808 t >> 20,
809 t_parse
810 );
811 }
812 let total_errors = parser.error_count();
813 self.last_syntax_errors = parser.take_errors();
814 drop(parser);
817 if total_errors > 0 {
818 crate::warn!(
819 "[JS] {} syntax error(s) recovered; executing best-effort",
820 total_errors
821 );
822 for e in self.last_syntax_errors.iter().take(5) {
823 crate::warn!(
824 "[JS] SyntaxError: {} (token #{})",
825 e.message,
826 e.token_index
827 );
828 }
829 }
830 let mut interp = self.new_interp();
831 let scope = self.global.clone();
832 let global_this = self.global.borrow().vars.get("globalThis").cloned().unwrap_or(Value::Undefined);
836 #[cfg(target_os = "none")]
837 let t_exec0 = crate::os_lib::platform::now_ms();
838 #[cfg(target_os = "none")]
839 let allocs0 = crate::os_lib::platform::alloc_count();
840 let result = interp.exec_top_statements(&program.body, &scope, &global_this);
841 drop(program);
842 interp.run_event_loop();
844 (self.host.after_eval)(&mut interp);
845 #[cfg(target_os = "none")]
846 {
847 let t_exec = crate::os_lib::platform::now_ms().saturating_sub(t_exec0);
848 crate::os_lib::platform::responsiveness_record_ms(crate::os_lib::platform::Lat::JsRun, t_exec);
849 if is_large || t_exec + t_parse >= 1000 {
850 crate::warn!(
851 "[JS][TIME] len={} 解析={}ms 実行(イベントループ込み)={}ms steps={} allocs={}",
852 source.len(),
853 t_parse,
854 t_exec,
855 interp.steps,
856 crate::os_lib::platform::alloc_count().saturating_sub(allocs0)
857 );
858 }
859 }
860 #[cfg(target_os = "none")]
861 if is_large {
862 let _ = super::cycle_gc::collect(true);
863 }
864 let _ = is_large;
865 self.out.push_str(&interp.out);
867 if interp.aborted {
868 return Err(String::from("script aborted (step/depth budget exceeded)"));
869 }
870 match result {
871 Ok(Completion::Normal(v)) | Ok(Completion::Return(v)) => Ok(v),
872 Ok(_) => Ok(Value::Undefined),
873 Err(thrown) => {
874 self.last_thrown = Some(thrown.clone());
875 let err_str = thrown.to_js_string();
876 if err_str == "[object Object]" {
877 if let Value::Object(o) = &thrown {
878 let name = o.borrow().props.get("name").map(|v| v.to_js_string()).unwrap_or_else(|| alloc::string::String::from("Error"));
879 let msg = o.borrow().props.get("message").map(|v| v.to_js_string()).unwrap_or_else(|| alloc::string::String::from(""));
880 let stack = o.borrow().props.get("stack").map(|v| v.to_js_string()).unwrap_or_else(|| alloc::string::String::from(""));
881 crate::warn!("[JS] [JS_ERR] {}: {}\nStack:\n{}", name, msg, stack);
882 }
883 }
884 Err(err_str)
885 }
886 }
887 }
888}
889
890pub struct Interp {
892 pub steps: u64,
893 pub max_steps: u64,
896 pub(crate) task_start: u64,
898 pub(crate) task_depth: u32,
900 pub(crate) microtask_step_cap: u64,
902 pub(crate) vm_stack: Vec<Value>,
904 pub(crate) window_pos: usize,
906 pub(crate) strict: bool,
909 pub(crate) implicit_globals: Vec<Rc<str>>,
911 pub(crate) arg_pool: Vec<Vec<Value>>,
913 pub(crate) scope_pool: Vec<Rc<RefCell<Scope>>>,
915 pub depth: u32,
916 pub max_depth: u32,
917 pub stack_limit: (usize, usize),
920 pub aborted: bool,
921 pub out: String,
922 pub(crate) host: &'static super::host::HostHooks,
924 pub(crate) host_state: Rc<dyn core::any::Any>,
926 pub microtasks: Rc<RefCell<VecDeque<Job>>>,
928 gen_replay: Option<GenReplay>,
930 pub macrotasks: Rc<RefCell<VecDeque<TimerTask>>>,
932 pub clock_skew: Rc<core::cell::Cell<u64>>,
934 pub base_url: String,
936 pub global: Rc<RefCell<Scope>>,
938 pub modules: ModuleRegistry,
940 pub builtin_fn_cache: Rc<RefCell<BTreeMap<usize, Value>>>,
942 pub runtime_id: u64,
944 pub units_cache: Rc<RefCell<super::builtins::UnitsCache>>,
946 pub(crate) wm_index: WeakMapIndex,
948 pub(crate) global_lexicals: Rc<RefCell<BTreeSet<Rc<str>>>>,
950 pending_label: Option<Rc<str>>,
955 pending_new_target: Option<Value>,
959 pub(crate) forof_preset: Option<Value>,
961 pub(crate) join_stack: Vec<usize>,
963 new_target_stack: Vec<Value>,
966 pub(crate) derived_this_stack: Vec<Option<Value>>,
968 pub call_names: Vec<Value>,
972 pub(crate) active_param_names: Vec<Vec<Rc<str>>>,
974 pub(crate) eval_ctx_stack: Vec<super::ast::EvalSyntaxCtx>,
976 pub(crate) private_brand_seq: Rc<core::cell::Cell<u64>>,
978}
979
980type EvalResult = Result<Value, Value>;
981
982impl Interp {
983 #[inline]
985 pub(crate) fn next_private_brand_id(&self) -> u64 {
986 let id = self.private_brand_seq.get();
987 self.private_brand_seq.set(id.wrapping_add(1));
988 id
989 }
990 #[inline]
992 pub(crate) fn effective_this(&self, fallback: &Value) -> Value {
993 if let Some(Some(dt)) = self.derived_this_stack.last() {
994 dt.clone()
995 } else {
996 fallback.clone()
997 }
998 }
999 #[inline]
1001 pub(crate) fn global_object(&self) -> Option<ObjRef> {
1002 match self.global.borrow().vars.get("globalThis") {
1003 Some(Value::Object(o)) => Some(o.clone()),
1004 _ => None,
1005 }
1006 }
1007
1008 pub(crate) fn sync_global_prop_if_present(&self, name: &str, val: &Value) -> Option<Value> {
1011 if self.global_lexicals.borrow().contains(name) {
1012 return None;
1013 }
1014 let w = self.global_object()?;
1015 let mut wb = w.borrow_mut();
1016 if wb.get_attr(name).is_some_and(|a| !a.writable) {
1017 return wb.props.get(name).cloned();
1018 }
1019 if let Some(slot) = wb.props.get_mut(name) {
1020 *slot = val.clone();
1021 }
1022 None
1023 }
1024
1025 #[inline]
1030 pub fn builtin_fn_val(&self, name: &'static str, func: NativeFn) -> Value {
1031 let key = func as usize;
1032 if let Some(v) = self.builtin_fn_cache.borrow().get(&key) {
1033 return v.clone();
1034 }
1035 let val = Value::Object(Obj::native(name, func));
1036 self.builtin_fn_cache.borrow_mut().insert(key, val.clone());
1037 val
1038 }
1039
1040 pub fn char_unit_val(&self, u: Option<u16>) -> Value {
1043 let Some(u) = u else { return self.empty_str_val() };
1044 if u >= 128 {
1045 return Value::str(String::from_utf16_lossy(&[u]));
1046 }
1047 let key = u as usize + 1;
1048 if let Some(v) = self.builtin_fn_cache.borrow().get(&key) {
1049 return v.clone();
1050 }
1051 let val = Value::str(String::from(u as u8 as char));
1052 self.builtin_fn_cache.borrow_mut().insert(key, val.clone());
1053 val
1054 }
1055
1056 #[inline]
1058 pub fn empty_str_val(&self) -> Value {
1059 if let Some(v) = self.builtin_fn_cache.borrow().get(&0) {
1060 return v.clone();
1061 }
1062 let val = Value::str("");
1063 self.builtin_fn_cache.borrow_mut().insert(0, val.clone());
1064 val
1065 }
1066}
1067
1068
1069pub(crate) mod bytecode;
1074pub(crate) mod exec;
1075pub(crate) mod iter_gen;
1076pub(crate) mod gen_vm;
1077pub(crate) mod eval_expr;
1078pub(crate) mod promise_loop;
1079pub(crate) mod operators;
1080pub(crate) mod calls;
1081pub(crate) mod properties;
1082
1083pub(crate) enum CallKind {
1084 User(FunctionData),
1085 Native(NativeFn),
1086 Resolver(Rc<RefCell<PromiseState>>, bool),
1087 Proxy {
1088 target: ObjRef,
1089 handler: ObjRef,
1090 },
1091 Bound {
1092 target: Value,
1093 bound_this: Value,
1094 bound_args: Vec<Value>,
1095 },
1096 NotCallable(&'static str),
1097}
1098
1099#[inline(always)]
1101pub(crate) fn extract_call_target(obj: &ObjRef, host: &super::host::HostHooks) -> CallKind {
1102 let b = obj.borrow();
1103 match &b.kind {
1104 ObjKind::Function(fd) => CallKind::User(fd.clone()),
1105 ObjKind::Native { func, .. } => CallKind::Native(*func),
1106 ObjKind::Resolver { state, reject } => CallKind::Resolver(state.clone(), *reject),
1107 ObjKind::Proxy(p) => CallKind::Proxy {
1108 target: p.target.clone(),
1109 handler: p.handler.clone(),
1110 },
1111 ObjKind::Bound(bd) => CallKind::Bound {
1112 target: bd.target.clone(),
1113 bound_this: bd.bound_this.clone(),
1114 bound_args: bd.bound_args.clone(),
1115 },
1116 ObjKind::Array(_) => CallKind::NotCallable("array"),
1117 ObjKind::Plain => CallKind::NotCallable("object"),
1118 ObjKind::HostRef(h) => CallKind::NotCallable((host.class_name)(*h).1),
1119 _ => CallKind::NotCallable("other"),
1120 }
1121}
1122
1123pub fn iterable_values(v: &Value) -> Vec<Value> {
1127 match v {
1128 Value::Str(s) => s.chars().map(|c| Value::str(c.to_string())).collect(),
1129 Value::Object(o) => {
1130 let b = o.borrow();
1131 match &b.kind {
1132 ObjKind::Array(items) => items.clone(),
1133 ObjKind::SetObj(items) => items.clone(),
1134 ObjKind::MapObj(entries) => entries
1135 .iter()
1136 .map(|(k, val)| Value::Object(Obj::array(alloc::vec![k.clone(), val.clone()])))
1137 .collect(),
1138 ObjKind::Generator(_) => Vec::new(),
1141 ObjKind::Iter => {
1147 let items = b.props.get("_items").cloned();
1148 let pos = b
1149 .props
1150 .get("_pos")
1151 .map(|v| v.to_number() as usize)
1152 .unwrap_or(0);
1153 match items {
1154 Some(Value::Object(arr)) => match &arr.borrow().kind {
1155 ObjKind::Array(v) => v.get(pos..).map(|s| s.to_vec()).unwrap_or_default(),
1156 _ => Vec::new(),
1157 },
1158 _ => Vec::new(),
1159 }
1160 }
1161 _ => Vec::new(),
1162 }
1163 }
1164 _ => Vec::new(),
1165 }
1166}
1167
1168pub(crate) fn to_property_key(v: &Value) -> alloc::borrow::Cow<'_, str> {
1170 match v {
1171 Value::Number(n) => alloc::borrow::Cow::Owned(fmt_number(*n)),
1172 Value::Str(s) => alloc::borrow::Cow::Borrowed(s.as_str()),
1173 _ => alloc::borrow::Cow::Owned(v.to_js_string()),
1174 }
1175}
1176
1177fn shift_amount(b: &super::bigint::BigInt) -> Option<i64> {
1180 let f = b.to_f64();
1181 if !f.is_finite() {
1182 return None;
1183 }
1184 if libm::fabs(f) >= 2147483648.0 {
1186 return None;
1187 }
1188 Some(f as i64)
1189}
1190
1191pub(crate) fn to_i32(n: f64) -> i32 {
1195 if !n.is_finite() {
1196 return 0;
1197 }
1198 let m = libm::trunc(n);
1199 let r = libm::fmod(m, 4294967296.0);
1200 let r = if r < 0.0 { r + 4294967296.0 } else { r };
1201 (r as u64 as u32) as i32
1202}
1203pub(crate) fn to_u32(n: f64) -> u32 {
1204 to_i32(n) as u32
1205}
1206
1207fn powf(base: f64, exp: f64) -> f64 {
1208 super::numfmt::js_pow(base, exp)
1209}
1210
1211fn loose_eq(l: &Value, r: &Value) -> bool {
1212 match (l, r) {
1213 (Value::Null, Value::Undefined) | (Value::Undefined, Value::Null) => true,
1214 (Value::Null, Value::Null) | (Value::Undefined, Value::Undefined) => true,
1215 (Value::Null | Value::Undefined, Value::Object(o)) | (Value::Object(o), Value::Null | Value::Undefined) => {
1217 o.borrow().flags & crate::os_lib::ecma::value::OBJ_FLAG_HTMLDDA != 0
1218 }
1219 (Value::Null | Value::Undefined, _) | (_, Value::Null | Value::Undefined) => false,
1223 (Value::Number(a), Value::Number(b)) => a == b,
1224 (Value::Str(a), Value::Str(b)) => a == b,
1225 (Value::Bool(a), Value::Bool(b)) => a == b,
1226 (Value::Object(_), Value::Object(_)) => l.strict_eq(r),
1227 (Value::Object(o), other) | (other, Value::Object(o))
1232 if !matches!(other, Value::Object(_)) =>
1233 {
1234 loose_eq(&Value::str(Value::Object(o.clone()).to_js_string()), other)
1237 }
1238 (Value::Number(_), Value::Str(_))
1240 | (Value::Str(_), Value::Number(_))
1241 | (Value::Bool(_), _)
1242 | (_, Value::Bool(_)) => l.to_number() == r.to_number(),
1243 _ => false,
1244 }
1245}
1246
1247fn cmp_f64(a: f64, b: f64) -> Option<core::cmp::Ordering> {
1249 if a.is_nan() || b.is_nan() {
1250 return None;
1251 }
1252 Some(if a < b {
1253 core::cmp::Ordering::Less
1254 } else if a > b {
1255 core::cmp::Ordering::Greater
1256 } else {
1257 core::cmp::Ordering::Equal
1258 })
1259}
1260
1261fn cmp(l: &Value, r: &Value, pred: fn(core::cmp::Ordering) -> bool) -> Value {
1262 let prim = |v: &Value| -> Option<Value> {
1267 let Value::Object(o) = v else { return None };
1268 if matches!(o.borrow().kind, ObjKind::DateObj(_)) {
1269 return Some(Value::Number(v.to_number()));
1270 }
1271 Some(Value::str(v.to_js_string()))
1272 };
1273 let (lp, rp) = (prim(l), prim(r));
1274 let (l, r) = (lp.as_ref().unwrap_or(l), rp.as_ref().unwrap_or(r));
1275 if let (Value::Str(a), Value::Str(b)) = (l, r) {
1277 return Value::Bool(pred(a.as_str().cmp(b.as_str())));
1278 }
1279 let a = l.to_number();
1280 let b = r.to_number();
1281 if a.is_nan() || b.is_nan() {
1282 return Value::Bool(false);
1283 }
1284 let ord = if a < b {
1285 core::cmp::Ordering::Less
1286 } else if a > b {
1287 core::cmp::Ordering::Greater
1288 } else {
1289 core::cmp::Ordering::Equal
1290 };
1291 Value::Bool(pred(ord))
1292}
1293
1294fn break_cycles(roots: alloc::vec::Vec<Value>, scopes: alloc::vec::Vec<Rc<RefCell<Scope>>>) {
1301 let mut vals = roots;
1302 let mut scopes = scopes;
1303 loop {
1304 if let Some(sc) = scopes.pop() {
1305 if let Ok(mut s) = sc.try_borrow_mut() {
1306 if let Some(p) = s.parent.take() {
1307 scopes.push(p);
1308 }
1309 vals.extend(core::mem::take(&mut s.vars).into_values());
1310 }
1311 continue;
1312 }
1313 let Some(val) = vals.pop() else { break };
1314 let Value::Object(obj) = val else { continue };
1315 let (proto, props, accessors, kind) = if let Ok(mut o) = obj.try_borrow_mut() {
1316 let proto = o.proto.take();
1317 let props = core::mem::take(&mut o.props);
1318 let accessors = o.rare.take().map(|r| r.accessors).unwrap_or_default();
1319 let kind = core::mem::replace(&mut o.kind, super::value::ObjKind::Plain);
1320 o.clear_references();
1321 (proto, props, accessors, kind)
1322 } else {
1323 continue;
1324 };
1325 if let Some(p) = proto {
1326 vals.push(Value::Object(p));
1327 }
1328 vals.extend(props.into_values());
1329 for (_, acc) in accessors {
1330 vals.extend(acc.get);
1331 vals.extend(acc.set);
1332 }
1333 match kind {
1334 super::value::ObjKind::Array(items) | super::value::ObjKind::SetObj(items) => vals.extend(items),
1335 super::value::ObjKind::Function(f) => {
1336 if let Some(bt) = &f.bound_this {
1337 vals.push((**bt).clone());
1338 }
1339 scopes.push(f.closure.clone());
1340 }
1341 super::value::ObjKind::MapObj(entries) => {
1342 for (k, v) in entries {
1343 vals.push(k);
1344 vals.push(v);
1345 }
1346 }
1347 super::value::ObjKind::PromiseObj(p) => {
1348 if let Ok(mut st) = p.try_borrow_mut() {
1349 vals.push(core::mem::replace(&mut st.value, Value::Undefined));
1350 for r in core::mem::take(&mut st.reactions) {
1351 vals.extend(r.on_fulfilled);
1352 vals.extend(r.on_rejected);
1353 }
1354 }
1355 }
1356 super::value::ObjKind::Resolver { state, .. } => {
1357 if let Ok(mut st) = state.try_borrow_mut() {
1358 vals.push(core::mem::replace(&mut st.value, Value::Undefined));
1359 }
1360 }
1361 super::value::ObjKind::Bound(b) => {
1362 vals.push(b.target);
1363 vals.push(b.bound_this);
1364 vals.extend(b.bound_args);
1365 }
1366 super::value::ObjKind::Proxy(p) => {
1367 vals.push(Value::Object(p.target));
1368 vals.push(Value::Object(p.handler));
1369 }
1370 _ => {}
1371 }
1372 }
1373}
1374
1375impl Drop for JsRuntime {
1376 fn drop(&mut self) {
1377 let mut roots = alloc::vec::Vec::new();
1379 if let Ok(mut mt) = self.microtasks.try_borrow_mut() {
1380 for j in mt.drain(..) {
1381 roots.extend(j.handler);
1382 roots.push(j.arg);
1383 }
1384 }
1385 if let Ok(mut mt) = self.macrotasks.try_borrow_mut() {
1386 for t in mt.drain(..) {
1387 roots.push(t.cb);
1388 roots.extend(t.args);
1389 }
1390 }
1391 if let Ok(mut m) = self.modules.try_borrow_mut() {
1392 m.clear();
1393 }
1394 (self.host.teardown_runtime)(self.runtime_id, self.host_state.as_ref(), &mut roots);
1395 break_cycles(roots, alloc::vec![self.global.clone()]);
1396 }
1397}
1398
1399impl Interp {
1400 pub(crate) fn take_pending_new_target(&mut self) -> Option<Value> {
1402 self.pending_new_target.take()
1403 }
1404
1405 pub(crate) fn resolve_with_scope(
1407 &mut self,
1408 scope: &Rc<RefCell<Scope>>,
1409 name: &str,
1410 ) -> Result<Option<(super::value::ObjRef, bool)>, Value> {
1411 let mut cur = scope.clone();
1412 loop {
1413 let (wobj, has_local, in_tdz, next) = {
1414 let b = cur.borrow();
1415 let in_tdz = b.tdz.as_ref().is_some_and(|t| t.iter().any(|n| &**n == name));
1416 let has_local = b.vars.contains_key(name);
1417 (b.with_obj.clone(), has_local, in_tdz, b.parent.clone())
1418 };
1419 if let Some(obj) = wobj {
1420 let has = if super::builtins::is_proxy_or_has_proxy_proto(&obj) {
1421 super::builtins::pm_has_property(self, &obj, name)?
1422 } else {
1423 self.has_property_chain(&obj, name)
1424 };
1425 if has {
1426 let unscopables = self.get_property(&Value::Object(obj.clone()), "Symbol(Symbol.unscopables)")?;
1427 if let Value::Object(uo) = unscopables {
1428 let blocked = self.get_property(&Value::Object(uo), name)?.truthy();
1429 if !blocked {
1430 return Ok(Some((obj, true)));
1431 }
1432 } else {
1433 return Ok(Some((obj, false)));
1434 }
1435 }
1436 } else if in_tdz || has_local {
1437 return Ok(None);
1438 }
1439 match next {
1440 Some(p) => cur = p,
1441 None => return Ok(None),
1442 }
1443 }
1444 }
1445
1446 pub(crate) fn with_get_binding_value(
1448 &mut self,
1449 wobj: &super::value::ObjRef,
1450 name: &str,
1451 _had_unscopables: bool,
1452 ) -> Result<Value, Value> {
1453 let still_has = if super::builtins::is_proxy_or_has_proxy_proto(wobj) {
1454 super::builtins::pm_has_property(self, wobj, name)?
1455 } else {
1456 self.has_property_chain(wobj, name)
1457 };
1458 if !still_has {
1459 if self.strict {
1460 return Err(self.reference_error(alloc::format!("{} is not defined", name)));
1461 }
1462 return Ok(Value::Undefined);
1463 }
1464 self.get_property(&Value::Object(wobj.clone()), name)
1465 }
1466
1467 pub(crate) fn with_set_mutable_binding(
1469 &mut self,
1470 wobj: &super::value::ObjRef,
1471 name: &str,
1472 val: Value,
1473 ) -> Result<(), Value> {
1474 let still_exists = if super::builtins::is_proxy_or_has_proxy_proto(wobj) {
1475 super::builtins::pm_has_property(self, wobj, name)?
1476 } else {
1477 self.has_property_chain(wobj, name)
1478 };
1479 if !still_exists && self.strict {
1480 return Err(self.reference_error(alloc::format!("{} is not defined", name)));
1481 }
1482 self.put_value(&Value::Object(wobj.clone()), name, val)
1483 }
1484}