Skip to main content

blitz_script/native/
exec.rs

1use super::syntax::*;
2use super::*;
3use std::rc::{Rc, Weak};
4
5const MAX_SOURCE_BYTES: usize = 1_048_576;
6const MAX_CALL_DEPTH: usize = 256;
7const MAX_AWAIT_POLLS: usize = 1_024;
8pub(super) const MAX_ARRAY_LENGTH: usize = 65_536;
9const MAX_CALL_LABEL: usize = 96;
10
11fn append_call_label(label: &mut String, suffix: &str) {
12    if label.len() >= MAX_CALL_LABEL {
13        return;
14    }
15    let remaining = MAX_CALL_LABEL - label.len();
16    label.push_str(&suffix.chars().take(remaining).collect::<String>());
17}
18
19fn call_label(expression: &Expr) -> String {
20    match expression {
21        Expr::Ident(name) => name.chars().take(MAX_CALL_LABEL).collect(),
22        Expr::Member(object, key) => {
23            let mut label = call_label(object);
24            match key.as_ref() {
25                Expr::Literal(Literal::String(key)) => {
26                    append_call_label(&mut label, ".");
27                    append_call_label(
28                        &mut label,
29                        &String::from_utf16_lossy(&key[..key.len().min(MAX_CALL_LABEL)]),
30                    );
31                }
32                _ => append_call_label(&mut label, "[<computed>]"),
33            }
34            label
35        }
36        Expr::Chain(base, parts) => {
37            let mut label = call_label(base);
38            for part in parts {
39                match part {
40                    ChainPart::Member(Expr::Literal(Literal::String(key)), _) => {
41                        append_call_label(&mut label, ".");
42                        append_call_label(
43                            &mut label,
44                            &String::from_utf16_lossy(&key[..key.len().min(MAX_CALL_LABEL)]),
45                        );
46                    }
47                    ChainPart::Member(_, _) => append_call_label(&mut label, "[<computed>]"),
48                    ChainPart::Call(_, _) => append_call_label(&mut label, "()"),
49                }
50            }
51            label
52        }
53        Expr::Function(function) => function
54            .name
55            .as_deref()
56            .map(|name| name.chars().take(MAX_CALL_LABEL).collect())
57            .unwrap_or_else(|| "<function>".into()),
58        _ => "<expression>".into(),
59    }
60}
61
62fn class_fields(metadata: &Value) -> Vec<(String, Option<Expr>)> {
63    metadata
64        .as_object()
65        .and_then(|object| object.borrow().payload.clone())
66        .and_then(|payload| {
67            payload
68                .downcast_ref::<Vec<(String, Option<Expr>)>>()
69                .cloned()
70        })
71        .unwrap_or_default()
72}
73
74#[derive(Clone)]
75enum Flow {
76    Normal,
77    Return(Value),
78    Break,
79    Continue,
80}
81
82type ExecResult = Result<Flow>;
83
84impl<B: RuntimeBridge> Guest<B> {
85    fn error_value(&self, error: &Error) -> Value {
86        let value = error.value();
87        if error.thrown.is_none() {
88            let constructor = match error.name.as_str() {
89                "TypeError" | "RangeError" | "ReferenceError" | "SyntaxError" => &error.name,
90                _ => "Error",
91            };
92            let prototype = self.global.get(constructor).get("prototype");
93            if let Some(object) = value.as_object() {
94                object.borrow_mut().prototype = Some(prototype);
95            }
96        }
97        value
98    }
99
100    /// Parse and execute one source unit in this guest's persistent global scope.
101    pub fn evaluate(&mut self, doc: &mut BaseDocument, source: &str) -> Result<Value> {
102        let _scope = super::value::HeapScope::enter(&self.heap);
103        if self.disposed {
104            return Err(Error::new("InvalidStateError", "guest has been disposed"));
105        }
106        if source.len() > MAX_SOURCE_BYTES {
107            return Err(Error::syntax("source exceeds the execution size limit"));
108        }
109        let program = parse(source).map_err(Error::syntax)?;
110        let env = Rc::clone(&self.env);
111        self.hoist(doc, &program, &env)?;
112        if let Some((Stmt::Expr(last), prefix)) = program.split_last() {
113            match self.exec_statements(doc, prefix, &env)? {
114                Flow::Normal => return self.eval_expr(doc, last, &env),
115                Flow::Return(value) => return Ok(value),
116                Flow::Break | Flow::Continue => {
117                    return Err(Error::syntax("control statement escaped the program"));
118                }
119            }
120        }
121        match self.exec_statements(doc, &program, &env)? {
122            Flow::Return(value) => Ok(value),
123            Flow::Normal | Flow::Break | Flow::Continue => Ok(Value::Undefined),
124        }
125    }
126
127    /// Invoke a retained parsed function with its captured lexical environment.
128    pub fn call_function(
129        &mut self,
130        doc: &mut BaseDocument,
131        function: Rc<Function>,
132        this: Value,
133        args: Vec<Value>,
134        construct: bool,
135    ) -> Result<Value> {
136        if function.asynchronous && construct {
137            return Err(Error::type_error("async functions are not constructors"));
138        }
139        let asynchronous = function.asynchronous;
140        let result = if self.depth >= MAX_CALL_DEPTH {
141            Err(Error::new(
142                "RangeError",
143                "maximum guest call depth exceeded",
144            ))
145        } else {
146            self.depth += 1;
147            let result = self.call_function_inner(doc, function, this, args, construct);
148            self.depth -= 1;
149            result
150        };
151        if !asynchronous {
152            return result;
153        }
154        let promise = Value::pending_promise();
155        match result {
156            Ok(value) => self.resolve_promise(doc, &promise, value, false)?,
157            Err(error) => {
158                let reason = self.error_value(&error);
159                self.resolve_promise(doc, &promise, reason, true)?;
160            }
161        }
162        Ok(promise)
163    }
164
165    fn call_function_inner(
166        &mut self,
167        doc: &mut BaseDocument,
168        function: Rc<Function>,
169        this: Value,
170        args: Vec<Value>,
171        construct: bool,
172    ) -> Result<Value> {
173        let derived_constructor = construct
174            && function
175                .env
176                .borrow()
177                .bindings
178                .contains_key("\0derived_constructor");
179        let receiver = if derived_constructor {
180            Value::Undefined
181        } else if function.arrow && construct {
182            return Err(Error::type_error("arrow functions are not constructors"));
183        } else if function.arrow {
184            function.this.clone()
185        } else if construct {
186            let instance = Value::object("Object");
187            let prototype = Self::lookup(&function.env, "\0self")
188                .map(|constructor| constructor.get("prototype"))
189                .unwrap_or(Value::Undefined);
190            if let Some(object) = instance.as_object() {
191                if matches!(prototype, Value::Object(_)) {
192                    object.borrow_mut().prototype = Some(prototype);
193                }
194            }
195            instance
196        } else {
197            this
198        };
199
200        let env = Environment::new(Some(Rc::clone(&function.env)));
201        env.borrow_mut()
202            .bindings
203            .insert("this".into(), receiver.clone());
204        if derived_constructor {
205            env.borrow_mut()
206                .bindings
207                .insert("\0derived_constructor_call".into(), Value::Bool(true));
208        }
209        if !function.arrow {
210            let arguments = Value::object("Arguments");
211            if let Some(object) = arguments.as_object() {
212                let mut object = object.borrow_mut();
213                object.indexed = args.clone();
214                object.props.insert(
215                    "length".into(),
216                    Property {
217                        value: Value::Number(args.len() as f64),
218                        get: None,
219                        set: None,
220                        enumerable: false,
221                    },
222                );
223            }
224            env.borrow_mut()
225                .bindings
226                .insert("arguments".into(), arguments);
227        }
228        for (index, pattern) in function.params.iter().enumerate() {
229            let value = if matches!(pattern, Pattern::Rest(_)) {
230                Value::array(
231                    args.iter()
232                        .skip(index)
233                        .take(MAX_ARRAY_LENGTH)
234                        .cloned()
235                        .collect(),
236                )
237            } else {
238                args.get(index).cloned().unwrap_or(Value::Undefined)
239            };
240            self.bind_pattern(doc, pattern, value, &env)?;
241        }
242        if construct && !derived_constructor {
243            let fields = function
244                .env
245                .borrow()
246                .bindings
247                .get("\0instance_fields")
248                .map(class_fields)
249                .unwrap_or_default();
250            let field_env = Environment::new(Some(Rc::clone(&function.env)));
251            field_env
252                .borrow_mut()
253                .bindings
254                .insert("this".into(), receiver.clone());
255            for (name, initial) in fields {
256                let value = if let Some(initial) = initial {
257                    self.eval_expr(doc, &initial, &field_env)?
258                } else {
259                    Value::Undefined
260                };
261                self.set_property(doc, &receiver, &name, value)?;
262            }
263        }
264        self.hoist(doc, &function.body, &env)?;
265        let returned = match self.exec_statements(doc, &function.body, &env)? {
266            Flow::Return(value) => value,
267            Flow::Normal | Flow::Break | Flow::Continue => Value::Undefined,
268        };
269        if !construct {
270            return Ok(returned);
271        }
272        if matches!(returned, Value::Object(_)) {
273            return Ok(returned);
274        }
275        if derived_constructor {
276            let initialized = Self::lookup(&env, "this").unwrap_or(Value::Undefined);
277            if matches!(initialized, Value::Object(_)) {
278                Ok(initialized)
279            } else {
280                Err(Error::type_error(
281                    "derived constructor must call super or return an object",
282                ))
283            }
284        } else {
285            Ok(receiver)
286        }
287    }
288
289    /// Resolve a settled promise or drive real bridge/jobs work for a pending one.
290    pub fn await_value(&mut self, doc: &mut BaseDocument, value: Value) -> Result<Value> {
291        if value.kind() != "Promise" {
292            self.resume_after_await()?;
293            return Ok(value);
294        }
295        for _ in 0..MAX_AWAIT_POLLS {
296            let state = value.get("state").number_value() as i32;
297            if state == 1 {
298                self.resume_after_await()?;
299                return Ok(value.get("value"));
300            }
301            if state == 2 {
302                self.resume_after_await()?;
303                let reason = value.get("value");
304                return Err(Error::thrown(reason));
305            }
306
307            let host_jobs = self.bridge.poll(doc, None, true)?;
308            self.jobs.extend(host_jobs);
309            let did_work = self.drain_one_job(doc)?;
310            if value.get("state").number_value() != 0.0 {
311                continue;
312            }
313            if !did_work && self.bridge.pending_task_count() == 0 && self.jobs.is_empty() {
314                return Err(Error::new(
315                    "InvalidStateError",
316                    "promise is pending and no host work can resolve it",
317                ));
318            }
319            self.tick()?;
320            self.bridge.wait_for_work()?;
321        }
322        Err(Error::new(
323            "TimeoutError",
324            "promise did not settle within the bounded poll budget",
325        ))
326    }
327
328    /// Test prototype identity for parsed functions and native constructors.
329    pub fn instance_of(
330        &mut self,
331        doc: &mut BaseDocument,
332        value: &Value,
333        constructor: &Value,
334    ) -> Result<bool> {
335        if !matches!(value, Value::Object(_)) {
336            return Ok(false);
337        }
338        let is_function = constructor
339            .as_object()
340            .is_some_and(|object| object.borrow().function.is_some())
341            || super::proxy::is_callable(constructor);
342        let is_native = matches!(constructor.get("__native"), Value::String(_));
343        if !is_function && !is_native {
344            return Err(Error::type_error(
345                "right-hand side of instanceof is not callable",
346            ));
347        }
348        let target = self.get_property(doc, constructor, "prototype")?;
349        if !matches!(target, Value::Object(_)) {
350            return Err(Error::type_error(
351                "right-hand side of instanceof is not callable",
352            ));
353        }
354        let mut cursor = value
355            .as_object()
356            .and_then(|object| object.borrow().prototype.clone());
357        let mut remaining = MAX_CALL_DEPTH * 4;
358        while let Some(prototype) = cursor {
359            if prototype.same(&target) {
360                return Ok(true);
361            }
362            if remaining == 0 {
363                return Err(Error::new("RangeError", "prototype chain exceeds limit"));
364            }
365            remaining -= 1;
366            cursor = prototype
367                .as_object()
368                .and_then(|object| object.borrow().prototype.clone());
369        }
370        Ok(false)
371    }
372
373    fn lookup(env: &Env, name: &str) -> Option<Value> {
374        let (value, parent) = {
375            let scope = env.borrow();
376            (scope.bindings.get(name).cloned(), scope.parent.clone())
377        };
378        value
379            .and_then(|value| {
380                if value.kind() == "FunctionSelfRef" {
381                    value
382                        .as_object()
383                        .and_then(|object| {
384                            object
385                                .borrow()
386                                .payload
387                                .as_ref()
388                                .and_then(|payload| {
389                                    payload.downcast_ref::<Weak<std::cell::RefCell<Object>>>()
390                                })
391                                .and_then(Weak::upgrade)
392                        })
393                        .map(Value::Object)
394                } else {
395                    Some(value)
396                }
397            })
398            .or_else(|| parent.and_then(|parent| Self::lookup(&parent, name)))
399    }
400
401    fn assign(env: &Env, name: &str, value: Value) -> bool {
402        let parent = {
403            let mut scope = env.borrow_mut();
404            if scope.bindings.contains_key(name) {
405                scope.bindings.insert(name.to_owned(), value);
406                return true;
407            }
408            scope.parent.clone()
409        };
410        parent.is_some_and(|parent| Self::assign(&parent, name, value))
411    }
412
413    fn declare(&self, env: &Env, name: &str, value: Value) {
414        env.borrow_mut().bindings.insert(name.to_owned(), value);
415    }
416
417    fn hoist(&mut self, doc: &mut BaseDocument, statements: &[Stmt], env: &Env) -> Result<()> {
418        for statement in statements {
419            match statement {
420                Stmt::FunctionDecl(name, function) => {
421                    let value = self.make_function(function.clone(), Rc::clone(env));
422                    self.declare(env, name, value);
423                }
424                Stmt::Var(kind, declarations) => {
425                    if !matches!(kind, VarKind::Var) {
426                        for (pattern, _) in declarations {
427                            self.declare_pattern_names(pattern, env);
428                        }
429                    }
430                }
431                Stmt::ClassDecl(name, class) => {
432                    let value = self.eval_class(doc, class, env)?;
433                    self.declare(env, name, value);
434                }
435                _ => {}
436            }
437        }
438        self.hoist_vars(statements, env)
439    }
440
441    fn hoist_vars(&self, statements: &[Stmt], env: &Env) -> Result<()> {
442        for statement in statements {
443            match statement {
444                Stmt::Var(VarKind::Var, declarations) => {
445                    for (pattern, _) in declarations {
446                        self.declare_pattern_names(pattern, env);
447                    }
448                }
449                Stmt::Block(body) => self.hoist_vars(body, env)?,
450                Stmt::If(_, yes, no) => {
451                    self.hoist_vars(std::slice::from_ref(yes), env)?;
452                    if let Some(no) = no {
453                        self.hoist_vars(std::slice::from_ref(no), env)?;
454                    }
455                }
456                Stmt::While(_, body) | Stmt::DoWhile(body, _) => {
457                    self.hoist_vars(std::slice::from_ref(body), env)?;
458                }
459                Stmt::For { init, body, .. } => {
460                    if let Some(init) = init {
461                        self.hoist_vars(std::slice::from_ref(init), env)?;
462                    }
463                    self.hoist_vars(std::slice::from_ref(body), env)?;
464                }
465                Stmt::ForEach {
466                    pattern,
467                    kind: Some(VarKind::Var),
468                    body,
469                    ..
470                } => {
471                    self.declare_pattern_names(pattern, env);
472                    self.hoist_vars(std::slice::from_ref(body), env)?;
473                }
474                Stmt::ForEach { body, .. } => self.hoist_vars(std::slice::from_ref(body), env)?,
475                Stmt::Try {
476                    body,
477                    catch,
478                    finally,
479                } => {
480                    self.hoist_vars(std::slice::from_ref(body), env)?;
481                    if let Some((_, body)) = catch {
482                        self.hoist_vars(std::slice::from_ref(body), env)?;
483                    }
484                    if let Some(body) = finally {
485                        self.hoist_vars(std::slice::from_ref(body), env)?;
486                    }
487                }
488                Stmt::Switch(_, cases) => {
489                    for (_, body) in cases {
490                        self.hoist_vars(body, env)?;
491                    }
492                }
493                _ => {}
494            }
495        }
496        Ok(())
497    }
498
499    fn declare_pattern_names(&self, pattern: &Pattern, env: &Env) {
500        match pattern {
501            Pattern::Ident(name) => {
502                env.borrow_mut()
503                    .bindings
504                    .entry(name.clone())
505                    .or_insert(Value::Undefined);
506            }
507            Pattern::Array(items) => {
508                for item in items.iter().flatten() {
509                    self.declare_pattern_names(item, env);
510                }
511            }
512            Pattern::Object(entries) => {
513                for (_, item) in entries {
514                    self.declare_pattern_names(item, env);
515                }
516            }
517            Pattern::Rest(item) | Pattern::Default(item, _) => {
518                self.declare_pattern_names(item, env)
519            }
520        }
521    }
522
523    fn bind_pattern(
524        &mut self,
525        doc: &mut BaseDocument,
526        pattern: &Pattern,
527        value: Value,
528        env: &Env,
529    ) -> Result<()> {
530        match pattern {
531            Pattern::Ident(name) => {
532                env.borrow_mut().bindings.insert(name.clone(), value);
533            }
534            Pattern::Rest(inner) => self.bind_pattern(doc, inner, value, env)?,
535            Pattern::Default(inner, fallback) => {
536                let value = if matches!(value, Value::Undefined) {
537                    self.eval_expr(doc, fallback, env)?
538                } else {
539                    value
540                };
541                self.bind_pattern(doc, inner, value, env)?;
542            }
543            Pattern::Array(items) => {
544                let values = value.items();
545                for (cursor, item) in items.iter().enumerate() {
546                    if let Some(item) = item {
547                        if let Pattern::Rest(inner) = item {
548                            self.bind_pattern(
549                                doc,
550                                inner,
551                                Value::array(values.iter().skip(cursor).cloned().collect()),
552                                env,
553                            )?;
554                            continue;
555                        }
556                        self.bind_pattern(
557                            doc,
558                            item,
559                            values.get(cursor).cloned().unwrap_or(Value::Undefined),
560                            env,
561                        )?;
562                    }
563                }
564            }
565            Pattern::Object(entries) => {
566                let mut used = Vec::with_capacity(entries.len());
567                for (key, item) in entries {
568                    if let Pattern::Rest(inner) = item {
569                        let rest = Value::object("Object");
570                        for property in self.enumerable_keys(doc, &value)? {
571                            let property = property_key(&property);
572                            if !used.iter().any(|used_key| used_key == &property) {
573                                rest.put(&property, self.get_property(doc, &value, &property)?);
574                            }
575                        }
576                        self.bind_pattern(doc, inner, rest, env)?;
577                        continue;
578                    }
579                    used.push(key.clone());
580                    let field = self.get_property(doc, &value, key)?;
581                    self.bind_pattern(doc, item, field, env)?;
582                }
583            }
584        }
585        Ok(())
586    }
587
588    fn bind_var_pattern(
589        &mut self,
590        doc: &mut BaseDocument,
591        pattern: &Pattern,
592        value: Value,
593        env: &Env,
594    ) -> Result<()> {
595        match pattern {
596            Pattern::Ident(name) => {
597                if !Self::assign(env, name, value.clone()) {
598                    self.declare(env, name, value);
599                }
600            }
601            Pattern::Rest(inner) => self.bind_var_pattern(doc, inner, value, env)?,
602            Pattern::Default(inner, fallback) => {
603                let value = if matches!(value, Value::Undefined) {
604                    self.eval_expr(doc, fallback, env)?
605                } else {
606                    value
607                };
608                self.bind_var_pattern(doc, inner, value, env)?;
609            }
610            Pattern::Array(items) => {
611                let values = value.items();
612                for (cursor, item) in items.iter().enumerate() {
613                    if let Some(item) = item {
614                        let value = if matches!(item, Pattern::Rest(_)) {
615                            Value::array(values.iter().skip(cursor).cloned().collect())
616                        } else {
617                            values.get(cursor).cloned().unwrap_or(Value::Undefined)
618                        };
619                        self.bind_var_pattern(doc, item, value, env)?;
620                    }
621                }
622            }
623            Pattern::Object(entries) => {
624                let mut used = Vec::with_capacity(entries.len());
625                for (key, item) in entries {
626                    if matches!(item, Pattern::Rest(_)) {
627                        let rest = Value::object("Object");
628                        for property in self.enumerable_keys(doc, &value)? {
629                            let property = property_key(&property);
630                            if !used.iter().any(|used_key| used_key == &property) {
631                                rest.put(&property, self.get_property(doc, &value, &property)?);
632                            }
633                        }
634                        self.bind_var_pattern(doc, item, rest, env)?;
635                    } else {
636                        used.push(key.clone());
637                        let field = self.get_property(doc, &value, key)?;
638                        self.bind_var_pattern(doc, item, field, env)?;
639                    }
640                }
641            }
642        }
643        Ok(())
644    }
645
646    fn make_function(&self, function: FunctionExpr, env: Env) -> Value {
647        let name = function.name.clone();
648        let source_offset = function.source_offset;
649        let prototype = (!function.arrow).then(|| Value::object("Object"));
650        let closure = Environment::new(Some(env));
651        if let Some(prototype) = &prototype {
652            closure
653                .borrow_mut()
654                .bindings
655                .insert("\0function_prototype".into(), prototype.clone());
656        }
657        let lexical_this = if function.arrow {
658            Self::lookup(&closure, "this").unwrap_or(Value::Undefined)
659        } else {
660            Value::Undefined
661        };
662        let function = Rc::new(Function {
663            params: function.params,
664            body: function.body,
665            env: Rc::clone(&closure),
666            arrow: function.arrow,
667            asynchronous: function.asynchronous,
668            source_offset,
669            this: lexical_this,
670            name,
671        });
672        let object = Value::object("Function");
673        if let Some(object) = object.as_object() {
674            let mut object = object.borrow_mut();
675            object.function = Some(Rc::clone(&function));
676            object.props.insert(
677                "name".into(),
678                Property::data(Value::string(function.name.as_deref().unwrap_or(""))),
679            );
680            if let Some(prototype) = prototype {
681                object
682                    .props
683                    .insert("prototype".into(), Property::data(prototype));
684            }
685        }
686        let self_ref = Value::object("FunctionSelfRef");
687        if let (Some(reference), Some(function_object)) = (self_ref.as_object(), object.as_object())
688        {
689            let weak: Weak<std::cell::RefCell<Object>> = Rc::downgrade(&function_object);
690            reference.borrow_mut().payload = Some(Rc::new(weak));
691        }
692        if let Some(name) = &function.name {
693            if !name.is_empty() {
694                closure
695                    .borrow_mut()
696                    .bindings
697                    .insert(name.clone(), self_ref.clone());
698            }
699        }
700        closure
701            .borrow_mut()
702            .bindings
703            .insert("\0self".into(), self_ref);
704        object
705    }
706
707    fn exec_statements(
708        &mut self,
709        doc: &mut BaseDocument,
710        statements: &[Stmt],
711        env: &Env,
712    ) -> ExecResult {
713        for statement in statements {
714            self.tick()?;
715            match self.exec_stmt(doc, statement, env)? {
716                Flow::Normal => {}
717                Flow::Return(value) => return Ok(Flow::Return(value)),
718                Flow::Break => return Ok(Flow::Break),
719                Flow::Continue => return Ok(Flow::Continue),
720            }
721        }
722        Ok(Flow::Normal)
723    }
724
725    fn exec_stmt(&mut self, doc: &mut BaseDocument, stmt: &Stmt, env: &Env) -> ExecResult {
726        match stmt {
727            Stmt::Empty => Ok(Flow::Normal),
728            Stmt::Expr(expr) => {
729                self.eval_expr(doc, expr, env)?;
730                Ok(Flow::Normal)
731            }
732            Stmt::Block(body) => {
733                let block = Environment::new(Some(Rc::clone(env)));
734                self.hoist(doc, body, &block)?;
735                self.exec_statements(doc, body, &block)
736            }
737            Stmt::Var(kind, declarations) => {
738                for (pattern, init) in declarations {
739                    if matches!(kind, VarKind::Var) && init.is_none() {
740                        continue;
741                    }
742                    let value = if let Some(init) = init {
743                        self.eval_expr(doc, init, env)?
744                    } else {
745                        Value::Undefined
746                    };
747                    if matches!(kind, VarKind::Var) {
748                        self.bind_var_pattern(doc, pattern, value, env)?;
749                    } else {
750                        self.bind_pattern(doc, pattern, value, env)?;
751                    }
752                }
753                Ok(Flow::Normal)
754            }
755            Stmt::FunctionDecl(_, _) | Stmt::ClassDecl(_, _) => Ok(Flow::Normal),
756            Stmt::Return(expr) => Ok(Flow::Return(match expr {
757                Some(expr) => self.eval_expr(doc, expr, env)?,
758                None => Value::Undefined,
759            })),
760            Stmt::Throw(expr) => Err(Error::thrown(self.eval_expr(doc, expr, env)?)),
761            Stmt::If(test, yes, no) => {
762                if self.eval_expr(doc, test, env)?.truthy() {
763                    self.exec_stmt(doc, yes, env)
764                } else if let Some(no) = no {
765                    self.exec_stmt(doc, no, env)
766                } else {
767                    Ok(Flow::Normal)
768                }
769            }
770            Stmt::While(test, body) => {
771                while self.eval_expr(doc, test, env)?.truthy() {
772                    self.tick()?;
773                    match self.exec_stmt(doc, body, env)? {
774                        Flow::Normal | Flow::Continue => {}
775                        Flow::Break => break,
776                        other => return Ok(other),
777                    }
778                }
779                Ok(Flow::Normal)
780            }
781            Stmt::DoWhile(body, test) => {
782                loop {
783                    self.tick()?;
784                    match self.exec_stmt(doc, body, env)? {
785                        Flow::Normal | Flow::Continue => {}
786                        Flow::Break => break,
787                        other => return Ok(other),
788                    }
789                    if !self.eval_expr(doc, test, env)?.truthy() {
790                        break;
791                    }
792                }
793                Ok(Flow::Normal)
794            }
795            Stmt::For {
796                init,
797                test,
798                update,
799                body,
800            } => {
801                let lexical_loop = !matches!(init.as_deref(), Some(Stmt::Var(VarKind::Var, _)));
802                let loop_env = if lexical_loop {
803                    Environment::new(Some(Rc::clone(env)))
804                } else {
805                    Rc::clone(env)
806                };
807                if let Some(init) = init {
808                    let _ = self.exec_stmt(doc, init, &loop_env)?;
809                }
810                loop {
811                    if let Some(test) = test {
812                        if !self.eval_expr(doc, test, &loop_env)?.truthy() {
813                            break;
814                        }
815                    }
816                    self.tick()?;
817                    match self.exec_stmt(doc, body, &loop_env)? {
818                        Flow::Normal | Flow::Continue => {}
819                        Flow::Break => break,
820                        other => return Ok(other),
821                    }
822                    if let Some(update) = update {
823                        self.eval_expr(doc, update, &loop_env)?;
824                    }
825                }
826                Ok(Flow::Normal)
827            }
828            Stmt::ForEach {
829                pattern,
830                kind,
831                iterable,
832                body,
833                keys,
834            } => {
835                let source = self.eval_expr(doc, iterable, env)?;
836                let values = if *keys {
837                    self.enumerable_string_keys(doc, &source)?
838                } else {
839                    self.iterable_values(doc, &source)?
840                };
841                for value in values.into_iter().take(MAX_ARRAY_LENGTH) {
842                    self.tick()?;
843                    let loop_env = if matches!(kind, Some(VarKind::Let | VarKind::Const)) {
844                        Environment::new(Some(Rc::clone(env)))
845                    } else {
846                        Rc::clone(env)
847                    };
848                    if !matches!(kind, Some(VarKind::Let | VarKind::Const)) {
849                        self.bind_var_pattern(doc, pattern, value, &loop_env)?;
850                    } else {
851                        self.bind_pattern(doc, pattern, value, &loop_env)?;
852                    }
853                    match self.exec_stmt(doc, body, &loop_env)? {
854                        Flow::Normal | Flow::Continue => {}
855                        Flow::Break => break,
856                        other => return Ok(other),
857                    }
858                }
859                Ok(Flow::Normal)
860            }
861            Stmt::Try {
862                body,
863                catch,
864                finally,
865            } => {
866                let attempted = self.exec_stmt(doc, body, env);
867                let caught = match attempted {
868                    Err(error) => {
869                        if let Some((pattern, handler)) = catch {
870                            let catch_env = Environment::new(Some(Rc::clone(env)));
871                            if let Some(pattern) = pattern {
872                                let thrown = self.error_value(&error);
873                                self.bind_pattern(doc, pattern, thrown, &catch_env)?;
874                            }
875                            self.exec_stmt(doc, handler, &catch_env)
876                        } else {
877                            Err(error)
878                        }
879                    }
880                    flow => flow,
881                };
882                if let Some(finally) = finally {
883                    match self.exec_stmt(doc, finally, env)? {
884                        Flow::Normal => {}
885                        override_flow => return Ok(override_flow),
886                    }
887                }
888                caught
889            }
890            Stmt::Switch(value, cases) => {
891                let switch_env = Environment::new(Some(Rc::clone(env)));
892                let switch_statements = cases
893                    .iter()
894                    .flat_map(|(_, body)| body.iter().cloned())
895                    .collect::<Vec<_>>();
896                self.hoist(doc, &switch_statements, &switch_env)?;
897                let discriminant = self.eval_expr(doc, value, &switch_env)?;
898                let mut start = None;
899                let mut default = None;
900                for (index, (test, _)) in cases.iter().enumerate() {
901                    if let Some(test) = test {
902                        let value = self.eval_expr(doc, test, &switch_env)?;
903                        if self.strict_equal(&discriminant, &value) {
904                            start = Some(index);
905                            break;
906                        }
907                    } else {
908                        default = Some(index);
909                    }
910                }
911                if start.is_none() {
912                    start = default;
913                }
914                if let Some(start) = start {
915                    for (_, body) in cases.iter().skip(start) {
916                        match self.exec_statements(doc, body, &switch_env)? {
917                            Flow::Break => break,
918                            other @ Flow::Return(_) => return Ok(other),
919                            Flow::Continue => return Ok(Flow::Continue),
920                            Flow::Normal => {}
921                        }
922                    }
923                }
924                Ok(Flow::Normal)
925            }
926            Stmt::Break => Ok(Flow::Break),
927            Stmt::Continue => Ok(Flow::Continue),
928        }
929    }
930
931    fn eval_expr(&mut self, doc: &mut BaseDocument, expr: &Expr, env: &Env) -> Result<Value> {
932        self.tick()?;
933        match expr {
934            Expr::Literal(literal) => Ok(match literal {
935                Literal::Undefined => Value::Undefined,
936                Literal::Null => Value::Null,
937                Literal::Bool(value) => Value::Bool(*value),
938                Literal::Number(value) => Value::Number(*value),
939                Literal::String(value) => Value::String(Rc::from(value.clone())),
940            }),
941            Expr::Ident(name) => {
942                if let Some(value) =
943                    Self::lookup(env, name).or_else(|| Self::lookup(&self.env, name))
944                {
945                    Ok(value)
946                } else {
947                    let value = self.get_property(doc, &self.global.clone(), name)?;
948                    if matches!(value, Value::Undefined) {
949                        Err(Error::new(
950                            "ReferenceError",
951                            format!("{name} is not defined"),
952                        ))
953                    } else {
954                        Ok(value)
955                    }
956                }
957            }
958            Expr::This => Ok(Self::lookup(env, "this").unwrap_or(Value::Undefined)),
959            Expr::Array(items) => {
960                let mut values = Vec::with_capacity(items.len().min(MAX_ARRAY_LENGTH));
961                for item in items {
962                    match item {
963                        Some(Expr::Spread(source)) => {
964                            let source = self.eval_expr(doc, source, env)?;
965                            let spread = self.iterable_values(doc, &source)?;
966                            if values.len().saturating_add(spread.len()) > MAX_ARRAY_LENGTH {
967                                return Err(Error::new(
968                                    "RangeError",
969                                    "array literal exceeds the element limit",
970                                ));
971                            }
972                            values.extend(spread);
973                        }
974                        Some(expr) => values.push(self.eval_expr(doc, expr, env)?),
975                        None => values.push(Value::Undefined),
976                    }
977                    if values.len() > MAX_ARRAY_LENGTH {
978                        return Err(Error::new(
979                            "RangeError",
980                            "array literal exceeds the element limit",
981                        ));
982                    }
983                }
984                Ok(Value::array(values))
985            }
986            Expr::Object(entries) => {
987                let object = Value::object("Object");
988                for entry in entries {
989                    match entry {
990                        ObjectEntry::Property(key, value) => {
991                            let value = self.eval_expr(doc, value, env)?;
992                            object.put(key, value);
993                        }
994                        ObjectEntry::Computed(key, value) => {
995                            let key = property_key(&self.eval_expr(doc, key, env)?);
996                            let value = self.eval_expr(doc, value, env)?;
997                            self.set_property(doc, &object, &key, value)?;
998                        }
999                        ObjectEntry::Spread(value) => {
1000                            let spread = self.eval_expr(doc, value, env)?;
1001                            for key in self.enumerable_keys(doc, &spread)? {
1002                                let key = property_key(&key);
1003                                let value = self.get_property(doc, &spread, &key)?;
1004                                self.set_property(doc, &object, &key, value)?;
1005                            }
1006                        }
1007                        ObjectEntry::Method(key, function) => {
1008                            object.put(key, self.make_function(function.clone(), Rc::clone(env)));
1009                        }
1010                        ObjectEntry::Getter(key, function) => {
1011                            let getter = self.make_function(function.clone(), Rc::clone(env));
1012                            if let Some(obj) = object.as_object() {
1013                                let mut obj = obj.borrow_mut();
1014                                let prop = obj
1015                                    .props
1016                                    .entry(key.clone())
1017                                    .or_insert_with(|| Property::data(Value::Undefined));
1018                                prop.get = Some(getter);
1019                            }
1020                        }
1021                        ObjectEntry::Setter(key, function) => {
1022                            let setter = self.make_function(function.clone(), Rc::clone(env));
1023                            if let Some(obj) = object.as_object() {
1024                                let mut obj = obj.borrow_mut();
1025                                let prop = obj
1026                                    .props
1027                                    .entry(key.clone())
1028                                    .or_insert_with(|| Property::data(Value::Undefined));
1029                                prop.set = Some(setter);
1030                            }
1031                        }
1032                    }
1033                }
1034                Ok(object)
1035            }
1036            Expr::Function(function) => Ok(self.make_function(function.clone(), Rc::clone(env))),
1037            Expr::Class(class) => self.eval_class(doc, class, env),
1038            Expr::Unary(op, value) => {
1039                if op == "delete" {
1040                    return self.delete_target(doc, Some(value), env).map(Value::Bool);
1041                }
1042                let value = match self.eval_expr(doc, value, env) {
1043                    Err(error)
1044                        if op == "typeof"
1045                            && matches!(value.as_ref(), Expr::Ident(_))
1046                            && error.name == "ReferenceError" =>
1047                    {
1048                        Value::Undefined
1049                    }
1050                    result => result?,
1051                };
1052                match op.as_str() {
1053                    "!" => Ok(Value::Bool(!value.truthy())),
1054                    "void" => Ok(Value::Undefined),
1055                    "typeof" => Ok(Value::string(match &value {
1056                        Value::Undefined => "undefined",
1057                        Value::Null => "object",
1058                        Value::Bool(_) => "boolean",
1059                        Value::Number(_) => "number",
1060                        Value::String(_) => "string",
1061                        Value::Object(_) if value.kind() == "Symbol" => "symbol",
1062                        Value::Object(_) if super::proxy::is_callable(&value) => "function",
1063                        _ => "object",
1064                    })),
1065                    "+" => Ok(Value::Number(to_number(&value))),
1066                    "-" => Ok(Value::Number(-to_number(&value))),
1067                    "~" => Ok(Value::Number((!(to_number(&value) as i32)) as f64)),
1068                    _ => Err(Error::syntax(format!("unsupported unary operator {op}"))),
1069                }
1070            }
1071            Expr::Binary(op, left, right) => {
1072                let left = self.eval_expr(doc, left, env)?;
1073                if op == "&&" && !left.truthy() {
1074                    return Ok(left);
1075                }
1076                if op == "||" && left.truthy() {
1077                    return Ok(left);
1078                }
1079                if op == "??" && !matches!(left, Value::Null | Value::Undefined) {
1080                    return Ok(left);
1081                }
1082                let right = self.eval_expr(doc, right, env)?;
1083                self.binary(doc, op, left, right)
1084            }
1085            Expr::Conditional(test, yes, no) => {
1086                if self.eval_expr(doc, test, env)?.truthy() {
1087                    self.eval_expr(doc, yes, env)
1088                } else {
1089                    self.eval_expr(doc, no, env)
1090                }
1091            }
1092            Expr::Assign(op, target, rhs) => {
1093                if op == "=" {
1094                    let value = self.eval_expr(doc, rhs, env)?;
1095                    self.assign_target(doc, target, env, value.clone())?;
1096                    return Ok(value);
1097                }
1098                let current = self.eval_expr(doc, target, env)?;
1099                if op == "&&=" && !current.truthy()
1100                    || op == "||=" && current.truthy()
1101                    || op == "??=" && !matches!(current, Value::Null | Value::Undefined)
1102                {
1103                    return Ok(current);
1104                }
1105                let value = self.eval_expr(doc, rhs, env)?;
1106                let result = self.binary(doc, op.trim_end_matches('='), current, value)?;
1107                self.assign_target(doc, target, env, result.clone())?;
1108                Ok(result)
1109            }
1110            Expr::Update(op, target, prefix) => {
1111                let old = self.eval_expr(doc, target, env)?;
1112                let delta = if op == "++" {
1113                    1.0
1114                } else if op == "--" {
1115                    -1.0
1116                } else {
1117                    return Err(Error::syntax("invalid update operator"));
1118                };
1119                let next = Value::Number(to_number(&old) + delta);
1120                self.assign_target(doc, target, env, next.clone())?;
1121                Ok(if *prefix { next } else { old })
1122            }
1123            Expr::Member(target, key) => {
1124                let object = self.eval_expr(doc, target, env)?;
1125                let key = property_key(&self.eval_expr(doc, key, env)?);
1126                let mut label = call_label(target);
1127                append_call_label(&mut label, ".");
1128                append_call_label(&mut label, &key);
1129                self.get_property(doc, &object, &key).map_err(|mut error| {
1130                    error.stack.insert(0, format!("read {label}"));
1131                    error
1132                })
1133            }
1134            Expr::Call(callee, arguments) => {
1135                if matches!(callee.as_ref(),Expr::Ident(name) if name == "super") {
1136                    let parent = Self::lookup(env, "super")
1137                        .ok_or_else(|| Error::syntax("super has no parent constructor"))?;
1138                    if !env
1139                        .borrow()
1140                        .bindings
1141                        .get("\0derived_constructor_call")
1142                        .is_some_and(Value::truthy)
1143                    {
1144                        return Err(Error::syntax(
1145                            "super() is only valid in a derived constructor",
1146                        ));
1147                    }
1148                    if env.borrow().bindings.contains_key("\0super_called") {
1149                        return Err(Error::type_error(
1150                            "super constructor may only be called once",
1151                        ));
1152                    }
1153                    let args = self.eval_arguments(doc, arguments, env)?;
1154                    let instance = self.call(doc, parent, Value::Undefined, args, true)?;
1155                    if let Some(object) = instance.as_object() {
1156                        if let Some(prototype) = Self::lookup(env, "\0function_prototype") {
1157                            object.borrow_mut().prototype = Some(prototype);
1158                        }
1159                    } else {
1160                        return Err(Error::type_error(
1161                            "super constructor did not return an object",
1162                        ));
1163                    }
1164                    Self::assign(env, "this", instance.clone());
1165                    env.borrow_mut()
1166                        .bindings
1167                        .insert("\0super_called".into(), Value::Bool(true));
1168                    let fields = Self::lookup(env, "\0instance_fields")
1169                        .map(|metadata| class_fields(&metadata))
1170                        .unwrap_or_default();
1171                    let field_parent = env
1172                        .borrow()
1173                        .parent
1174                        .clone()
1175                        .unwrap_or_else(|| Rc::clone(env));
1176                    let field_env = Environment::new(Some(field_parent));
1177                    field_env
1178                        .borrow_mut()
1179                        .bindings
1180                        .insert("this".into(), instance.clone());
1181                    for (name, initial) in fields {
1182                        let value = if let Some(initial) = initial {
1183                            self.eval_expr(doc, &initial, &field_env)?
1184                        } else {
1185                            Value::Undefined
1186                        };
1187                        self.set_property(doc, &instance, &name, value)?;
1188                    }
1189                    return Ok(instance);
1190                }
1191                let (function, receiver, label) = match callee.as_ref() {
1192                    Expr::Member(object, key) => {
1193                        let receiver = self.eval_expr(doc, object, env)?;
1194                        let key = property_key(&self.eval_expr(doc, key, env)?);
1195                        let function = self.get_property(doc, &receiver, &key)?;
1196                        let mut label = call_label(object);
1197                        append_call_label(&mut label, ".");
1198                        append_call_label(&mut label, &key);
1199                        (function, receiver, label)
1200                    }
1201                    _ => (
1202                        self.eval_expr(doc, callee, env)?,
1203                        Value::Undefined,
1204                        call_label(callee),
1205                    ),
1206                };
1207                let args = self.eval_arguments(doc, arguments, env)?;
1208                self.call(doc, function, receiver, args, false)
1209                    .map_err(|mut error| {
1210                        error.stack.insert(0, format!("call {label}"));
1211                        error
1212                    })
1213            }
1214            Expr::New(callee, arguments) => {
1215                let constructor = self.eval_expr(doc, callee, env)?;
1216                let args = self.eval_arguments(doc, arguments, env)?;
1217                self.call(doc, constructor, Value::Undefined, args, true)
1218            }
1219            Expr::Sequence(expressions) => {
1220                let mut value = Value::Undefined;
1221                for expression in expressions {
1222                    value = self.eval_expr(doc, expression, env)?;
1223                }
1224                Ok(value)
1225            }
1226            Expr::Await(value) => {
1227                let value = self.eval_expr(doc, value, env)?;
1228                self.await_value(doc, value)
1229            }
1230            Expr::Spread(value) => self.eval_expr(doc, value, env),
1231            Expr::Chain(base, parts) => {
1232                let mut value = self.eval_expr(doc, base, env)?;
1233                let mut receiver = Value::Undefined;
1234                let mut label = call_label(base);
1235                for part in parts {
1236                    self.tick()?;
1237                    match part {
1238                        ChainPart::Member(key, optional) => {
1239                            if *optional && matches!(value, Value::Null | Value::Undefined) {
1240                                return Ok(Value::Undefined);
1241                            }
1242                            let key = property_key(&self.eval_expr(doc, key, env)?);
1243                            receiver = value;
1244                            let mut read_label = label.clone();
1245                            append_call_label(&mut read_label, ".");
1246                            append_call_label(&mut read_label, &key);
1247                            value =
1248                                self.get_property(doc, &receiver, &key)
1249                                    .map_err(|mut error| {
1250                                        error.stack.insert(0, format!("read {read_label}"));
1251                                        error
1252                                    })?;
1253                            append_call_label(&mut label, ".");
1254                            append_call_label(&mut label, &key);
1255                        }
1256                        ChainPart::Call(arguments, optional) => {
1257                            if *optional && matches!(value, Value::Null | Value::Undefined) {
1258                                return Ok(Value::Undefined);
1259                            }
1260                            let arguments = self.eval_arguments(doc, arguments, env)?;
1261                            value = self.call(doc, value, receiver, arguments, false).map_err(
1262                                |mut error| {
1263                                    error.stack.insert(0, format!("call {label}"));
1264                                    error
1265                                },
1266                            )?;
1267                            append_call_label(&mut label, "()");
1268                            receiver = Value::Undefined;
1269                        }
1270                    }
1271                }
1272                Ok(value)
1273            }
1274            Expr::Template(parts) => {
1275                let mut text = String::new();
1276                for part in parts {
1277                    match part {
1278                        TemplatePart::Text(units) => {
1279                            text.push_str(&String::from_utf16_lossy(units))
1280                        }
1281                        TemplatePart::Expression(expr) => {
1282                            text.push_str(&self.eval_expr(doc, expr, env)?.text())
1283                        }
1284                    }
1285                }
1286                Ok(Value::string(text))
1287            }
1288        }
1289    }
1290
1291    fn eval_arguments(
1292        &mut self,
1293        doc: &mut BaseDocument,
1294        args: &[Expr],
1295        env: &Env,
1296    ) -> Result<Vec<Value>> {
1297        let mut values = Vec::new();
1298        for arg in args {
1299            if let Expr::Spread(expr) = arg {
1300                let value = self.eval_expr(doc, expr, env)?;
1301                values.extend(self.iterable_values(doc, &value)?);
1302            } else {
1303                values.push(self.eval_expr(doc, arg, env)?);
1304            }
1305            if values.len() > MAX_ARRAY_LENGTH {
1306                return Err(Error::new("RangeError", "argument list exceeds limit"));
1307            }
1308        }
1309        Ok(values)
1310    }
1311
1312    fn eval_class(
1313        &mut self,
1314        doc: &mut BaseDocument,
1315        class: &ClassExpr,
1316        env: &Env,
1317    ) -> Result<Value> {
1318        let env = Environment::new(Some(Rc::clone(env)));
1319        let parent_constructor = if let Some(parent) = &class.extends {
1320            let parent = self.eval_expr(doc, parent, &env)?;
1321            env.borrow_mut().bindings.insert("super".into(), parent);
1322            Some(Self::lookup(&env, "super").unwrap_or(Value::Undefined))
1323        } else {
1324            None
1325        };
1326        let derived = parent_constructor.is_some();
1327        let constructor = class
1328            .methods
1329            .iter()
1330            .find(|method| method.name == "constructor" && !method.is_static);
1331        let has_explicit_constructor = constructor.is_some();
1332        let mut constructor =
1333            constructor
1334                .map(|method| method.function.clone())
1335                .unwrap_or(FunctionExpr {
1336                    params: Vec::new(),
1337                    body: Vec::new(),
1338                    arrow: false,
1339                    asynchronous: false,
1340                    name: class.name.clone(),
1341                    source_offset: None,
1342                });
1343        let fields = class
1344            .fields
1345            .iter()
1346            .filter(|(_, _, is_static)| !*is_static)
1347            .map(|(name, initial, _)| (name.clone(), initial.clone()))
1348            .collect::<Vec<_>>();
1349        if derived {
1350            if !has_explicit_constructor {
1351                constructor.body.push(Stmt::Expr(Expr::Call(
1352                    Box::new(Expr::Ident("super".into())),
1353                    vec![Expr::Spread(Box::new(Expr::Ident("arguments".into())))],
1354                )));
1355            }
1356        }
1357        let function = self.make_function(constructor, Rc::clone(&env));
1358        let field_metadata = Value::object("ClassFieldMetadata");
1359        if let Some(object) = field_metadata.as_object() {
1360            object.borrow_mut().payload = Some(Rc::new(fields));
1361        }
1362        if let Some(function_data) = function
1363            .as_object()
1364            .and_then(|object| object.borrow().function.clone())
1365        {
1366            function_data
1367                .env
1368                .borrow_mut()
1369                .bindings
1370                .insert("\0instance_fields".into(), field_metadata);
1371            if derived {
1372                function_data
1373                    .env
1374                    .borrow_mut()
1375                    .bindings
1376                    .insert("\0derived_constructor".into(), Value::Bool(true));
1377            }
1378        }
1379        if let Some(name) = &class.name {
1380            env.borrow_mut()
1381                .bindings
1382                .insert(name.clone(), function.clone());
1383        }
1384        let prototype = Value::object("Object");
1385        if let Some(parent) = &parent_constructor {
1386            let parent_proto = self.get_property(doc, parent, "prototype")?;
1387            if let Some(proto) = prototype.as_object() {
1388                proto.borrow_mut().prototype = Some(parent_proto);
1389            }
1390            if let Some(function_object) = function.as_object() {
1391                function_object.borrow_mut().prototype = Some(parent.clone());
1392            }
1393        }
1394        for method in &class.methods {
1395            if method.name == "constructor" {
1396                continue;
1397            }
1398            let value = self.make_function(method.function.clone(), Rc::clone(&env));
1399            let target = if method.is_static {
1400                &function
1401            } else {
1402                &prototype
1403            };
1404            if method.getter || method.setter {
1405                if let Some(object) = target.as_object() {
1406                    let mut object = object.borrow_mut();
1407                    let property = object
1408                        .props
1409                        .entry(method.name.clone())
1410                        .or_insert_with(|| Property::data(Value::Undefined));
1411                    if method.getter {
1412                        property.get = Some(value);
1413                    } else {
1414                        property.set = Some(value);
1415                    }
1416                }
1417            } else {
1418                target.put(&method.name, value);
1419            }
1420        }
1421        function.put("prototype", prototype.clone());
1422        if let Some(function_data) = function
1423            .as_object()
1424            .and_then(|object| object.borrow().function.clone())
1425        {
1426            function_data
1427                .env
1428                .borrow_mut()
1429                .bindings
1430                .insert("\0function_prototype".into(), prototype);
1431        }
1432        for (name, initial, is_static) in &class.fields {
1433            if *is_static {
1434                let value = if let Some(initial) = initial {
1435                    self.eval_expr(doc, initial, &env)?
1436                } else {
1437                    Value::Undefined
1438                };
1439                function.put(name, value);
1440            }
1441        }
1442        if let Some(name) = &class.name {
1443            function.put("name", Value::string(name));
1444        }
1445        Ok(function)
1446    }
1447
1448    fn binary(
1449        &mut self,
1450        doc: &mut BaseDocument,
1451        op: &str,
1452        left: Value,
1453        right: Value,
1454    ) -> Result<Value> {
1455        let ln = to_number(&left);
1456        let rn = to_number(&right);
1457        let order = match (&left, &right) {
1458            (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
1459            _ => ln.partial_cmp(&rn),
1460        };
1461        Ok(match op {
1462            "+" => {
1463                if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
1464                    Value::string(format!("{}{}", left.text(), right.text()))
1465                } else {
1466                    Value::Number(ln + rn)
1467                }
1468            }
1469            "-" => Value::Number(ln - rn),
1470            "*" => Value::Number(ln * rn),
1471            "/" => Value::Number(ln / rn),
1472            "%" => Value::Number(ln % rn),
1473            "**" => Value::Number(ln.powf(rn)),
1474            "===" => Value::Bool(self.strict_equal(&left, &right)),
1475            "!==" => Value::Bool(!self.strict_equal(&left, &right)),
1476            "==" => Value::Bool(self.loose_equal(&left, &right)),
1477            "!=" => Value::Bool(!self.loose_equal(&left, &right)),
1478            "<" => Value::Bool(order == Some(std::cmp::Ordering::Less)),
1479            ">" => Value::Bool(order == Some(std::cmp::Ordering::Greater)),
1480            "<=" => Value::Bool(matches!(
1481                order,
1482                Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal)
1483            )),
1484            ">=" => Value::Bool(matches!(
1485                order,
1486                Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal)
1487            )),
1488            "&&" | "||" | "??" => right,
1489            "|" => Value::Number(((ln as i32) | (rn as i32)) as f64),
1490            "&" => Value::Number(((ln as i32) & (rn as i32)) as f64),
1491            "^" => Value::Number(((ln as i32) ^ (rn as i32)) as f64),
1492            "<<" => Value::Number(((ln as i32) << ((rn as u32) & 31)) as f64),
1493            ">>" => Value::Number(((ln as i32) >> ((rn as u32) & 31)) as f64),
1494            ">>>" => Value::Number(((ln as u32) >> ((rn as u32) & 31)) as f64),
1495            "in" => {
1496                if !matches!(&right, Value::Object(_)) {
1497                    return Err(Error::type_error("right operand of in is not an object"));
1498                }
1499                Value::Bool(self.has_property(doc, &right, &property_key(&left))?)
1500            }
1501            "instanceof" => Value::Bool(self.instance_of(doc, &left, &right)?),
1502            _ => return Err(Error::syntax(format!("unsupported binary operator {op}"))),
1503        })
1504    }
1505
1506    fn strict_equal(&self, left: &Value, right: &Value) -> bool {
1507        match (left, right) {
1508            (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
1509            (Value::Bool(a), Value::Bool(b)) => a == b,
1510            (Value::Number(a), Value::Number(b)) => a == b,
1511            (Value::String(a), Value::String(b)) => a == b,
1512            (Value::Object(_), Value::Object(_)) => left.same(right),
1513            _ => false,
1514        }
1515    }
1516
1517    fn loose_equal(&self, left: &Value, right: &Value) -> bool {
1518        if self.strict_equal(left, right) {
1519            return true;
1520        }
1521        match (left, right) {
1522            (Value::Null, Value::Undefined) | (Value::Undefined, Value::Null) => true,
1523            (Value::Number(_), Value::String(_)) | (Value::String(_), Value::Number(_)) => {
1524                to_number(left) == to_number(right)
1525            }
1526            (Value::Bool(_), _) => to_number(left) == to_number(right),
1527            (_, Value::Bool(_)) => to_number(left) == to_number(right),
1528            (Value::Object(_), Value::String(_) | Value::Number(_)) => {
1529                self.loose_equal(&Value::string(left.text()), right)
1530            }
1531            (Value::String(_) | Value::Number(_), Value::Object(_)) => {
1532                self.loose_equal(left, &Value::string(right.text()))
1533            }
1534            _ => false,
1535        }
1536    }
1537
1538    fn assign_target(
1539        &mut self,
1540        doc: &mut BaseDocument,
1541        target: &Expr,
1542        env: &Env,
1543        value: Value,
1544    ) -> Result<()> {
1545        match target {
1546            Expr::Ident(name) => {
1547                let global_binding = self.env.borrow().bindings.contains_key(name);
1548                let unbound = !Self::assign(env, name, value.clone())
1549                    && !Self::assign(&self.env, name, value.clone());
1550                if unbound || global_binding {
1551                    self.global.put(name, value);
1552                }
1553                Ok(())
1554            }
1555            Expr::Member(object, key) => {
1556                let object = self.eval_expr(doc, object, env)?;
1557                let key = property_key(&self.eval_expr(doc, key, env)?);
1558                self.set_property(doc, &object, &key, value)
1559            }
1560            _ => Err(Error::syntax("invalid assignment target")),
1561        }
1562    }
1563
1564    fn delete_target(
1565        &mut self,
1566        doc: &mut BaseDocument,
1567        target: Option<&Expr>,
1568        env: &Env,
1569    ) -> Result<bool> {
1570        let Some(target) = target else {
1571            return Ok(false);
1572        };
1573        if let Expr::Member(object, key) = target {
1574            let object = self.eval_expr(doc, object, env)?;
1575            let key = property_key(&self.eval_expr(doc, key, env)?);
1576            if object.kind() == "Proxy" {
1577                return Ok(self.proxy_delete(doc, &object, &key)?.unwrap_or(false));
1578            }
1579            if let Some(object) = object.as_object() {
1580                let mut object = object.borrow_mut();
1581                if object.props.remove(&key).is_some() {
1582                    return Ok(true);
1583                }
1584                if let Some(index) = object.binary_index(&key) {
1585                    return Ok(index >= object.indexed_len());
1586                }
1587                if let Ok(index) = key.parse::<usize>() {
1588                    if let Some(value) = object.indexed.get_mut(index) {
1589                        *value = Value::Undefined;
1590                        return Ok(true);
1591                    }
1592                }
1593                return Ok(false);
1594            }
1595        }
1596        Ok(false)
1597    }
1598
1599    fn enumerable_keys(&mut self, doc: &mut BaseDocument, value: &Value) -> Result<Vec<Value>> {
1600        if value.as_object().is_some() {
1601            let mut keys = Vec::new();
1602            for key in self.own_property_names(doc, value)? {
1603                if self
1604                    .ordinary_descriptor(doc, value, &key)?
1605                    .get("enumerable")
1606                    .truthy()
1607                {
1608                    keys.push(property_key_value(&self.global, &key));
1609                }
1610            }
1611            return Ok(keys);
1612        }
1613        if let Value::String(units) = value {
1614            return Ok((0..units.len())
1615                .map(|index| Value::string(index.to_string()))
1616                .collect());
1617        }
1618        let _ = doc;
1619        Ok(Vec::new())
1620    }
1621
1622    fn enumerable_string_keys(
1623        &mut self,
1624        doc: &mut BaseDocument,
1625        value: &Value,
1626    ) -> Result<Vec<Value>> {
1627        Ok(self
1628            .enumerable_keys(doc, value)?
1629            .into_iter()
1630            .filter(|key| key.kind() != "Symbol")
1631            .collect())
1632    }
1633
1634    pub(super) fn iterable_values(
1635        &mut self,
1636        doc: &mut BaseDocument,
1637        value: &Value,
1638    ) -> Result<Vec<Value>> {
1639        if matches!(value, Value::Object(_)) {
1640            let iterator = self.get_property(doc, value, "@@iterator")?;
1641            if !matches!(iterator, Value::Undefined) {
1642                return self.collect_iterator(doc, value, iterator);
1643            }
1644        }
1645        let items = value.items();
1646        if !items.is_empty() || value.kind() == "Array" || value.kind() == "NodeList" {
1647            return Ok(items.into_iter().take(MAX_ARRAY_LENGTH).collect());
1648        }
1649        if let Value::String(units) = value {
1650            return Ok(String::from_utf16_lossy(units)
1651                .chars()
1652                .map(|c| Value::string(c.to_string()))
1653                .collect());
1654        }
1655        Err(Error::type_error("value is not iterable"))
1656    }
1657
1658    pub(super) fn collect_iterator(
1659        &mut self,
1660        doc: &mut BaseDocument,
1661        value: &Value,
1662        method: Value,
1663    ) -> Result<Vec<Value>> {
1664        let iterator = self.call(doc, method, value.clone(), Vec::new(), false)?;
1665        let mut out = Vec::new();
1666        for _ in 0..MAX_ARRAY_LENGTH {
1667            let next = self.get_property(doc, &iterator, "next")?;
1668            let step = self.call(doc, next, iterator.clone(), Vec::new(), false)?;
1669            if self.get_property(doc, &step, "done")?.truthy() {
1670                return Ok(out);
1671            }
1672            out.push(self.get_property(doc, &step, "value")?);
1673        }
1674        Err(Error::new("RangeError", "iterator exceeded element limit"))
1675    }
1676
1677    fn drain_one_job(&mut self, doc: &mut BaseDocument) -> Result<bool> {
1678        if let Some(job) = self.jobs.pop_front() {
1679            let callable = job.callback.clone();
1680            self.call(doc, callable, job.this, job.args, false)?;
1681            self.tick()?;
1682            return Ok(true);
1683        }
1684        let host_jobs = self.bridge.poll(doc, None, true)?;
1685        self.jobs.extend(host_jobs);
1686        if let Some(job) = self.jobs.pop_front() {
1687            self.call(doc, job.callback, job.this, job.args, false)?;
1688            self.tick()?;
1689            return Ok(true);
1690        }
1691        Ok(false)
1692    }
1693}
1694
1695fn to_number(value: &Value) -> f64 {
1696    match value {
1697        Value::Undefined => f64::NAN,
1698        Value::Null => 0.0,
1699        Value::Bool(value) => {
1700            if *value {
1701                1.0
1702            } else {
1703                0.0
1704            }
1705        }
1706        Value::Number(value) => *value,
1707        Value::String(value) => String::from_utf16_lossy(value)
1708            .trim()
1709            .parse()
1710            .unwrap_or_else(|_| {
1711                if String::from_utf16_lossy(value).trim().is_empty() {
1712                    0.0
1713                } else {
1714                    f64::NAN
1715                }
1716            }),
1717        Value::Object(_) => value.text().parse().unwrap_or(f64::NAN),
1718    }
1719}
1720
1721pub(super) fn property_key(value: &Value) -> String {
1722    if value.kind() == "Symbol" {
1723        if let Some(name) = value.as_object().and_then(|object| {
1724            object
1725                .borrow()
1726                .payload
1727                .as_ref()
1728                .and_then(|payload| payload.downcast_ref::<String>().cloned())
1729        }) {
1730            if name == "Symbol.iterator" {
1731                return "@@iterator".into();
1732            }
1733            return format!("@@{name}");
1734        }
1735    }
1736    value.text()
1737}
1738
1739pub(super) fn property_key_value(global: &Value, key: &str) -> Value {
1740    let symbol = global.get("\0symbol_keys").get(key);
1741    if symbol.kind() == "Symbol" {
1742        symbol
1743    } else {
1744        Value::string(key)
1745    }
1746}
1747
1748pub(super) fn is_symbol_property_key(global: &Value, key: &str) -> bool {
1749    global.get("\0symbol_keys").get(key).kind() == "Symbol"
1750}