1use super::*;
5
6#[inline]
9pub(crate) fn is_class_ctor(o: &ObjRef) -> bool {
10 let b = o.borrow();
11 matches!(b.kind, super::super::value::ObjKind::Function(_))
12 && b.get_attr("prototype").is_some_and(|a| !a.writable)
13}
14
15pub(crate) fn func_diag_name(func: &Value) -> String {
16 match func {
17 Value::Object(o) => {
18 let b = o.borrow();
19 b.props
20 .get("name")
21 .map(|v| v.to_js_string())
22 .filter(|n| !n.is_empty())
23 .or_else(|| match &b.kind {
24 ObjKind::Function(fd) if !fd.name().is_empty() => Some(fd.name().to_string()),
25 _ => None,
26 })
27 .or_else(|| b.props.get("_diag_name").map(|v| alloc::format!("~{}", v.to_js_string())))
28 .unwrap_or_else(|| String::from("<anonymous>"))
29 }
30 _ => String::from("<anonymous>"),
31 }
32}
33
34fn is_builtin_eval(func: &Value) -> bool {
36 match func {
37 Value::Object(o) => matches!(&o.borrow().kind,
38 ObjKind::Native { func, .. } if *func as usize == super::super::builtins::global_eval as *const () as usize),
39 _ => false,
40 }
41}
42
43fn func_diag_detail(func: &Value, host: &super::super::host::HostHooks) -> String {
45 let name = func_diag_name(func);
46 let Value::Object(o) = func else { return name };
47 let b = o.borrow();
48 let fd = match &b.kind {
49 ObjKind::Function(fd) => fd,
50 ObjKind::Native { name: n, .. } => return alloc::format!("{} [native {}]", name, n),
51 ObjKind::Bound(bd) => {
52 let t = bd.target.clone();
53 let nargs = bd.bound_args.len();
54 drop(b);
55 return alloc::format!("{} [bound, 引数 {} 個] → {}", name, nargs, func_diag_detail(&t, host));
56 }
57 ObjKind::Proxy(p) => {
58 let t = Value::Object(p.target.clone());
59 drop(b);
60 return alloc::format!("{} [proxy] → {}", name, func_diag_detail(&t, host));
61 }
62 k => {
63 let kind = match k {
64 ObjKind::Plain => "plain",
65 ObjKind::Array(_) => "array",
66 ObjKind::HostRef(h) => (host.class_name)(*h).0,
67 _ => "other",
68 };
69 return alloc::format!("{} [{}] props={:?}", name, kind, b.props.keys().take(8).collect::<Vec<_>>());
70 }
71 };
72 let params: Vec<String> = fd
73 .params()
74 .iter()
75 .map(|p| match &p.pattern {
76 crate::os_lib::ecma::ast::Pattern::Identifier(n) => n.to_string(),
77 other => alloc::format!("{:?}", other).chars().take(20).collect(),
78 })
79 .collect();
80 let first: String = fd
81 .body()
82 .stmts()
83 .first()
84 .map(|st| alloc::format!("{:?}", st))
85 .unwrap_or_default()
86 .chars()
87 .take(240)
88 .collect();
89 alloc::format!("{}({}) {{ {} }}", name, params.join(","), first)
90}
91
92impl Interp {
93 pub(crate) fn recursion_cycle_detail(&self) -> Vec<String> {
96 let mut seen: Vec<usize> = Vec::new();
97 let mut out = Vec::new();
98 for f in self.call_names.iter().rev().take(64) {
99 let key = match f {
100 Value::Object(o) => match &o.borrow().kind {
101 ObjKind::Function(fd) => Rc::as_ptr(fd.body()) as usize,
102 _ => Rc::as_ptr(o) as usize,
103 },
104 _ => 0,
105 };
106 if seen.contains(&key) {
107 continue;
108 }
109 seen.push(key);
110 out.push(func_diag_detail(f, self.host));
111 if out.len() >= 6 {
112 break;
113 }
114 }
115 out
116 }
117
118 pub(crate) fn call_stack_names(&self, n: usize) -> Vec<String> {
120 self.call_names.iter().rev().take(n).map(func_diag_name).collect()
121 }
122
123 pub(crate) fn eval_call(
124 &mut self,
125 callee: &Expression,
126 arguments: &[Expression],
127 optional: bool,
128 scope: &Rc<RefCell<Scope>>,
129 this: &Value,
130 ) -> EvalResult {
131 if matches!(callee, Expression::Super) {
133 let sc = self.super_ctor(scope)?;
134 let args = self.eval_arguments(arguments, scope, this)?;
135 if matches!(sc, Value::Null) || !is_constructor(&sc) {
136 return Err(self.type_error("Super constructor is not a constructor"));
137 }
138 let dt_cell = super::scope_derived_this(scope);
139 if dt_cell.as_ref().is_some_and(|c| c.borrow().is_some()) {
140 return Err(self.reference_error("Super constructor may only be called once"));
141 }
142 let nt_for_super = self.new_target_stack.last().cloned().unwrap_or_else(|| sc.clone());
143 let r = self.construct_with_target(&sc, &args, &nt_for_super)?;
144 if let Some(c) = dt_cell {
145 *c.borrow_mut() = Some(r.clone());
146 }
147 if let Some(slot) = self.derived_this_stack.last_mut() {
148 *slot = Some(r.clone());
149 }
150 return Ok(r);
151 }
152 if let Expression::Member {
154 object, property, ..
155 } = callee
156 {
157 if matches!(**object, Expression::Super) {
158 let eff_this = self.resolve_this(scope, this)?;
159 let f = self.super_get(scope, property, &eff_this)?;
160 let args = self.eval_arguments(arguments, scope, this)?;
161 return self.call_value(&f, eff_this, &args);
162 }
163 }
164 if let Expression::Index { object, index, .. } = callee {
166 if matches!(**object, Expression::Super) {
167 let eff_this = self.resolve_this(scope, this)?;
168 let k = self.eval_key(index, scope, this)?;
169 let f = self.super_get(scope, &to_property_key(&k), &eff_this)?;
170 let args = self.eval_arguments(arguments, scope, this)?;
171 return self.call_value(&f, eff_this, &args);
172 }
173 }
174 let (func, call_this, broke) = self.resolve_callee(callee, scope, this)?;
177 if broke {
178 return Ok(Value::Undefined);
179 }
180 if optional && matches!(func, Value::Undefined | Value::Null) {
181 return Ok(Value::Undefined);
182 }
183 let args = self.eval_arguments(arguments, scope, this)?;
184 if let Some(e) = self.not_callable(&func, callee, &call_this) {
188 return Err(e);
189 }
190 if matches!(callee, Expression::Identifier(n) if &**n == "eval") && is_builtin_eval(&func) {
192 let first = args.first().cloned().unwrap_or(Value::Undefined);
193 self.recycle_args(args);
194 return match &first {
195 Value::Str(s) => {
196 let src = s.to_string();
197 self.eval_source_in(&src, scope, this)
198 }
199 _ => Ok(first),
200 };
201 }
202 let r = self.call_value(&func, call_this, &args);
203 self.recycle_args(args);
204 r
205 }
206
207 pub(crate) fn not_callable(&mut self, func: &Value, callee: &Expression, call_this: &Value) -> Option<Value> {
209 let callable = match func {
210 Value::Object(o) => o.borrow().is_callable(),
211 _ => false,
212 };
213 if callable {
214 if let Value::Object(o) = func {
216 if is_class_ctor(o) {
217 let name = match &o.borrow().kind {
218 super::super::value::ObjKind::Function(fd) => String::from(fd.name()),
219 _ => String::new(),
220 };
221 return Some(self.type_error(alloc::format!(
222 "Class constructor {} cannot be invoked without 'new'",
223 name
224 )));
225 }
226 }
227 return None;
228 }
229 {
230 let desc = super::properties::describe_expr(callee);
231 let recv = match call_this {
234 Value::Object(o) => o
235 .borrow()
236 .kind
237 .host_ref()
238 .and_then(|h| (self.host.describe)(self, h))
239 .map(|d| alloc::format!(" (receiver {})", d)),
240 _ => None,
241 };
242 Some(self.type_error(alloc::format!("{} is not a function{}", desc, recv.unwrap_or_default())))
243 }
244 }
245
246 pub(crate) fn resolve_callee(
254 &mut self,
255 callee: &Expression,
256 scope: &Rc<RefCell<Scope>>,
257 this: &Value,
258 ) -> Result<(Value, Value, bool), Value> {
259 match callee {
260 Expression::Member {
261 object,
262 property,
263 optional: mopt,
264 } if !matches!(**object, Expression::Super) => {
265 let (obj, broke) = self.eval_chain_object(object, scope, this)?;
266 if broke {
267 return Ok((Value::Undefined, Value::Undefined, true));
268 }
269 if *mopt && matches!(obj, Value::Undefined | Value::Null) {
270 return Ok((Value::Undefined, Value::Undefined, true));
271 }
272 let f = if property.starts_with('#') {
273 self.private_get(&obj, property, scope)?
274 } else {
275 self.get_property_of_expr(&obj, property, object)?
276 };
277 Ok((f, obj, false))
278 }
279 Expression::Index {
280 object,
281 index,
282 optional: iopt,
283 } => {
284 if matches!(**object, Expression::Super) {
285 let key = self.eval_key(index, scope, this)?;
286 let f = self.super_get(scope, &to_property_key(&key), this)?;
287 return Ok((f, this.clone(), false));
288 }
289 let (obj, broke) = self.eval_chain_object(object, scope, this)?;
290 if broke {
291 return Ok((Value::Undefined, Value::Undefined, true));
292 }
293 if *iopt && matches!(obj, Value::Undefined | Value::Null) {
294 return Ok((Value::Undefined, Value::Undefined, true));
295 }
296 let key = self.eval_key_for(&obj, index, scope, this)?;
297 let f = self.get_property(&obj, &to_property_key(&key))?;
298 Ok((f, obj, false))
299 }
300 Expression::Identifier(name) if scope.borrow().has_with => {
301 if let Some((wobj, had_u)) = self.resolve_with_scope(scope, name)? {
302 let f = self.with_get_binding_value(&wobj, name, had_u)?;
303 return Ok((f, Value::Object(wobj), false));
304 }
305 let f = self.load_identifier_no_with(name, scope)?;
306 Ok((f, Value::Undefined, false))
307 }
308 _ => {
309 let (f, broke) = self.eval_chain_object(callee, scope, this)?;
310 Ok((f, Value::Undefined, broke))
311 }
312 }
313 }
314
315 pub(crate) fn eval_chain_object(
321 &mut self,
322 expr: &Expression,
323 scope: &Rc<RefCell<Scope>>,
324 this: &Value,
325 ) -> Result<(Value, bool), Value> {
326 match expr {
327 Expression::Member {
328 object,
329 property,
330 optional,
331 } => {
332 if matches!(**object, Expression::Super) {
333 return Ok((self.super_get(scope, property, this)?, false));
334 }
335 let (obj, broke) = self.eval_chain_object(object, scope, this)?;
336 if broke {
337 return Ok((Value::Undefined, true));
338 }
339 if *optional && matches!(obj, Value::Undefined | Value::Null) {
340 return Ok((Value::Undefined, true));
341 }
342 if property.starts_with('#') {
343 return Ok((self.private_get(&obj, property, scope)?, false));
344 }
345 Ok((self.get_property(&obj, property)?, false))
346 }
347 Expression::Index {
348 object,
349 index,
350 optional,
351 } => {
352 if matches!(**object, Expression::Super) {
353 let key = self.eval_key(index, scope, this)?;
354 return Ok((self.super_get(scope, &to_property_key(&key), this)?, false));
355 }
356 let (obj, broke) = self.eval_chain_object(object, scope, this)?;
357 if broke {
358 return Ok((Value::Undefined, true));
359 }
360 if *optional && matches!(obj, Value::Undefined | Value::Null) {
361 return Ok((Value::Undefined, true));
362 }
363 let key = self.eval_key_for(&obj, index, scope, this)?;
364 Ok((self.get_property(&obj, &to_property_key(&key))?, false))
365 }
366 Expression::Call {
367 callee,
368 arguments,
369 optional,
370 } => {
371 let involves_super = matches!(**callee, Expression::Super)
372 || matches!(&**callee, Expression::Member { object, .. } if matches!(**object, Expression::Super));
373 if involves_super {
374 return Ok((self.eval(expr, scope, this)?, false));
375 }
376 let (func, call_this, broke) = self.resolve_callee(callee, scope, this)?;
377 if broke {
378 return Ok((Value::Undefined, true));
379 }
380 if *optional && matches!(func, Value::Undefined | Value::Null) {
381 return Ok((Value::Undefined, true));
382 }
383 let args = self.eval_arguments(arguments, scope, this)?;
384 let r = self.call_value(&func, call_this, &args);
385 self.recycle_args(args);
386 Ok((r?, false))
387 }
388 _ => Ok((self.eval(expr, scope, this)?, false)),
389 }
390 }
391
392 pub(crate) fn eval_arguments(
394 &mut self,
395 arguments: &[Expression],
396 scope: &Rc<RefCell<Scope>>,
397 this: &Value,
398 ) -> Result<Vec<Value>, Value> {
399 let mut args = self.arg_pool.pop().unwrap_or_default();
401 args.reserve(arguments.len());
402 for a in arguments {
403 if let Expression::Spread(inner) = a {
404 let v = self.eval(inner, scope, this)?;
405 let items = self.spread_values(&v)?;
406 args.extend(items);
407 } else {
408 args.push(self.eval(a, scope, this)?);
409 }
410 }
411 Ok(args)
412 }
413
414 pub(crate) fn recycle_args(&mut self, mut args: Vec<Value>) {
416 if self.arg_pool.len() < 64 && args.capacity() <= 32 {
417 args.clear();
418 self.arg_pool.push(args);
419 }
420 }
421
422 pub(crate) fn eval_new(
423 &mut self,
424 callee: &Expression,
425 arguments: &[Expression],
426 scope: &Rc<RefCell<Scope>>,
427 this: &Value,
428 ) -> EvalResult {
429 let func = self.eval(callee, scope, this)?;
430 let args = self.eval_arguments(arguments, scope, this)?;
431 let res = self.construct_object(&func, &args);
432 self.recycle_args(args);
433 res
434 }
435
436 pub fn construct_value(&mut self, func: &Value, args: &[Value]) -> EvalResult {
438 self.construct_object(func, args)
439 }
440
441 pub(crate) fn construct_object(&mut self, func: &Value, args: &[Value]) -> EvalResult {
442 self.construct_with_target(func, args, func)
443 }
444
445 pub(crate) fn construct_with_target(&mut self, func: &Value, args: &[Value], new_target: &Value) -> EvalResult {
448 if !is_constructor(func) {
449 let d = describe_callee_value(func);
450 return Err(self.type_error(alloc::format!("{} is not a constructor", d)));
451 }
452 if let Value::Object(po) = func {
454 if matches!(po.borrow().kind, ObjKind::Proxy(_)) {
455 match super::super::builtins::proxy_step(self, po, "construct")? {
456 super::super::builtins::PStep::Trap { target, handler, trap } => {
457 let arr = Value::Object(Obj::array(args.to_vec()));
458 let r = self.call_value(&trap, Value::Object(handler), &[Value::Object(target), arr, new_target.clone()])?;
459 if !matches!(r, Value::Object(_)) {
460 return Err(self.type_error("proxy [[Construct]] must return an object"));
461 }
462 return Ok(r);
463 }
464 super::super::builtins::PStep::Forward(target) => {
465 let nt = match new_target {
466 Value::Object(n) if Rc::ptr_eq(n, po) => Value::Object(target.clone()),
467 other => other.clone(),
468 };
469 return self.construct_with_target(&Value::Object(target), args, &nt);
470 }
471 super::super::builtins::PStep::Plain => {}
472 }
473 }
474 }
475 if let Value::Object(fo) = func {
481 let bound = match &fo.borrow().kind {
482 ObjKind::Bound(b) => Some((b.target.clone(), b.bound_args.clone())),
483 _ => None,
484 };
485 if let Some((target, mut all)) = bound {
486 all.extend_from_slice(args);
487 let nt = match (new_target, func) {
488 (Value::Object(a), Value::Object(b)) if Rc::ptr_eq(a, b) => target.clone(),
489 _ => new_target.clone(),
490 };
491 return self.construct_with_target(&target, &all, &nt);
492 }
493 }
494 if let Some(res) = (self.host.construct_element)(self, func, args, new_target) {
496 return res;
497 }
498 let is_derived = matches!(func, Value::Object(fo) if is_class_ctor(fo) && fo.borrow().props.contains_key("__superclass__"));
500 let inst = if is_derived {
501 Value::Undefined
502 } else {
503 let inst_obj = Obj::plain();
504 if let Value::Object(fo) = new_target {
505 if let Some(Value::Object(p)) = Obj::fn_prototype(fo) {
506 inst_obj.borrow_mut().proto = Some(p);
507 }
508 }
509 Value::Object(inst_obj)
510 };
511 self.pending_new_target = Some(new_target.clone());
517 let ret = self.call_value(func, inst.clone(), args);
518 self.pending_new_target = None;
520 let ret = ret?;
521 match ret {
522 Value::Object(ref r) => {
523 let is_native = matches!(func, Value::Object(f) if matches!(f.borrow().kind, ObjKind::Native { .. }));
526 let diff_target = !matches!(
527 (func, new_target),
528 (Value::Object(a), Value::Object(b)) if Rc::ptr_eq(a, b)
529 );
530 if is_native && !Rc::ptr_eq(r, match &inst { Value::Object(i) => i, _ => r }) {
531 let needs = {
532 let b = r.borrow();
533 b.proto.is_none()
534 && !b.is_null_proto()
535 && (diff_target || matches!(b.kind, ObjKind::Plain))
536 };
537 if needs {
538 if let Value::Object(fo) = new_target {
539 if let Some(Value::Object(p)) = Obj::fn_prototype(fo) {
540 r.borrow_mut().proto = Some(p);
541 }
542 }
543 }
544 }
545 Ok(ret)
546 }
547 prim @ (Value::Number(_) | Value::Str(_) | Value::Bool(_)) => {
549 if let (Value::Object(f), Value::Object(i)) = (func, &inst) {
550 let is_wrap_ctor = matches!(&f.borrow().kind, ObjKind::Native { name, .. } if matches!(&**name, "Number" | "String" | "Boolean"));
551 if is_wrap_ctor {
552 i.borrow_mut().rare_data_mut().primitive = Some(prim);
553 }
554 }
555 Ok(inst)
556 }
557 _ => Ok(inst),
558 }
559 }
560
561 #[inline]
563 pub(crate) fn call_enter(&mut self, func: &Value) -> Result<(), Value> {
564 self.depth += 1;
565 let sp = super::current_sp();
569 if sp < self.stack_limit.0.saturating_sub(super::JS_STACK_MARGIN) || sp > self.stack_limit.1 {
570 self.stack_limit = super::js_stack_window();
571 }
572 let used = self.stack_limit.1.saturating_sub(sp);
573 if self.depth > self.max_depth || sp < self.stack_limit.0 {
574 static N: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
575 if N.fetch_add(1, core::sync::atomic::Ordering::Relaxed) < 5 {
576 let top = self.call_stack_names(16);
577 crate::warn!(
578 "[JSPROF] call stack exceeded thread={:?} depth={} stack={}KB (steps={}) top={:?}",
579 crate::os_lib::platform::current_process_name(),
580 self.depth,
581 used / 1024,
582 self.steps,
583 top
584 );
585 for (i, d) in self.recursion_cycle_detail().iter().enumerate() {
586 crate::warn!("[JSPROF] 再帰している関数 {}: {}", i, d);
587 }
588 }
589 self.depth -= 1;
590 return Err(self.range_error("Maximum call stack size exceeded"));
591 }
592 self.call_names.push(func.clone());
594 if crate::os_lib::ecma::cycle_gc::should_collect() {
596 (self.host.gc_cleanup)(self);
598 if let Some(st) = crate::os_lib::ecma::cycle_gc::maybe_collect() {
599 crate::warn!(
600 "[JS][GC] objs={} scopes={} garbage_objs={} garbage_scopes={} (plain={} fn={} arr={} dom={} prom={} oth={}) heap={}MB",
601 st.objs,
602 st.scopes,
603 st.garbage_objs,
604 st.garbage_scopes,
605 st.count_plain,
606 st.count_func,
607 st.count_array,
608 st.count_dom,
609 st.count_promise,
610 st.count_other,
611 crate::os_lib::platform::heap_stats().0 / (1024 * 1024)
612 );
613 }
614 }
615 Ok(())
616 }
617
618 #[inline]
620 pub(crate) fn call_leave(&mut self) {
621 (self.host.after_call)(self);
622 self.call_names.pop();
623 self.depth -= 1;
624 }
625
626 #[inline]
628 pub(crate) fn call_value_with_new_target(
629 &mut self,
630 func: &Value,
631 this: Value,
632 args: &[Value],
633 new_target: Value,
634 ) -> EvalResult {
635 self.pending_new_target = Some(new_target);
636 self.call_value(func, this, args)
637 }
638
639 fn make_arguments_obj(&self, args: &[Value], callee: Value, is_strict: bool) -> Rc<RefCell<Obj>> {
641 let arguments_obj = Obj::array(args.to_vec());
642 if is_strict {
643 let tte_acc = super::super::builtins::extra_static::global_ctor_proto(self, "Function")
644 .and_then(|fp| fp.borrow().get_accessor("caller").cloned());
645 if let Some(acc) = tte_acc {
646 let mut ab = arguments_obj.borrow_mut();
647 ab.insert_accessor("callee", acc);
648 ab.insert_attr(
649 "callee",
650 super::super::value::PropertyAttributes {
651 writable: false,
652 enumerable: false,
653 configurable: false,
654 },
655 );
656 return arguments_obj.clone();
657 }
658 }
659 arguments_obj.borrow_mut().props.insert("callee".into(), callee);
660 arguments_obj
661 }
662
663 pub fn call_value(&mut self, func: &Value, this: Value, args: &[Value]) -> EvalResult {
665 self.call_enter(func)?;
666 let result = self.call_value_inner(func, this, args);
667 self.call_leave();
668 result
669 }
670
671 pub fn call_listener(
679 &mut self,
680 func: &Value,
681 this: Value,
682 args: &[Value],
683 context: &str,
684 ) -> bool {
685 match self.call_value(func, this, args) {
686 Ok(_) => true,
687 Err(thrown) => {
688 self.report_uncaught(context, &thrown);
689 false
690 }
691 }
692 }
693
694 pub fn report_uncaught(&mut self, context: &str, thrown: &Value) {
696 let mut repr = thrown.to_js_string();
697 if repr == "[object Object]" {
700 repr = alloc::format!("[object Object] {}", describe_thrown(thrown, 3));
701 }
702 let line = crate::os_lib::ecma::uncaught::format_uncaught(context, &repr);
703 crate::warn!("[JS] {}", line);
704 self.out.push_str(&line);
705 self.out.push('\n');
706 }
707
708 #[inline]
710 pub(crate) fn dispatch_call_kind(
711 &mut self,
712 kind: CallKind,
713 func: &Value,
714 this: Value,
715 args: &[Value],
716 ) -> EvalResult {
717 match kind {
718 CallKind::Native(f) => f(self, this, args),
719 CallKind::Resolver(state, reject) => {
720 let arg = args.first().cloned().unwrap_or(Value::Undefined);
721 if reject {
722 self.promise_reject(&state, arg);
723 } else {
724 self.promise_resolve(&state, arg);
725 }
726 Ok(Value::Undefined)
727 }
728 CallKind::User(fd) => {
729 let nt = self.pending_new_target.take().unwrap_or(Value::Undefined);
732 let pushed = !fd.is_arrow();
733 if pushed {
734 self.new_target_stack.push(nt);
735 }
736 let result = self.call_user_function(&fd, this, args, func.clone());
737 if pushed {
738 self.new_target_stack.pop();
739 }
740 result
741 }
742 CallKind::Proxy { .. } => {
743 let Value::Object(po) = func else {
744 return Err(self.type_error("not a function"));
745 };
746 match super::super::builtins::proxy_step(self, po, "apply")? {
747 super::super::builtins::PStep::Trap { target, handler, trap } => {
748 let arg_arr = Value::Object(Obj::array(args.to_vec()));
749 self.call_value(&trap, Value::Object(handler), &[Value::Object(target), this, arg_arr])
750 }
751 super::super::builtins::PStep::Forward(target) => self.call_value(&Value::Object(target), this, args),
752 super::super::builtins::PStep::Plain => Err(self.type_error("not a function")),
753 }
754 }
755 CallKind::Bound {
756 target,
757 bound_this,
758 bound_args,
759 } => {
760 let mut combined = bound_args;
761 combined.extend_from_slice(args);
762 self.call_value(&target, bound_this, &combined)
763 }
764 CallKind::NotCallable(kind_name) => Err(self.type_error(alloc::format!(
765 "not a function: {} (呼べない種別)",
766 kind_name
767 ))),
768 }
769 }
770
771 pub(crate) fn call_value_inner(&mut self, func: &Value, this: Value, args: &[Value]) -> EvalResult {
772 let obj = match func {
773 Value::Object(o) => o,
774 _ => {
776 let d = func.to_js_string().to_string();
777 return Err(self.type_error(alloc::format!("not a function: {}", d)));
778 }
779 };
780 let kind = extract_call_target(obj, self.host);
781 self.dispatch_call_kind(kind, func, this, args)
782 }
783
784 #[inline]
785 pub(crate) fn alloc_call_scope(&mut self, parent: Rc<RefCell<Scope>>, n_vars: usize) -> Rc<RefCell<Scope>> {
786 if let Some(sc) = self.scope_pool.pop() {
787 let has_with = parent.borrow().has_with;
788 {
789 let mut b = sc.borrow_mut();
790 b.vars.clear_keep_capacity();
791 b.vars.ensure_capacity(n_vars);
792 b.parent = Some(parent);
793 b.is_block = false;
794 b.is_param = false;
795 b.is_catch = false;
796 b.annex_b_skip = None;
797 b.tdz = None;
798 b.this_barrier = false;
799 b.derived_this = None;
800 b.with_obj = None;
801 b.has_with = has_with;
802 b.is_eval = false;
803 }
804 sc
805 } else {
806 Scope::child_with_capacity(parent, n_vars)
807 }
808 }
809
810 #[inline]
811 pub(crate) fn alloc_block_scope(&mut self, parent: Rc<RefCell<Scope>>) -> Rc<RefCell<Scope>> {
812 if let Some(r) = &mut self.gen_replay {
813 if r.gen_depth == self.depth {
814 let idx = r.scope_cursor;
815 r.scope_cursor += 1;
816 if let Some(sc) = r.saved_scopes.get(idx) {
817 return sc.clone();
818 }
819 let sc = Scope::block(parent);
820 r.saved_scopes.push(sc.clone());
821 return sc;
822 }
823 }
824 if let Some(sc) = self.scope_pool.pop() {
825 let has_with = parent.borrow().has_with;
826 {
827 let mut b = sc.borrow_mut();
828 b.vars.clear_keep_capacity();
829 b.parent = Some(parent);
830 b.is_block = true;
831 b.is_param = false;
832 b.is_catch = false;
833 b.annex_b_skip = None;
834 b.tdz = None;
835 b.this_barrier = false;
836 b.derived_this = None;
837 b.with_obj = None;
838 b.has_with = has_with;
839 b.is_eval = false;
840 }
841 sc
842 } else {
843 Scope::block(parent)
844 }
845 }
846
847 #[inline]
848 pub(crate) fn recycle_call_scope(&mut self, scope: Rc<RefCell<Scope>>) {
849 if Rc::strong_count(&scope) == 1 {
850 if self.scope_pool.len() < 64 {
851 let cap = scope.borrow().vars.capacity();
852 if cap <= 32 {
853 {
854 let mut b = scope.borrow_mut();
855 b.vars.clear_keep_capacity();
856 b.parent = None;
857 b.is_block = false;
858 b.is_param = false;
859 b.is_catch = false;
860 b.annex_b_skip = None;
861 b.tdz = None;
862 b.this_barrier = false;
863 b.derived_this = None;
864 b.with_obj = None;
865 b.has_with = false;
866 b.is_eval = false;
867 }
868 self.scope_pool.push(scope);
869 }
870 }
871 } else {
872 scope.borrow_mut().vars.shrink_to_fit();
874 }
875 }
876
877 #[inline]
878 pub(crate) fn recycle_block_scope(&mut self, scope: Rc<RefCell<Scope>>) {
879 if let Some(r) = &self.gen_replay {
880 if r.gen_depth == self.depth {
881 return;
882 }
883 }
884 self.recycle_call_scope(scope);
885 }
886
887 #[inline]
889 pub(crate) fn global_window(&mut self) -> Value {
890 let g = self.global.borrow();
891 if let Some((k, v)) = g.vars.entry_at(self.window_pos) {
892 if crate::os_lib::ecma::value::key_eq(k, "globalThis") {
894 return v.clone();
895 }
896 }
897 if let Some(i) = g.vars.position_of("globalThis") {
898 self.window_pos = i;
899 }
900 g.vars.get("globalThis").cloned().unwrap_or(Value::Undefined)
901 }
902
903 pub(crate) fn call_user_function(
904 &mut self,
905 fd: &FunctionData,
906 this: Value,
907 args: &[Value],
908 callee: Value,
909 ) -> EvalResult {
910 let prev_strict = self.strict;
911 self.strict = fd.body().strict;
912 let is_derived = matches!(&callee, Value::Object(fo) if is_class_ctor(fo) && fo.borrow().props.contains_key("__superclass__"));
913 let dt_cell = if is_derived && !fd.is_arrow() {
914 Some(Rc::new(RefCell::new(None)))
915 } else {
916 None
917 };
918 let pushed_dt = !fd.is_arrow();
919 if pushed_dt {
920 self.derived_this_stack.push(None);
921 }
922 let pushed_eval_ctx = fd.body().eval_ctx().is_some();
923 if let Some(ctx) = fd.body().eval_ctx() {
924 self.eval_ctx_stack.push(ctx);
925 }
926 let r = self.call_user_function_inner(fd, this, args, callee, dt_cell.clone());
927 if pushed_eval_ctx {
928 self.eval_ctx_stack.pop();
929 }
930 let derived_this = if pushed_dt {
931 self.derived_this_stack.pop().flatten()
932 } else {
933 None
934 };
935 self.strict = prev_strict;
936 if let Some(cell) = dt_cell {
937 let dt_val = cell.borrow().clone().or(derived_this);
938 return match r {
939 Ok(Value::Object(o)) => Ok(Value::Object(o)),
940 Ok(Value::Undefined) => match dt_val {
941 Some(v) => Ok(v),
942 None => Err(self.reference_error(
943 "Must call super constructor in derived class before accessing 'this' or returning from derived constructor",
944 )),
945 },
946 Ok(_) => Err(self.type_error("Derived constructors may only return object or undefined")),
947 Err(e) => Err(e),
948 };
949 }
950 match r {
951 Ok(v) if !matches!(v, Value::Object(_)) => Ok(derived_this.unwrap_or(v)),
952 other => other,
953 }
954 }
955
956 fn call_user_function_inner(
957 &mut self,
958 fd: &FunctionData,
959 this: Value,
960 args: &[Value],
961 callee: Value,
962 dt_cell: Option<Rc<RefCell<Option<Value>>>>,
963 ) -> EvalResult {
964 let this = if !fd.is_arrow() && !fd.body().strict {
967 match &this {
968 Value::Undefined | Value::Null => self.global_window(),
969 Value::Object(_) => this,
970 _ => super::super::builtins::object_ctor(
971 self,
972 Value::Undefined,
973 core::slice::from_ref(&this),
974 )?,
975 }
976 } else {
977 this
978 };
979 if fd.has_simple_unique_params() && !fd.is_generator() && !fd.is_async() {
980 let use_this = if fd.is_arrow() {
981 fd.bound_this
982 .as_ref()
983 .map(|b| (**b).clone())
984 .unwrap_or(Value::Undefined)
985 } else {
986 this
987 };
988 let stmts = fd.body().stmts();
989 let uses_args = !fd.is_arrow() && fd.body().uses_arguments(&stmts);
990 let hoisted = match fd.body().cached_var_names() {
991 Some(n) => n,
992 None => {
993 let n: Rc<Vec<Rc<str>>> = Rc::new(super::exec::var_names_of(&stmts));
994 fd.body().store_var_names(&stmts, n.clone());
995 n
996 }
997 };
998 let n_params = fd.params().len();
999 let call_scope = self.alloc_call_scope(fd.closure.clone(), n_params + hoisted.len());
1000 let res = (|| -> EvalResult {
1001 {
1002 let mut sc = call_scope.borrow_mut();
1003 sc.this_barrier = !fd.is_arrow();
1004 sc.derived_this = dt_cell.clone();
1005 for (i, p) in fd.params().iter().enumerate() {
1006 let crate::os_lib::ecma::ast::Pattern::Identifier(name) = &p.pattern else {
1007 unreachable!()
1008 };
1009 let v = args.get(i).cloned().unwrap_or(Value::Undefined);
1010 sc.vars.push_fresh_small(name.clone(), v);
1011 }
1012 if !uses_args {
1013 for n in hoisted.iter() {
1014 sc.vars.push_hoisted_missing(n, n_params, Value::Undefined);
1015 }
1016 }
1017 sc.vars.promote_if_big();
1018 }
1019 if uses_args {
1020 let arguments_obj = self.make_arguments_obj(args, callee, fd.body().strict);
1021 scope_declare(&call_scope, "arguments", Value::Object(arguments_obj));
1022 self.hoist_declarations(&stmts, &call_scope, &use_this, Some(&hoisted));
1023 } else if fd.body().has_function_decls(&stmts) {
1024 self.hoist_function_decls(&stmts, &call_scope, &use_this);
1025 }
1026 super::exec::maybe_record_annex_b_skip(&stmts, fd.params(), &call_scope);
1027 if let Some(code) = fd.body().code(&stmts) {
1028 return self.run_code(&code, &call_scope, &use_this);
1029 }
1030 match self.exec_statements_prehoisted(&stmts, &call_scope, &use_this)? {
1031 Completion::Return(v) => Ok(v),
1032 _ => Ok(Value::Undefined),
1033 }
1034 })();
1035 self.recycle_call_scope(call_scope);
1036 return res;
1037 }
1038 let n_vars = fd.params().len() + fd.body().cached_var_names().map_or(0, |n| n.len());
1040 let call_scope = self.alloc_call_scope(fd.closure.clone(), n_vars);
1041 {
1042 let mut sc = call_scope.borrow_mut();
1043 sc.this_barrier = !fd.is_arrow();
1044 sc.derived_this = dt_cell;
1045 }
1046 let res = (|| -> EvalResult {
1047 let is_simple_params = fd.params().iter().all(|p| {
1050 !p.is_rest && p.default.is_none() && matches!(p.pattern, crate::os_lib::ecma::ast::Pattern::Identifier(_))
1051 });
1052 let has_param_exprs = fd.params().iter().any(|p| p.default.is_some() || pattern_has_exprs(&p.pattern));
1053 if is_simple_params {
1054 let mut sc = call_scope.borrow_mut();
1055 for (i, p) in fd.params().iter().enumerate() {
1056 let crate::os_lib::ecma::ast::Pattern::Identifier(name) = &p.pattern else { unreachable!() };
1057 let v = args.get(i).cloned().unwrap_or(Value::Undefined);
1058 sc.vars.insert(name.clone(), v);
1059 }
1060 } else {
1061 if has_param_exprs {
1062 call_scope.borrow_mut().is_param = true;
1063 let mut pnames = Vec::new();
1064 for p in fd.params().iter() {
1065 super::exec::collect_pattern_names(&p.pattern, &mut pnames);
1066 }
1067 call_scope.borrow_mut().tdz = Some(pnames.clone().into_boxed_slice());
1068 if !fd.is_arrow() && !pnames.iter().any(|n| &**n == "arguments") {
1069 pnames.push(Rc::from("arguments"));
1070 let arguments_obj = self.make_arguments_obj(args, callee.clone(), true);
1071 scope_declare(&call_scope, "arguments", Value::Object(arguments_obj));
1072 }
1073 self.active_param_names.push(pnames);
1074 }
1075 let param_res = (|| -> Result<(), Value> {
1076 for (i, p) in fd.params().iter().enumerate() {
1077 if p.is_rest {
1078 let rest_args: Vec<Value> =
1080 args.get(i..).map(|s| s.to_vec()).unwrap_or_default();
1081 self.bind_pattern(
1082 &p.pattern,
1083 Value::Object(Obj::array(rest_args)),
1084 &call_scope,
1085 &this,
1086 )?;
1087 break;
1088 }
1089 let mut v = args.get(i).cloned().unwrap_or(Value::Undefined);
1090 if matches!(v, Value::Undefined) {
1092 if let Some(def) = &p.default {
1093 v = self.eval(def, &call_scope, &this)?;
1094 super::name_default_value(&v, def, &p.pattern);
1095 }
1096 }
1097 self.bind_pattern(&p.pattern, v, &call_scope, &this)?;
1098 }
1099 Ok(())
1100 })();
1101 if has_param_exprs {
1102 self.active_param_names.pop();
1103 let mut sc = call_scope.borrow_mut();
1104 sc.is_param = false;
1105 sc.tdz = None;
1106 }
1107 if let Err(e) = param_res {
1108 if fd.is_async() && !fd.is_generator() && !self.aborted {
1109 let pstate = Rc::new(RefCell::new(PromiseState::pending()));
1110 self.promise_reject(&pstate, e);
1111 return Ok(Value::Object(Obj::promise(pstate)));
1112 }
1113 return Err(e);
1114 }
1115 }
1116 let use_this = if fd.is_arrow() {
1117 fd.bound_this
1118 .as_ref()
1119 .map(|b| (**b).clone())
1120 .unwrap_or(Value::Undefined)
1121 } else {
1122 this
1123 };
1124 if fd.is_generator() {
1125 let gen_obj = Obj::generator(GenState {
1129 func: fd.clone(),
1130 args: args.to_vec(),
1131 this: use_this,
1132 param_vars: call_scope.borrow().vars.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
1133 sent: Vec::new(),
1134 started: false,
1135 done: false,
1136 returned: Value::Undefined,
1137 call_scope: None,
1138 done_stmts: Vec::new(),
1139 saved_scopes: Vec::new(),
1140 vm_mode: super::super::value::GEN_MODE_UNKNOWN,
1141 vm: None,
1142 executing: false,
1143 });
1144 if let Value::Object(callee_obj) = &callee {
1145 if let Some(Value::Object(gp)) = Obj::fn_prototype(callee_obj) {
1146 {
1147 let mut gpb = gp.borrow_mut();
1148 if gpb.proto.is_none() && !gpb.is_null_proto() {
1149 gpb.proto = if fd.is_async() {
1150 super::super::builtins::async_generator_proto(self)
1151 } else {
1152 super::super::builtins::generator_proto(self)
1153 };
1154 }
1155 }
1156 gen_obj.borrow_mut().proto = Some(gp);
1157 }
1158 }
1159 return Ok(Value::Object(gen_obj));
1160 }
1161 let stmts = fd.body().stmts();
1162 let body_scope_opt = if has_param_exprs {
1165 let bs = self.alloc_call_scope(call_scope.clone(), n_vars);
1166 {
1167 let ps = call_scope.borrow();
1168 let mut bsb = bs.borrow_mut();
1169 for (k, v) in ps.vars.iter() {
1170 bsb.vars.insert(k.clone(), v.clone());
1171 }
1172 }
1173 Some(bs)
1174 } else {
1175 None
1176 };
1177 let exec_scope = body_scope_opt.as_ref().unwrap_or(&call_scope);
1178 if !has_param_exprs && !fd.is_arrow() && fd.body().uses_arguments(&stmts) {
1179 let arguments_obj = self.make_arguments_obj(args, callee, fd.body().strict || !is_simple_params);
1180 scope_declare(exec_scope, "arguments", Value::Object(arguments_obj));
1181 }
1182 super::exec::maybe_record_annex_b_skip(&stmts, fd.params(), exec_scope);
1183 if fd.is_async() {
1184 let outcome = self.exec_statements(&stmts, exec_scope, &use_this);
1187 if let Some(bs) = body_scope_opt {
1188 self.recycle_call_scope(bs);
1189 }
1190 let pstate = Rc::new(RefCell::new(PromiseState::pending()));
1191 match outcome {
1192 Ok(Completion::Return(v)) => self.promise_resolve(&pstate, v),
1193 Ok(_) => self.promise_resolve(&pstate, Value::Undefined),
1194 Err(e) => {
1195 if self.aborted {
1196 return Err(e);
1197 }
1198 self.promise_reject(&pstate, e);
1199 }
1200 }
1201 return Ok(Value::Object(Obj::promise(pstate)));
1202 }
1203 let hoisted = match fd.body().cached_var_names() {
1204 Some(n) => n,
1205 None => {
1206 let n: Rc<Vec<Rc<str>>> = Rc::new(super::exec::var_names_of(&stmts));
1207 fd.body().store_var_names(&stmts, n.clone());
1208 n
1209 }
1210 };
1211 let body_res = if let Some(code) = fd.body().code(&stmts) {
1213 self.hoist_declarations(&stmts, exec_scope, &use_this, Some(&hoisted));
1214 self.run_code(&code, exec_scope, &use_this)
1215 } else {
1216 match self.exec_statements_hoisted(&stmts, exec_scope, &use_this, Some(&hoisted))? {
1217 Completion::Return(v) => Ok(v),
1218 _ => Ok(Value::Undefined),
1219 }
1220 };
1221 if let Some(bs) = body_scope_opt {
1222 self.recycle_call_scope(bs);
1223 }
1224 body_res
1225 })();
1226 self.recycle_call_scope(call_scope);
1227 res
1228 }
1229
1230 }
1233
1234pub(crate) fn describe_thrown(v: &Value, depth: u32) -> String {
1236 match v {
1237 Value::Object(o) => {
1238 if depth == 0 {
1239 return String::from("{…}");
1240 }
1241 let b = o.borrow();
1242 if let ObjKind::Array(items) = &b.kind {
1243 let parts: Vec<String> = items.iter().take(4).map(|x| describe_thrown(x, depth - 1)).collect();
1244 return alloc::format!("[{}]", parts.join(", "));
1245 }
1246 let parts: Vec<String> = b
1247 .props
1248 .iter()
1249 .take(8)
1250 .map(|(k, x)| alloc::format!("{}={}", k, describe_thrown(x, depth - 1)))
1251 .collect();
1252 alloc::format!("{{{}}}", parts.join(", "))
1253 }
1254 other => other.to_js_string().chars().take(300).collect(),
1255 }
1256}
1257
1258fn describe_callee_value(v: &Value) -> String {
1259 match v {
1260 Value::Object(_) => String::from("value"),
1261 other => other.to_js_string(),
1262 }
1263}
1264
1265pub(crate) fn is_constructor(v: &Value) -> bool {
1268 let Value::Object(o) = v else { return false };
1269 let b = o.borrow();
1270 match &b.kind {
1271 ObjKind::Function(fd) => !fd.is_arrow() && !fd.is_async() && !fd.is_generator() && !fd.body().is_method(),
1272 ObjKind::Native { name, .. } => {
1273 if b.props.contains_key("prototype") {
1274 return true;
1275 }
1276 let n: &str = name;
1277 let first = n.chars().next().unwrap_or('a');
1278 !(n.contains('.') || first.is_lowercase() || first == '[' || n.starts_with("Symbol("))
1279 }
1280 ObjKind::Bound(bd) => is_constructor(&bd.target),
1281 ObjKind::Proxy(p) => is_constructor(&Value::Object(p.target.clone())),
1282 ObjKind::Resolver { .. } => false,
1283 ObjKind::Plain | ObjKind::Array(_) | ObjKind::Iter | ObjKind::MapObj(_) | ObjKind::SetObj(_) | ObjKind::DateObj(_) | ObjKind::PromiseObj(_) | ObjKind::RegExpObj(_) | ObjKind::Generator(_) | ObjKind::GenReturn | ObjKind::Bytes(_) => false,
1284 _ => true,
1285 }
1286}
1287
1288fn pattern_has_exprs(p: &crate::os_lib::ecma::ast::Pattern) -> bool {
1290 use crate::os_lib::ecma::ast::Pattern;
1291 match p {
1292 Pattern::Identifier(_) => false,
1293 Pattern::Expr(_) => true,
1294 Pattern::Object(props) => props
1295 .iter()
1296 .any(|pr| pr.default.is_some() || pr.computed_key.is_some() || pattern_has_exprs(&pr.value)),
1297 Pattern::Array(elems) => elems
1298 .iter()
1299 .any(|e| e.default.is_some() || e.pattern.as_ref().is_some_and(pattern_has_exprs)),
1300 }
1301}