1use std::any::Any;
2use std::cell::RefCell;
3use std::collections::{BTreeMap, BTreeSet};
4use std::fmt;
5use std::rc::Rc;
6
7use super::syntax::{Pattern, Stmt};
8use blitz_dom::NodeId;
9
10pub type Result<T, E = Error> = std::result::Result<T, E>;
11pub type Env = Rc<RefCell<Environment>>;
12
13#[derive(Clone)]
14pub struct Error {
15 pub name: String,
16 pub message: String,
17 pub thrown: Option<Value>,
18 pub stack: Vec<String>,
19}
20impl Error {
21 pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
22 Self {
23 name: name.into(),
24 message: message.into(),
25 thrown: None,
26 stack: Vec::new(),
27 }
28 }
29 pub fn type_error(message: impl Into<String>) -> Self {
30 Self::new("TypeError", message)
31 }
32 pub fn syntax(message: impl Into<String>) -> Self {
33 Self::new("SyntaxError", message)
34 }
35 pub fn thrown(value: Value) -> Self {
36 let stack = value
37 .get("\0error_stack")
38 .items()
39 .iter()
40 .take(64)
41 .map(Value::text)
42 .collect();
43 Self {
44 name: value.get("name").text(),
45 message: value.get("message").text(),
46 thrown: Some(value),
47 stack,
48 }
49 }
50 pub fn value(&self) -> Value {
51 let value = self
52 .thrown
53 .clone()
54 .unwrap_or_else(|| Value::error(&self.name, &self.message));
55 value.put_hidden(
56 "\0error_stack",
57 Value::array(self.stack.iter().map(Value::string).collect()),
58 );
59 value
60 }
61}
62impl fmt::Debug for Error {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "{}: {}", self.name, self.message)?;
65 for frame in &self.stack {
66 write!(f, "\n at {frame}")?;
67 }
68 let mut seen = Vec::new();
69 let mut cause = self.thrown.as_ref().map(|value| value.get("cause"));
70 while let Some(value) = cause {
71 if matches!(value, Value::Undefined)
72 || seen.len() >= 16
73 || seen.iter().any(|prior: &Value| prior.same(&value))
74 {
75 break;
76 }
77 write!(
78 f,
79 "\nCaused by: {}: {}",
80 value.get("name").text(),
81 value.get("message").text()
82 )?;
83 for frame in value.get("\0error_stack").items().iter().take(64) {
84 write!(f, "\n at {}", frame.text())?;
85 }
86 cause = Some(value.get("cause"));
87 seen.push(value);
88 }
89 Ok(())
90 }
91}
92impl fmt::Display for Error {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 fmt::Debug::fmt(self, f)
95 }
96}
97impl std::error::Error for Error {}
98
99#[derive(Clone, Default)]
100pub enum Value {
101 #[default]
102 Undefined,
103 Null,
104 Bool(bool),
105 Number(f64),
106 String(Rc<[u16]>),
107 Object(Rc<RefCell<Object>>),
108}
109impl fmt::Debug for Value {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 match self {
112 Self::Object(object) => write!(
113 f,
114 "[{}]",
115 object
116 .try_borrow()
117 .map_or_else(|_| String::from("borrowed"), |o| o.kind.clone())
118 ),
119 _ => write!(f, "{}", self.text()),
120 }
121 }
122}
123#[derive(Clone, Debug)]
124pub struct Property {
125 pub value: Value,
126 pub get: Option<Value>,
127 pub set: Option<Value>,
128 pub enumerable: bool,
129}
130impl Property {
131 pub fn data(value: Value) -> Self {
132 Self {
133 value,
134 get: None,
135 set: None,
136 enumerable: true,
137 }
138 }
139}
140pub struct Object {
141 pub kind: String,
142 pub native: Option<String>,
143 pub realm: Option<u64>,
144 pub props: BTreeMap<String, Property>,
145 pub indexed: Vec<Value>,
146 pub prototype: Option<Value>,
147 pub function: Option<Rc<Function>>,
148 pub payload: Option<Rc<dyn Any>>,
149 pub frozen: bool,
150}
151impl Object {
152 pub fn new(kind: impl Into<String>) -> Self {
153 Self {
154 kind: kind.into(),
155 native: None,
156 realm: None,
157 props: BTreeMap::new(),
158 indexed: Vec::new(),
159 prototype: None,
160 function: None,
161 payload: None,
162 frozen: false,
163 }
164 }
165}
166#[derive(Clone)]
167pub struct Function {
168 pub params: Vec<Pattern>,
169 pub body: Vec<Stmt>,
170 pub env: Env,
171 pub arrow: bool,
172 pub asynchronous: bool,
173 pub source_offset: Option<usize>,
174 pub this: Value,
175 pub name: Option<String>,
176}
177pub struct Environment {
178 pub bindings: BTreeMap<String, Value>,
179 pub parent: Option<Env>,
180}
181impl Environment {
182 pub fn new(parent: Option<Env>) -> Env {
183 let environment = Rc::new(RefCell::new(Self {
184 bindings: BTreeMap::new(),
185 parent,
186 }));
187 track_environment(&environment);
188 environment
189 }
190}
191impl Value {
192 pub fn string(text: impl AsRef<str>) -> Self {
193 Self::String(text.as_ref().encode_utf16().collect::<Vec<_>>().into())
194 }
195 pub fn object(kind: impl Into<String>) -> Self {
196 let object = Rc::new(RefCell::new(Object::new(kind)));
197 track_object(&object);
198 Self::Object(object)
199 }
200 pub fn number(number: impl Into<f64>) -> Self {
201 Self::Number(number.into())
202 }
203 pub fn array(items: Vec<Value>) -> Self {
204 let value = Self::object("Array");
205 if let Self::Object(object) = &value {
206 object.borrow_mut().indexed = items;
207 }
208 value
209 }
210 pub fn native(name: impl Into<String>) -> Self {
211 let value = Self::object("Native");
212 if let Some(object) = value.as_object() {
213 object.borrow_mut().native = Some(name.into());
214 }
215 value
216 }
217 pub fn promise(result: Result<Value>) -> Self {
218 let promise = Self::pending_promise();
219 let (state, value) = match result {
220 Ok(value) => (1.0, value),
221 Err(error) => (2.0, error.value()),
222 };
223 promise.put_hidden("state", Self::Number(state));
224 promise.put_hidden("value", value);
225 promise
226 }
227 pub fn pending_promise() -> Self {
228 let value = Self::object("Promise");
229 value.put_hidden("state", Self::Number(0.0));
230 value.put_hidden("value", Self::Undefined);
231 value
232 }
233 pub fn error(name: impl AsRef<str>, message: impl AsRef<str>) -> Self {
234 let value = Self::object("Error");
235 value.put("name", Self::string(name));
236 value.put("message", Self::string(message));
237 value
238 }
239 pub fn as_object(&self) -> Option<Rc<RefCell<Object>>> {
240 if let Self::Object(o) = self {
241 Some(Rc::clone(o))
242 } else {
243 None
244 }
245 }
246 pub fn kind(&self) -> String {
247 match self {
248 Self::Undefined => "Undefined".into(),
249 Self::Null => "Null".into(),
250 Self::Bool(_) => "Boolean".into(),
251 Self::Number(_) => "Number".into(),
252 Self::String(_) => "String".into(),
253 Self::Object(o) => o.borrow().kind.clone(),
254 }
255 }
256 pub fn get(&self, key: &str) -> Value {
257 let Self::Object(object) = self else {
258 return Self::Undefined;
259 };
260 let object = object.borrow();
261 if key == "__native" {
262 if let Some(name) = &object.native {
263 return Self::string(name);
264 }
265 }
266 if let Some(value) = object.binary_property(key) {
267 return value;
268 }
269 if let Some(property) = object.props.get(key) {
270 return property.value.clone();
271 }
272 if key == "length"
273 && matches!(
274 object.kind.as_str(),
275 "Array"
276 | "NodeList"
277 | "HTMLCollection"
278 | "Uint8Array"
279 | "Uint8ClampedArray"
280 | "Uint16Array"
281 | "Uint32Array"
282 | "Int8Array"
283 | "Int16Array"
284 | "Int32Array"
285 | "Float32Array"
286 | "Float64Array"
287 )
288 {
289 return Self::Number(object.indexed.len() as f64);
290 }
291 if let Ok(index) = key.parse::<usize>() {
292 return object.indexed.get(index).cloned().unwrap_or_default();
293 }
294 Self::Undefined
295 }
296 pub fn put(&self, key: &str, value: Value) {
297 let Self::Object(cell) = self else {
298 return;
299 };
300 let mut object = cell.borrow_mut();
301 if object.frozen {
302 return;
303 }
304 if let Some(payload) = object
305 .payload
306 .as_ref()
307 .filter(|payload| {
308 payload.is::<super::buffer::ArrayBuffer>() || payload.is::<super::buffer::TypedArray>()
309 })
310 .cloned()
311 {
312 drop(object);
314 if super::buffer::set_property(payload.as_ref(), key, &value) {
315 return;
316 }
317 object = cell.borrow_mut();
318 }
319 if let Ok(index) = key.parse::<usize>() {
320 if index < 1_048_576
321 && (index < object.indexed.len()
322 || matches!(
323 object.kind.as_str(),
324 "Array"
325 | "Uint8Array"
326 | "Uint8ClampedArray"
327 | "Uint16Array"
328 | "Uint32Array"
329 | "Int8Array"
330 | "Int16Array"
331 | "Int32Array"
332 | "Float32Array"
333 | "Float64Array"
334 ))
335 {
336 if index >= object.indexed.len() {
337 object.indexed.resize(index + 1, Self::Undefined);
338 }
339 object.indexed[index] = value;
340 return;
341 }
342 }
343 if key == "length" && object.kind == "Array" {
344 let length = value.number_value();
345 if length.is_finite() && (0.0..=1_048_576.0).contains(&length) {
346 object.indexed.resize(length as usize, Self::Undefined);
347 }
348 return;
349 }
350 if let Some(property) = object.props.get_mut(key) {
351 property.value = value;
352 } else {
353 object.props.insert(key.into(), Property::data(value));
354 }
355 }
356 pub fn put_hidden(&self, key: &str, value: Value) {
358 let Self::Object(object) = self else {
359 return;
360 };
361 let mut object = object.borrow_mut();
362 if object.frozen {
363 return;
364 }
365 object.props.insert(
366 key.into(),
367 Property {
368 value,
369 get: None,
370 set: None,
371 enumerable: false,
372 },
373 );
374 }
375 pub fn items(&self) -> Vec<Value> {
376 match self {
377 Self::Object(o) => {
378 let object = o.borrow();
379 if object.indexed.is_empty()
380 && let Some(blob) = object.payload.as_deref().and_then(|payload| {
381 payload.downcast_ref::<super::web::BlobBytes>()
382 })
383 {
384 return blob.0.iter().map(|&byte| Self::Number(f64::from(byte))).collect();
385 }
386 object
387 .binary_items()
388 .unwrap_or_else(|| object.indexed.clone())
389 }
390 Self::String(s) => s
391 .iter()
392 .map(|unit| Self::String(Rc::from([*unit])))
393 .collect(),
394 _ => Vec::new(),
395 }
396 }
397 pub fn node_id(&self) -> Option<NodeId> {
398 let object = self.as_object()?;
399 let object = object.borrow();
400 if let Some(id) = object
401 .payload
402 .as_ref()
403 .and_then(|payload| payload.downcast_ref::<NodeId>())
404 {
405 return Some(*id);
406 }
407 object
408 .props
409 .get("__node")?
410 .value
411 .text()
412 .parse::<u64>()
413 .ok()
414 .map(NodeId::from_u64)
415 }
416 pub fn same(&self, other: &Value) -> bool {
417 match (self, other) {
418 (Self::Undefined, Self::Undefined) | (Self::Null, Self::Null) => true,
419 (Self::Bool(a), Self::Bool(b)) => a == b,
420 (Self::Number(a), Self::Number(b)) => a == b,
421 (Self::String(a), Self::String(b)) => a == b,
422 (Self::Object(a), Self::Object(b)) => Rc::ptr_eq(a, b),
423 _ => false,
424 }
425 }
426 pub fn truthy(&self) -> bool {
427 match self {
428 Self::Undefined | Self::Null => false,
429 Self::Bool(v) => *v,
430 Self::Number(v) => *v != 0.0 && !v.is_nan(),
431 Self::String(v) => !v.is_empty(),
432 Self::Object(_) => true,
433 }
434 }
435 pub fn number_value(&self) -> f64 {
436 match self {
437 Self::Undefined => f64::NAN,
438 Self::Null => 0.0,
439 Self::Bool(v) => u8::from(*v) as f64,
440 Self::Number(v) => *v,
441 Self::String(s) => {
442 let s = String::from_utf16_lossy(s);
443 let s = s.trim();
444 if s.is_empty() {
445 0.0
446 } else if let Some(v) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
447 u64::from_str_radix(v, 16).map_or(f64::NAN, |v| v as f64)
448 } else {
449 s.parse().unwrap_or(f64::NAN)
450 }
451 }
452 Self::Object(_) => self.text().parse().unwrap_or(f64::NAN),
453 }
454 }
455 pub fn text(&self) -> String {
456 match self {
457 Self::Undefined => "undefined".into(),
458 Self::Null => "null".into(),
459 Self::Bool(v) => v.to_string(),
460 Self::Number(v) => {
461 if v.is_nan() {
462 "NaN".into()
463 } else if *v == 0.0 {
464 "0".into()
465 } else {
466 v.to_string()
467 }
468 }
469 Self::String(v) => String::from_utf16_lossy(v),
470 Self::Object(o) => {
471 let o = o.borrow();
472 if matches!(
473 o.kind.as_str(),
474 "Array" | "Uint8Array" | "Uint8ClampedArray" | "Uint32Array" | "Float32Array"
475 ) {
476 let items = o.binary_items();
477 items
478 .as_deref()
479 .unwrap_or(&o.indexed)
480 .iter()
481 .map(|v| {
482 if matches!(v, Self::Null | Self::Undefined) {
483 String::new()
484 } else {
485 v.text()
486 }
487 })
488 .collect::<Vec<_>>()
489 .join(",")
490 } else if o.kind == "Error" || o.kind == "DOMException" {
491 let name = o
492 .props
493 .get("name")
494 .map_or("Error".into(), |p| p.value.text());
495 let message = o
496 .props
497 .get("message")
498 .map_or(String::new(), |p| p.value.text());
499 if message.is_empty() {
500 name
501 } else {
502 format!("{name}: {message}")
503 }
504 } else if o.kind == "URL" {
505 o.props
506 .get("href")
507 .map_or(String::new(), |p| p.value.text())
508 } else {
509 format!(
510 "[object {}]",
511 if o.kind == "Object" {
512 "Object"
513 } else {
514 &o.kind
515 }
516 )
517 }
518 }
519 }
520 }
521 pub fn from_json(value: serde_json::Value) -> Value {
522 match value {
523 serde_json::Value::Null => Self::Null,
524 serde_json::Value::Bool(v) => Self::Bool(v),
525 serde_json::Value::Number(v) => Self::Number(v.as_f64().unwrap_or(f64::NAN)),
526 serde_json::Value::String(v) => Self::string(v),
527 serde_json::Value::Array(v) => {
528 Self::array(v.into_iter().map(Self::from_json).collect())
529 }
530 serde_json::Value::Object(v) => {
531 let object = Self::object("Object");
532 for (k, v) in v {
533 object.put(&k, Self::from_json(v));
534 }
535 object
536 }
537 }
538 }
539 pub fn to_json(&self) -> Result<serde_json::Value> {
540 self.json_inner(&mut BTreeSet::new(), 0)
541 }
542 fn json_inner(&self, seen: &mut BTreeSet<usize>, depth: usize) -> Result<serde_json::Value> {
543 if depth > 128 {
544 return Err(Error::new("RangeError", "JSON nesting limit exceeded"));
545 }
546 Ok(match self {
547 Self::Undefined | Self::Null => serde_json::Value::Null,
548 Self::Bool(v) => serde_json::Value::Bool(*v),
549 Self::Number(v)
550 if v.is_finite()
551 && v.fract() == 0.0
552 && *v >= i64::MIN as f64
553 && *v < i64::MAX as f64 =>
554 {
555 serde_json::Value::Number(serde_json::Number::from(*v as i64))
556 }
557 Self::Number(v)
558 if v.is_finite() && v.fract() == 0.0 && *v >= 0.0 && *v < u64::MAX as f64 =>
559 {
560 serde_json::Value::Number(serde_json::Number::from(*v as u64))
561 }
562 Self::Number(v) => serde_json::Number::from_f64(*v)
563 .map_or(serde_json::Value::Null, serde_json::Value::Number),
564 Self::String(v) => serde_json::Value::String(String::from_utf16_lossy(v)),
565 Self::Object(o) => {
566 let id = Rc::as_ptr(o) as usize;
567 if !seen.insert(id) {
568 return Err(Error::type_error(
569 "cyclic value cannot be represented as JSON",
570 ));
571 }
572 let (kind, items, properties) = {
573 let o = o.borrow();
574 (o.kind.clone(), o.indexed.clone(), o.props.clone())
575 };
576 let result = if matches!(kind.as_str(), "Array" | "NodeList" | "HTMLCollection") {
577 serde_json::Value::Array(
578 items
579 .iter()
580 .map(|v| v.json_inner(seen, depth + 1))
581 .collect::<Result<_>>()?,
582 )
583 } else {
584 let mut map = serde_json::Map::new();
585 for (k, p) in properties {
586 if p.enumerable
587 && !matches!(p.value, Self::Undefined)
588 && !matches!(p.value.kind().as_str(), "Native" | "Function")
589 {
590 map.insert(k, p.value.json_inner(seen, depth + 1)?);
591 }
592 }
593 serde_json::Value::Object(map)
594 };
595 seen.remove(&id);
596 result
597 }
598 })
599 }
600}
601
602#[derive(Default)]
603pub(super) struct RealmHeap {
604 pub(super) realm: u64,
605 objects: Vec<std::rc::Weak<RefCell<Object>>>,
606 environments: Vec<std::rc::Weak<RefCell<Environment>>>,
607 exhausted: bool,
608}
609thread_local! {
610 static ACTIVE_HEAP: RefCell<Option<std::rc::Weak<RefCell<RealmHeap>>>> = const { RefCell::new(None) };
611}
612pub(super) struct HeapScope(Option<std::rc::Weak<RefCell<RealmHeap>>>);
613impl HeapScope {
614 pub(super) fn enter(heap: &Rc<RefCell<RealmHeap>>) -> Self {
615 Self(ACTIVE_HEAP.with(|active| active.replace(Some(Rc::downgrade(heap)))))
616 }
617}
618impl Drop for HeapScope {
619 fn drop(&mut self) {
620 ACTIVE_HEAP.with(|active| {
621 active.replace(self.0.take());
622 });
623 }
624}
625impl RealmHeap {
626 pub(super) fn exhausted(&mut self) -> bool {
627 if self.exhausted {
628 self.prune_expired();
629 self.exhausted = self.objects.len() + self.environments.len() > 131_072;
630 }
631 self.exhausted
632 }
633 fn prune_expired(&mut self) {
634 self.objects.retain(|object| object.strong_count() > 0);
635 self.environments
636 .retain(|environment| environment.strong_count() > 0);
637 }
638 pub(super) fn release(&mut self) {
639 let objects = self
640 .objects
641 .drain(..)
642 .filter_map(|object| object.upgrade())
643 .collect::<Vec<_>>();
644 let environments = self
645 .environments
646 .drain(..)
647 .filter_map(|environment| environment.upgrade())
648 .collect::<Vec<_>>();
649 for object in &objects {
650 if let Ok(mut object) = object.try_borrow_mut() {
651 object.props.clear();
652 object.indexed.clear();
653 object.prototype = None;
654 object.function = None;
655 object.payload = None;
656 }
657 }
658 for environment in &environments {
659 if let Ok(mut environment) = environment.try_borrow_mut() {
660 environment.bindings.clear();
661 environment.parent = None;
662 }
663 }
664 }
665}
666fn track_object(object: &Rc<RefCell<Object>>) {
667 ACTIVE_HEAP.with(|active| {
668 if let Some(heap) = active.borrow().as_ref().and_then(std::rc::Weak::upgrade) {
669 let mut heap = heap.borrow_mut();
670 object.borrow_mut().realm = Some(heap.realm);
671 heap.objects.push(Rc::downgrade(object));
672 if heap.objects.len() + heap.environments.len() > 131_072 {
673 heap.prune_expired();
674 heap.exhausted = heap.objects.len() + heap.environments.len() > 131_072;
675 }
676 }
677 });
678}
679fn track_environment(environment: &Env) {
680 ACTIVE_HEAP.with(|active| {
681 if let Some(heap) = active.borrow().as_ref().and_then(std::rc::Weak::upgrade) {
682 let mut heap = heap.borrow_mut();
683 heap.environments.push(Rc::downgrade(environment));
684 if heap.objects.len() + heap.environments.len() > 131_072 {
685 heap.prune_expired();
686 heap.exhausted = heap.objects.len() + heap.environments.len() > 131_072;
687 }
688 }
689 });
690}