1use crate::host::{
5 call_method, invoke, is_callable, reject_promise_val, resolve_promise_val, subscribe_native,
6 take_exc_or_error, with_host, JsObj, PromiseState,
7};
8use fusevm::Value;
9
10pub const METHODS: &[&str] = &[
11 "ok",
12 "equal",
13 "notEqual",
14 "strictEqual",
15 "notStrictEqual",
16 "deepEqual",
17 "notDeepEqual",
18 "deepStrictEqual",
19 "notDeepStrictEqual",
20 "throws",
21 "doesNotThrow",
22 "fail",
23 "match",
24 "doesNotMatch",
25 "ifError",
26 "partialDeepStrictEqual",
27 "rejects",
28 "doesNotReject",
29];
30
31pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
32 let a = || args.first().cloned().unwrap_or(Value::Undef);
33 let b = || args.get(1).cloned().unwrap_or(Value::Undef);
34 Some(match method {
35 "ok" => assert_ok(args),
36 "equal" => check(loose_eq(&a(), &b()), args, 2, "==", &a(), &b()),
37 "notEqual" => check(!loose_eq(&a(), &b()), args, 2, "!=", &a(), &b()),
38 "strictEqual" => check(strict(&a(), &b()), args, 2, "===", &a(), &b()),
39 "notStrictEqual" => check(!strict(&a(), &b()), args, 2, "!==", &a(), &b()),
40 "deepEqual" => check(
41 deep_equal(&a(), &b(), false),
42 args,
43 2,
44 "deepEqual",
45 &a(),
46 &b(),
47 ),
48 "notDeepEqual" => check(
49 !deep_equal(&a(), &b(), false),
50 args,
51 2,
52 "notDeepEqual",
53 &a(),
54 &b(),
55 ),
56 "deepStrictEqual" => check(
57 deep_equal(&a(), &b(), true),
58 args,
59 2,
60 "deepStrictEqual",
61 &a(),
62 &b(),
63 ),
64 "notDeepStrictEqual" => check(
65 !deep_equal(&a(), &b(), true),
66 args,
67 2,
68 "notDeepStrictEqual",
69 &a(),
70 &b(),
71 ),
72 "throws" => throws(args, true),
73 "doesNotThrow" => throws(args, false),
74 "fail" => Err(throw_assertion(
77 &message(args, 0).unwrap_or_else(|| "Failed".to_string()),
78 message(args, 0).is_none(),
79 "fail",
80 Value::Undef,
81 Value::Undef,
82 )),
83 "match" => assert_match(args, true),
84 "doesNotMatch" => assert_match(args, false),
85 "ifError" => if_error(&a()),
86 "partialDeepStrictEqual" => partial(&a(), &b(), args),
87 "rejects" => Ok(rejects_impl(args, true)),
88 "doesNotReject" => Ok(rejects_impl(args, false)),
89 _ => return None,
90 })
91}
92
93pub fn strict_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
96 let mapped = match method {
97 "equal" => "strictEqual",
98 "notEqual" => "notStrictEqual",
99 "deepEqual" => "deepStrictEqual",
100 "notDeepEqual" => "notDeepStrictEqual",
101 other => other,
102 };
103 call(mapped, args)
104}
105
106fn assert_match(args: &[Value], want_match: bool) -> Result<Value, String> {
109 let s = args.first().cloned().unwrap_or(Value::Undef);
110 let re = args.get(1).cloned().unwrap_or(Value::Undef);
111 if !is_regexp(&re) {
112 return Err(crate::host::coded_error(
114 "TypeError",
115 "ERR_INVALID_ARG_TYPE",
116 &format!(
117 "The \"regexp\" argument must be an instance of RegExp. Received {}",
118 crate::stdlib::received_desc(&re)
119 ),
120 ));
121 }
122 let is_string = with_host(|h| h.type_of(&s) == "string");
125 if is_string && regexp_matches(&re, &s)? == want_match {
126 return Ok(Value::Undef);
127 }
128 let operator = if want_match { "match" } else { "doesNotMatch" };
129 let custom = message(args, 2);
130 let generated = custom.is_none();
131 let msg = custom.unwrap_or_else(|| {
132 with_host(|h| {
133 if !is_string {
134 return format!(
135 "The \"string\" argument must be of type string. Received type {} ({})",
136 h.type_of(&s),
137 h.inspect(&s)
138 );
139 }
140 let verb = if want_match {
141 "The input did not match the regular expression"
142 } else {
143 "The input was expected to not match the regular expression"
144 };
145 format!("{verb} {}. Input:\n\n{}\n", h.inspect(&re), h.inspect(&s))
146 })
147 });
148 Err(throw_assertion(&msg, generated, operator, s, re))
149}
150
151fn is_regexp(v: &Value) -> bool {
152 with_host(|h| matches!(h.get(v), Some(JsObj::RegExp(_))))
153}
154
155fn regexp_matches(re: &Value, s: &Value) -> Result<bool, String> {
157 let m = call_method(re, "exec", vec![s.clone()])?;
158 Ok(!with_host(|h| h.is_null(&m)) && !matches!(m, Value::Undef))
159}
160
161fn if_error(v: &Value) -> Result<Value, String> {
163 if with_host(|h| h.is_nullish(v)) {
164 return Ok(Value::Undef);
165 }
166 let desc = with_host(|h| match h.get(v) {
167 Some(JsObj::Object(p)) => p
168 .get("message")
169 .map(|m| h.str_of(m))
170 .unwrap_or_else(|| h.inspect(v)),
171 _ => h.inspect(v),
172 });
173 Err(assertion_error(&format!(
174 "ifError got unwanted exception: {desc}"
175 )))
176}
177
178fn partial(actual: &Value, expected: &Value, args: &[Value]) -> Result<Value, String> {
182 if partial_deep(actual, expected) {
183 return Ok(Value::Undef);
184 }
185 if let Some(m) = message(args, 2) {
186 return Err(assertion_error(&m));
187 }
188 let (sa, sb) = with_host(|h| (h.inspect(actual), h.inspect(expected)));
189 Err(assertion_error(&format!(
190 "Expected values to be strictly deep-equal (partial):\n{sb} should be a subset of {sa}"
191 )))
192}
193
194fn partial_deep(actual: &Value, expected: &Value) -> bool {
195 let ekind = with_host(|h| h.get(expected).map(kind));
196 match ekind {
197 Some(Kind::Object) => {
198 if !matches!(with_host(|h| h.get(actual).map(kind)), Some(Kind::Object)) {
199 return false;
200 }
201 let (ea, ee) = with_host(|h| (object_of(h, actual), object_of(h, expected)));
202 ee.iter().all(|(k, ve)| {
203 ea.iter()
204 .find(|(k2, _)| k2 == k)
205 .is_some_and(|(_, va)| partial_deep(va, ve))
206 })
207 }
208 Some(Kind::Array) => {
209 if !matches!(with_host(|h| h.get(actual).map(kind)), Some(Kind::Array)) {
210 return false;
211 }
212 let (ia, ie) = with_host(|h| (array_of(h, actual), array_of(h, expected)));
213 ie.len() <= ia.len() && ie.iter().zip(ia.iter()).all(|(e, a)| partial_deep(a, e))
214 }
215 _ => strict(actual, expected),
216 }
217}
218
219fn rejects_impl(args: &[Value], want_reject: bool) -> Value {
224 let input = args.first().cloned().unwrap_or(Value::Undef);
225 let rest: Vec<Value> = args.get(1..).unwrap_or(&[]).to_vec();
226 let result = with_host(|h| h.new_promise());
227 let rid = with_host(|h| h.promise_id(&result).unwrap());
228 let fail = |e: String| {
229 let ev = take_exc_or_error(&e);
230 reject_promise_val(rid, ev);
231 };
232 let operand = if with_host(|h| is_callable(h, &input)) {
236 match invoke(&input, Vec::new(), None) {
237 Ok(v) if is_promise_like(&v) => crate::host::promise_of(&v),
238 Ok(v) => {
239 fail(crate::host::coded_error(
240 "TypeError",
241 "ERR_INVALID_RETURN_VALUE",
242 &format!(
243 "Expected instance of Promise to be returned from the \"promiseFn\" function but got {}.",
244 crate::stdlib::received_desc(&v)
245 ),
246 ));
247 return result;
248 }
249 Err(e) => {
250 fail(e);
251 return result;
252 }
253 }
254 } else if is_promise_like(&input) {
255 crate::host::promise_of(&input)
256 } else {
257 fail(crate::host::coded_error(
258 "TypeError",
259 "ERR_INVALID_ARG_TYPE",
260 &format!(
261 "The \"promiseFn\" argument must be of type function or an instance of Promise. Received {}",
262 crate::stdlib::received_desc(&input)
263 ),
264 ));
265 return result;
266 };
267 let oid = with_host(|h| h.promise_id(&operand).unwrap());
268 subscribe_native(
269 oid,
270 Box::new(move |state, val| {
271 let actual = (state == PromiseState::Rejected).then_some(val);
272 let checked = if want_reject {
273 expects_error("rejects", "rejection", actual, &rest)
274 } else {
275 expects_no_error("doesNotReject", "rejection", actual, &rest)
276 };
277 match checked {
278 Ok(()) => resolve_promise_val(rid, Value::Undef),
279 Err(e) => {
280 let ev = take_exc_or_error(&e);
281 reject_promise_val(rid, ev);
282 }
283 }
284 Ok(())
285 }),
286 );
287 result
288}
289
290pub fn construct_assertion_error(args: &[Value]) -> Value {
294 let opts = args.first().cloned().unwrap_or(Value::Undef);
295 let (message, actual, expected, operator) = with_host(|h| match h.get(&opts) {
296 Some(JsObj::Object(p)) => (
297 p.get("message").map(|v| h.str_of(v)),
298 p.get("actual").cloned(),
299 p.get("expected").cloned(),
300 p.get("operator").map(|v| h.str_of(v)),
301 ),
302 _ => (None, None, None, None),
303 });
304 let generated = message.is_none();
305 let msg = message.unwrap_or_else(|| {
306 let (sa, se) = with_host(|h| {
307 (
308 actual.as_ref().map(|v| h.inspect(v)).unwrap_or_default(),
309 expected.as_ref().map(|v| h.inspect(v)).unwrap_or_default(),
310 )
311 });
312 let op = operator.clone().unwrap_or_else(|| "==".to_string());
313 format!("{sa} {op} {se}")
314 });
315 assertion_error_object(
316 &msg,
317 generated,
318 operator.as_deref(),
319 actual.unwrap_or(Value::Undef),
320 expected.unwrap_or(Value::Undef),
321 )
322}
323
324const DIFF_MODE: &str = "simple";
329
330fn assertion_error_object(
340 msg: &str,
341 generated: bool,
342 operator: Option<&str>,
343 actual: Value,
344 expected: Value,
345) -> Value {
346 let stack = format!("AssertionError [ERR_ASSERTION]: {msg}\n at <anonymous>");
347 let op_val = match operator {
348 Some(o) => with_host(|h| h.new_str(o)),
349 None => Value::Undef,
350 };
351 let name_v = with_host(|h| h.new_str("AssertionError"));
352 let msg_v = with_host(|h| h.new_str(msg));
353 let code_v = with_host(|h| h.new_str("ERR_ASSERTION"));
354 let stack_v = with_host(|h| h.new_str(stack));
355 let diff_v = with_host(|h| h.new_str(DIFF_MODE));
356 let mut props: indexmap::IndexMap<String, Value> = indexmap::IndexMap::new();
360 props.insert("stack".into(), stack_v);
361 props.insert("message".into(), msg_v);
362 props.insert("generatedMessage".into(), Value::Bool(generated));
363 props.insert("name".into(), name_v);
364 props.insert("code".into(), code_v);
365 props.insert("actual".into(), actual);
366 props.insert("expected".into(), expected);
367 props.insert("operator".into(), op_val);
368 props.insert("diff".into(), diff_v);
369 let obj = with_host(|h| h.new_object(props));
370 with_host(|h| {
371 for k in ["name", "message", "stack"] {
372 h.hide_prop(&obj, k);
373 }
374 h.ensure_error_protos();
375 if let Some(p) = crate::host::error_proto_of(h, "AssertionError") {
379 h.set_proto(&obj, p);
380 }
381 });
382 obj
383}
384
385fn throw_assertion(
392 msg: &str,
393 generated: bool,
394 operator: &str,
395 actual: Value,
396 expected: Value,
397) -> String {
398 let err = assertion_error_object(msg, generated, Some(operator), actual, expected);
399 with_host(|h| h.exc = Some(err));
400 assertion_error(msg)
401}
402
403pub fn assert_ok(args: &[Value]) -> Result<Value, String> {
405 let v = args.first().cloned().unwrap_or(Value::Undef);
406 if with_host(|h| h.truthy(&v)) {
407 return Ok(Value::Undef);
408 }
409 let custom = message(args, 1);
410 let msg = custom.clone().unwrap_or_else(||
411 "The expression evaluated to a falsy value:".to_string());
414 Err(throw_assertion(
418 &msg,
419 custom.is_none(),
420 "==",
421 v,
422 Value::Bool(true),
423 ))
424}
425
426fn check(
427 pass: bool,
428 args: &[Value],
429 msg_idx: usize,
430 op: &str,
431 a: &Value,
432 b: &Value,
433) -> Result<Value, String> {
434 if pass {
435 return Ok(Value::Undef);
436 }
437 let custom = message(args, msg_idx);
438 let diff_operator = match op {
444 "===" => Some("strictEqual"),
445 "deepStrictEqual" => Some("deepStrictEqual"),
446 "partialDeepStrictEqual" => Some("partialDeepStrictEqual"),
447 _ => None,
448 };
449 if let Some(diff_op) = diff_operator {
450 let msg = super::assert_diff::create_err_diff(a, b, diff_op, custom.as_deref());
451 let operator = if op == "===" { "strictEqual" } else { op };
452 return Err(throw_assertion(
453 &msg,
454 custom.is_none(),
455 operator,
456 a.clone(),
457 b.clone(),
458 ));
459 }
460 let (sa, sb) = (
465 super::assert_diff::inspect_operand(a),
466 super::assert_diff::inspect_operand(b),
467 );
468 let msg = match op {
473 "==" | "!=" => format!("{sa} {op} {sb}"),
474 "===" => format!("Expected values to be strictly equal:\n\n{sa} !== {sb}\n"),
475 "!==" => format!("Expected \"actual\" to be strictly unequal to: {sa}"),
476 "deepEqual" => format!(
477 "Expected values to be loosely deep-equal:\n\n{sa}\n\nshould loosely \
478 deep-equal\n\n{sb}"
479 ),
480 "notDeepEqual" => {
481 format!("Expected \"actual\" not to be loosely deep-equal to:\n\n{sa}")
482 }
483 "deepStrictEqual" => {
488 format!("Expected values to be strictly deep-equal:\n\n{sa} !== {sb}\n")
489 }
490 "notDeepStrictEqual" => {
491 format!("Expected \"actual\" not to be strictly deep-equal to:\n\n{sa}\n")
492 }
493 _ => format!("{sa} {op} {sb}"),
494 };
495 let operator = match op {
500 "===" => "strictEqual",
501 "!==" => "notStrictEqual",
502 other => other,
503 };
504 Err(throw_assertion(
505 &custom.clone().unwrap_or(msg),
506 custom.is_none(),
507 operator,
508 a.clone(),
509 b.clone(),
510 ))
511}
512
513fn throws(args: &[Value], want_throw: bool) -> Result<Value, String> {
518 let f = args.first().cloned().unwrap_or(Value::Undef);
519 if !with_host(|h| is_callable(h, &f)) {
520 return Err(crate::host::coded_error(
521 "TypeError",
522 "ERR_INVALID_ARG_TYPE",
523 &format!(
524 "The \"fn\" argument must be of type function. Received {}",
525 crate::stdlib::received_desc(&f)
526 ),
527 ));
528 }
529 let caught = match invoke(&f, Vec::new(), None) {
532 Ok(_) => None,
533 Err(e) => Some(crate::host::take_exc_or_error(&e)),
534 };
535 let rest = args.get(1..).unwrap_or(&[]);
536 if want_throw {
537 expects_error("throws", "exception", caught, rest)
538 } else {
539 expects_no_error("doesNotThrow", "exception", caught, rest)
540 }
541 .map(|_| Value::Undef)
542}
543
544fn expects_error(
547 operator: &str,
548 kind: &str,
549 actual: Option<Value>,
550 rest: &[Value],
551) -> Result<(), String> {
552 let mut error = rest.first().cloned().unwrap_or(Value::Undef);
553 let mut msg = message(rest, 1);
554 let type_of = |v: &Value| with_host(|h| h.type_of(v));
555 if type_of(&error) == "string" {
556 if rest.len() >= 2 {
557 return Err(invalid_error_arg(&error));
558 }
559 let text = with_host(|h| h.str_of(&error));
560 if let Some(a) = &actual {
561 if is_object(a) {
562 let m = crate::builtins::get_property(a, "message")?;
563 if with_host(|h| h.type_of(&m) == "string" && h.str_of(&m) == text) {
564 return Err(ambiguous(&format!(
565 "The error message \"{text}\" is identical to the message."
566 )));
567 }
568 } else if with_host(|h| h.type_of(a) == "string" && h.str_of(a) == text) {
569 return Err(ambiguous(&format!(
570 "The error \"{text}\" is identical to the message."
571 )));
572 }
573 }
574 msg = Some(text);
575 error = Value::Undef;
576 } else if !with_host(|h| h.is_nullish(&error))
577 && !matches!(type_of(&error), "object" | "function")
578 {
579 return Err(invalid_error_arg(&error));
580 }
581 let Some(actual) = actual else {
582 let name = if with_host(|h| h.is_nullish(&error)) {
583 None
584 } else {
585 let n = crate::builtins::get_property(&error, "name")?;
586 with_host(|h| h.truthy(&n).then(|| h.str_of(&n)))
587 };
588 let mut details = name.map(|n| format!(" ({n})")).unwrap_or_default();
589 details.push_str(&msg.map(|m| format!(": {m}")).unwrap_or_else(|| ".".into()));
590 return Err(throw_assertion(
591 &format!("Missing expected {kind}{details}"),
592 false,
593 operator,
594 Value::Undef,
595 error,
596 ));
597 };
598 if !with_host(|h| h.truthy(&error)) {
599 return Ok(());
600 }
601 expected_exception(operator, actual, error, msg)
602}
603
604fn invalid_error_arg(error: &Value) -> String {
605 crate::host::coded_error(
606 "TypeError",
607 "ERR_INVALID_ARG_TYPE",
608 &format!(
609 "The \"error\" argument must be of type function or an instance of Error, RegExp, or Object. Received {}",
610 crate::stdlib::received_desc(error)
611 ),
612 )
613}
614
615fn ambiguous(detail: &str) -> String {
616 crate::host::coded_error(
617 "TypeError",
618 "ERR_AMBIGUOUS_ARGUMENT",
619 &format!("The \"error/message\" argument is ambiguous. {detail}"),
620 )
621}
622
623fn is_object(v: &Value) -> bool {
624 with_host(|h| h.type_of(v) == "object" && !h.is_null(v))
625}
626
627fn is_error(v: &Value) -> bool {
629 is_object(v) && with_host(|h| crate::builtins::object_tag(h, v) == "[object Error]")
630}
631
632fn expected_exception(
635 operator: &str,
636 actual: Value,
637 expected: Value,
638 msg: Option<String>,
639) -> Result<(), String> {
640 let generated = msg.is_none();
641 let fail = |text: String| -> Result<(), String> {
642 Err(throw_assertion(
643 &text,
644 generated,
645 operator,
646 actual.clone(),
647 expected.clone(),
648 ))
649 };
650 if with_host(|h| h.type_of(&expected)) != "function" {
651 if is_regexp(&expected) {
652 let s = crate::host::to_string_value(&actual)?;
653 if regexp_matches(&expected, &s)? {
654 return Ok(());
655 }
656 return fail(msg.unwrap_or_else(|| {
657 with_host(|h| {
658 format!(
659 "The input did not match the regular expression {}. Input:\n\n{}\n",
660 h.inspect(&expected),
661 h.inspect(&s)
662 )
663 })
664 }));
665 }
666 if !is_object(&actual) {
667 let text = msg.unwrap_or_else(|| {
668 super::assert_diff::create_err_diff(&actual, &expected, "deepStrictEqual", None)
669 });
670 return fail(text);
671 }
672 let keys_v = crate::builtins::call_builtin_function("Object.keys", vec![expected.clone()])?;
676 let mut keys: Vec<Value> = with_host(|h| match h.get(&keys_v) {
677 Some(JsObj::Array(items)) => items.clone(),
678 _ => Vec::new(),
679 });
680 if is_error(&expected) {
681 keys.extend(with_host(|h| [h.new_str("name"), h.new_str("message")]));
682 } else if keys.is_empty() {
683 let shown = with_host(|h| h.inspect(&expected));
684 return Err(crate::host::coded_error(
685 "TypeError",
686 "ERR_INVALID_ARG_VALUE",
687 &format!("The argument 'error' may not be an empty object. Received {shown}"),
688 ));
689 }
690 for key in &keys {
691 let k = with_host(|h| h.str_of(key));
692 let a = crate::builtins::get_property(&actual, &k)?;
693 let e = crate::builtins::get_property(&expected, &k)?;
694 if with_host(|h| h.type_of(&a)) == "string" && is_regexp(&e) && regexp_matches(&e, &a)?
695 {
696 continue;
697 }
698 let present = crate::builtins::has_property(&actual, &k)?;
699 if present && deep_equal(&a, &e, true) {
700 continue;
701 }
702 let text = match &msg {
703 Some(m) => m.clone(),
704 None => {
705 let keys_arr = with_host(|h| h.new_array(keys.clone()));
706 let ca = comparison(&actual, &keys_arr, &Value::Undef)?;
707 let cb = comparison(&expected, &keys_arr, &actual)?;
708 super::assert_diff::create_err_diff(&ca, &cb, "deepStrictEqual", None)
709 }
710 };
711 return fail(text);
712 }
713 return Ok(());
714 }
715 let proto = crate::builtins::get_property(&expected, "prototype")?;
717 if !matches!(proto, Value::Undef) && crate::host::instance_of(&actual, &expected)? {
718 return Ok(());
719 }
720 if is_error_subclass(&expected) {
721 let text = match msg {
722 Some(m) => m,
723 None => {
724 let name = with_host(|h| h.callable_name(&expected));
725 let mut m =
726 format!("The error is expected to be an instance of \"{name}\". Received ");
727 if is_error(&actual) {
728 let ctor = crate::builtins::get_property(&actual, "constructor")?;
729 let ctor_name = if with_host(|h| h.truthy(&ctor)) {
730 crate::builtins::get_property(&ctor, "name")?
731 } else {
732 Value::Undef
733 };
734 let actual_name = if with_host(|h| h.truthy(&ctor_name)) {
735 with_host(|h| h.str_of(&ctor_name))
736 } else {
737 let n = crate::builtins::get_property(&actual, "name")?;
738 with_host(|h| h.str_of(&n))
739 };
740 if actual_name == name {
741 m.push_str("an error with identical name but a different prototype.");
742 } else {
743 m.push_str(&format!("\"{actual_name}\""));
744 }
745 let am = crate::builtins::get_property(&actual, "message")?;
746 if with_host(|h| h.truthy(&am)) {
747 m.push_str(&format!(
748 "\n\nError message:\n\n{}",
749 with_host(|h| h.str_of(&am))
750 ));
751 }
752 } else {
753 m.push_str(&format!("\"{}\"", with_host(|h| h.inspect(&actual))));
754 }
755 m
756 }
757 };
758 return fail(text);
759 }
760 let this = with_host(|h| h.new_object(indexmap::IndexMap::new()));
762 let res = invoke(&expected, vec![actual.clone()], Some(this))?;
763 if matches!(res, Value::Bool(true)) {
764 return Ok(());
765 }
766 let text = match msg {
767 Some(m) => m,
768 None => {
769 let name = with_host(|h| h.callable_name(&expected));
770 let named = if name.is_empty() {
771 String::new()
772 } else {
773 format!("\"{name}\" ")
774 };
775 let mut m = format!(
776 "The {named}validation function is expected to return \"true\". Received {}",
777 with_host(|h| h.inspect(&res))
778 );
779 if is_error(&actual) {
780 let s = crate::host::to_string_value(&actual)?;
781 m.push_str(&format!(
782 "\n\nCaught error:\n\n{}",
783 with_host(|h| h.str_of(&s))
784 ));
785 }
786 m
787 }
788 };
789 fail(text)
790}
791
792fn expects_no_error(
795 operator: &str,
796 kind: &str,
797 actual: Option<Value>,
798 rest: &[Value],
799) -> Result<(), String> {
800 let Some(actual) = actual else {
801 return Ok(());
802 };
803 let mut error = rest.first().cloned().unwrap_or(Value::Undef);
804 let mut msg = message(rest, 1);
805 if with_host(|h| h.type_of(&error)) == "string" {
806 msg = Some(with_host(|h| h.str_of(&error)));
807 error = Value::Undef;
808 }
809 if !with_host(|h| h.truthy(&error)) || has_matching_error(&actual, &error)? {
810 let details = msg.map(|m| format!(": {m}")).unwrap_or_else(|| ".".into());
811 let actual_message = if is_object(&actual) {
812 let m = crate::builtins::get_property(&actual, "message")?;
813 with_host(|h| h.str_of(&m))
814 } else {
815 "undefined".to_string()
816 };
817 return Err(throw_assertion(
818 &format!("Got unwanted {kind}{details}\nActual message: \"{actual_message}\""),
819 false,
820 operator,
821 actual,
822 error,
823 ));
824 }
825 Err(with_host(|h| {
826 h.exc = Some(actual.clone());
827 crate::builtins::error_string(h, &actual)
828 }))
829}
830
831fn has_matching_error(actual: &Value, expected: &Value) -> Result<bool, String> {
833 if with_host(|h| h.type_of(expected)) != "function" {
834 if is_regexp(expected) {
835 let s = crate::host::to_string_value(actual)?;
836 return regexp_matches(expected, &s);
837 }
838 return Err(crate::host::coded_error(
839 "TypeError",
840 "ERR_INVALID_ARG_TYPE",
841 &format!(
842 "The \"expected\" argument must be of type function or an instance of RegExp. Received {}",
843 crate::stdlib::received_desc(expected)
844 ),
845 ));
846 }
847 let proto = crate::builtins::get_property(expected, "prototype")?;
848 if !matches!(proto, Value::Undef) && crate::host::instance_of(actual, expected)? {
849 return Ok(true);
850 }
851 if is_error_subclass(expected) {
852 return Ok(false);
853 }
854 let this = with_host(|h| h.new_object(indexmap::IndexMap::new()));
855 let res = invoke(expected, vec![actual.clone()], Some(this))?;
856 Ok(matches!(res, Value::Bool(true)))
857}
858
859fn is_error_subclass(expected: &Value) -> bool {
862 let mut cur = crate::builtins::prototype_of(expected);
863 for _ in 0..100_000 {
864 if with_host(|h| h.is_null(&cur) || matches!(cur, Value::Undef)) {
865 return false;
866 }
867 if with_host(|h| matches!(h.get(&cur), Some(JsObj::Builtin(n)) if n == "Error")) {
868 return true;
869 }
870 cur = crate::builtins::prototype_of(&cur);
871 }
872 false
873}
874
875fn comparison(obj: &Value, keys: &Value, actual: &Value) -> Result<Value, String> {
880 thread_local! {
881 static FACTORY: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
882 }
883 let factory = match FACTORY.with(|f| f.borrow().clone()) {
884 Some(f) => f,
885 None => {
886 let f = crate::eval_internal(
887 "(() => { class Comparison { constructor(obj, keys, actual) { for (const key of keys) { if (key in obj) { if (actual !== undefined && typeof actual[key] === 'string' && Object.prototype.toString.call(obj[key]) === '[object RegExp]' && obj[key].exec(actual[key]) !== null) { this[key] = actual[key]; } else { this[key] = obj[key]; } } } } } return (obj, keys, actual) => new Comparison(obj, keys, actual); })()",
888 )?;
889 FACTORY.with(|c| *c.borrow_mut() = Some(f.clone()));
890 f
891 }
892 };
893 invoke(
894 &factory,
895 vec![obj.clone(), keys.clone(), actual.clone()],
896 None,
897 )
898}
899
900fn message(args: &[Value], idx: usize) -> Option<String> {
901 match args.get(idx) {
902 Some(Value::Undef) | None => None,
903 Some(v) => Some(with_host(|h| h.str_of(v))),
904 }
905}
906
907fn assertion_error(msg: &str) -> String {
914 crate::host::coded_error("AssertionError", "ERR_ASSERTION", msg)
915}
916
917fn strict(a: &Value, b: &Value) -> bool {
923 crate::builtins::same_value(a, b)
924}
925
926fn loose_eq(a: &Value, b: &Value) -> bool {
927 if strict(a, b) {
928 return true;
929 }
930 with_host(|h| {
931 let (na, nb) = (h.to_number(a), h.to_number(b));
932 if !na.is_nan() && !nb.is_nan() && (na == nb) {
933 return true;
934 }
935 h.str_of(a) == h.str_of(b)
936 })
937}
938
939pub fn deep_equal(a: &Value, b: &Value, strict_mode: bool) -> bool {
941 deep_equal_seen(a, b, strict_mode, &mut Vec::new())
942}
943
944fn deep_equal_seen(
952 a: &Value,
953 b: &Value,
954 strict_mode: bool,
955 seen: &mut Vec<(Value, Value)>,
956) -> bool {
957 if seen.iter().any(|(x, y)| x == a && y == b) {
958 return true;
959 }
960 if strict_mode {
965 let both_objects = with_host(|h| h.get(a).is_some() && h.get(b).is_some());
966 if both_objects
967 && with_host(|h| {
968 h.proto_of(a) != h.proto_of(b) || h.has_null_proto(a) != h.has_null_proto(b)
973 })
974 {
975 return false;
976 }
977 }
978 let kinds = with_host(|h| {
979 let av = h.get(a).map(kind);
980 let bv = h.get(b).map(kind);
981 (av, bv)
982 });
983 seen.push((a.clone(), b.clone()));
984 let result = deep_equal_body(a, b, strict_mode, seen, kinds);
985 seen.pop();
986 result
987}
988
989fn deep_equal_body(
990 a: &Value,
991 b: &Value,
992 strict_mode: bool,
993 seen: &mut Vec<(Value, Value)>,
994 kinds: (Option<Kind>, Option<Kind>),
995) -> bool {
996 match kinds {
997 (Some(Kind::Array), Some(Kind::Array)) => {
998 let (ia, ib) = with_host(|h| (array_of(h, a), array_of(h, b)));
999 ia.len() == ib.len()
1000 && ia
1001 .iter()
1002 .zip(ib.iter())
1003 .all(|(x, y)| deep_equal_seen(x, y, strict_mode, seen))
1004 }
1005 (Some(Kind::Object), Some(Kind::Object)) => {
1006 let both_buffers = [a, b]
1010 .iter()
1011 .all(|v| crate::stdlib::native_tag(v).as_deref() == Some("Buffer"));
1012 if both_buffers
1013 && crate::stdlib::buffer::view_bytes(a) != crate::stdlib::buffer::view_bytes(b)
1014 {
1015 return false;
1016 }
1017 let is_view_slot = |k: &str| {
1018 both_buffers && matches!(k, "byteOffset" | "buffer" | "@@bytes" | "@@buffer")
1019 };
1020 let (ea, eb) = with_host(|h| (object_of(h, a), object_of(h, b)));
1021 let ea: Vec<_> = ea.into_iter().filter(|(k, _)| !is_view_slot(k)).collect();
1022 let eb: Vec<_> = eb.into_iter().filter(|(k, _)| !is_view_slot(k)).collect();
1023 if ea.len() != eb.len() {
1024 return false;
1025 }
1026 let props_match = ea.iter().all(|(k, va)| {
1027 eb.iter()
1028 .find(|(k2, _)| k2 == k)
1029 .is_some_and(|(_, vb)| deep_equal_seen(va, vb, strict_mode, seen))
1030 });
1031 if !props_match {
1032 return false;
1033 }
1034 let (ia, ib) = with_host(|h| (internals_of(h, a), internals_of(h, b)));
1044 let ia: Vec<_> = ia.into_iter().filter(|(k, _)| !is_view_slot(k)).collect();
1045 let ib: Vec<_> = ib.into_iter().filter(|(k, _)| !is_view_slot(k)).collect();
1046 if ia.len() != ib.len() {
1047 return false;
1048 }
1049 ia.iter().all(|(k, va)| {
1050 ib.iter()
1051 .find(|(k2, _)| k2 == k)
1052 .is_some_and(|(_, vb)| deep_equal_seen(va, vb, strict_mode, seen))
1053 })
1054 }
1055 (Some(Kind::Map), Some(Kind::Map)) => {
1060 let (ea, eb) = with_host(|h| (map_entries_of(h, a), map_entries_of(h, b)));
1061 unordered_match(&ea, &eb, seen, |(ka, va), (kb, vb), seen| {
1062 deep_equal_seen(ka, kb, strict_mode, seen)
1063 && deep_equal_seen(va, vb, strict_mode, seen)
1064 })
1065 }
1066 (Some(Kind::Set), Some(Kind::Set)) => {
1067 let (ea, eb) = with_host(|h| (set_members_of(h, a), set_members_of(h, b)));
1068 unordered_match(&ea, &eb, seen, |x, y, seen| {
1069 deep_equal_seen(x, y, strict_mode, seen)
1070 })
1071 }
1072 (Some(Kind::RegExp), Some(Kind::RegExp)) => {
1075 with_host(|h| regexp_key(h, a) == regexp_key(h, b))
1076 }
1077 _ => {
1083 if strict_mode {
1084 strict(a, b)
1085 } else {
1086 loose_eq(a, b)
1087 }
1088 }
1089 }
1090}
1091
1092fn unordered_match<T>(
1097 ea: &[T],
1098 eb: &[T],
1099 seen: &mut Vec<(Value, Value)>,
1100 eq: impl Fn(&T, &T, &mut Vec<(Value, Value)>) -> bool,
1101) -> bool {
1102 if ea.len() != eb.len() {
1103 return false;
1104 }
1105 let mut claimed = vec![false; eb.len()];
1106 'outer: for x in ea {
1107 for (i, y) in eb.iter().enumerate() {
1108 if !claimed[i] && eq(x, y, seen) {
1109 claimed[i] = true;
1110 continue 'outer;
1111 }
1112 }
1113 return false;
1114 }
1115 true
1116}
1117
1118enum Kind {
1119 Array,
1120 Object,
1121 Map,
1122 Set,
1123 RegExp,
1124 Other,
1126}
1127fn kind(o: &JsObj) -> Kind {
1128 match o {
1129 JsObj::Array(_) => Kind::Array,
1130 JsObj::Object(_) => Kind::Object,
1131 JsObj::Map { weak: false, .. } => Kind::Map,
1134 JsObj::Set { weak: false, .. } => Kind::Set,
1135 JsObj::RegExp(_) => Kind::RegExp,
1136 _ => Kind::Other,
1137 }
1138}
1139fn map_entries_of(h: &crate::host::JsHost, v: &Value) -> Vec<(Value, Value)> {
1141 match h.get(v) {
1142 Some(JsObj::Map { entries, .. }) => entries.values().cloned().collect(),
1143 _ => Vec::new(),
1144 }
1145}
1146fn set_members_of(h: &crate::host::JsHost, v: &Value) -> Vec<Value> {
1148 match h.get(v) {
1149 Some(JsObj::Set { entries, .. }) => entries.values().cloned().collect(),
1150 _ => Vec::new(),
1151 }
1152}
1153fn regexp_key(h: &crate::host::JsHost, v: &Value) -> Option<(String, String)> {
1155 match h.get(v) {
1156 Some(JsObj::RegExp(r)) => Some((r.source.clone(), r.flags.clone())),
1157 _ => None,
1158 }
1159}
1160fn internals_of(h: &crate::host::JsHost, v: &Value) -> Vec<(String, Value)> {
1165 match h.get(v) {
1166 Some(JsObj::Object(p)) => p
1167 .iter()
1168 .filter(|(k, _)| k.starts_with("@@"))
1169 .map(|(k, v)| (k.clone(), v.clone()))
1170 .collect(),
1171 _ => Vec::new(),
1172 }
1173}
1174fn array_of(h: &crate::host::JsHost, v: &Value) -> Vec<Value> {
1175 match h.get(v) {
1176 Some(JsObj::Array(items)) => items.clone(),
1177 _ => Vec::new(),
1178 }
1179}
1180fn object_of(h: &crate::host::JsHost, v: &Value) -> Vec<(String, Value)> {
1181 match h.get(v) {
1182 Some(JsObj::Object(p)) => p
1183 .iter()
1184 .filter(|(k, _)| !k.starts_with("@@") && !k.starts_with('#'))
1185 .map(|(k, v)| (k.clone(), v.clone()))
1186 .collect(),
1187 _ => Vec::new(),
1188 }
1189}
1190
1191fn is_promise_like(v: &Value) -> bool {
1194 if with_host(|h| h.promise_id(v)).is_some() {
1195 return true;
1196 }
1197 if !is_object(v) {
1198 return false;
1199 }
1200 ["then", "catch"].iter().all(|k| {
1201 crate::builtins::get_property(v, k)
1202 .map(|f| with_host(|h| is_callable(h, &f)))
1203 .unwrap_or(false)
1204 })
1205}