1use std::fmt::Write as _;
29
30use crate::object::PropertyKey;
31use crate::{Gc, Interp, JsObject, JsResult, Value};
32
33const MAX_DEPTH: usize = 2;
35const MAX_STRING_LENGTH: usize = 1000;
37const MAX_ITEM_COUNT: usize = 100;
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct PrintLimits {
51 pub max_depth: usize,
53 pub max_string_length: usize,
55 pub max_item_count: usize,
57}
58
59impl Default for PrintLimits {
60 fn default() -> PrintLimits {
61 PrintLimits {
62 max_depth: MAX_DEPTH,
63 max_string_length: MAX_STRING_LENGTH,
64 max_item_count: MAX_ITEM_COUNT,
65 }
66 }
67}
68
69pub fn sprint(interp: &mut Interp<'_>, value: &Value) -> JsResult<String> {
71 sprint_limited(interp, value, PrintLimits::default())
72}
73
74pub fn sprint_limited(
76 interp: &mut Interp<'_>,
77 value: &Value,
78 limits: PrintLimits,
79) -> JsResult<String> {
80 let mut printer = Printer {
81 interp,
82 out: String::new(),
83 stack: Vec::new(),
84 limits,
85 };
86 printer.print_value(value)?;
87 Ok(printer.out)
88}
89
90struct Printer<'i, 'a> {
91 interp: &'i mut Interp<'a>,
92 out: String,
93 stack: Vec<Gc<JsObject>>,
95 limits: PrintLimits,
97}
98
99#[derive(Clone, Copy, PartialEq, Eq)]
106enum Comma {
107 First,
108 Next,
109}
110
111impl Comma {
112 fn before(&mut self, out: &mut String) {
113 if *self == Comma::Next {
114 out.push_str(", ");
115 }
116 *self = Comma::Next;
117 }
118}
119
120impl Printer<'_, '_> {
121 fn print_value(&mut self, value: &Value) -> JsResult<()> {
122 match value {
123 Value::Undefined => self.out.push_str("undefined"),
124 Value::Null => self.out.push_str("null"),
125 Value::Bool(flag) => self.out.push_str(if *flag { "true" } else { "false" }),
126 Value::Int(number) => {
127 let _ = write!(self.out, "{number}");
128 }
129 Value::Float(number) => {
133 if *number == 0.0 && number.is_sign_negative() {
134 self.out.push_str("-0");
137 } else {
138 self.out.push_str(&value.to_js_string());
141 }
142 }
143 Value::BigInt(big) => {
144 self.out.push_str(&big.to_decimal_string());
145 self.out.push('n');
146 }
147 Value::Symbol(symbol) => {
148 let _ = write!(
149 self.out,
150 "Symbol({:?})",
151 symbol.description().unwrap_or_default()
152 );
153 }
154 Value::String(_) => {
155 let text = value.to_js_string();
156 self.print_string(&text);
157 }
158 Value::Object(object) => self.print_object(object)?,
159 other => {
161 let _ = write!(self.out, "[unknown value {}]", other.type_of());
162 }
163 }
164 Ok(())
165 }
166}
167
168impl Printer<'_, '_> {
169 fn print_string(&mut self, text: &str) {
171 self.out.push('"');
172 let chars: Vec<char> = text.chars().collect();
173 let shown = chars.len().min(self.limits.max_string_length);
174 for &c in &chars[..shown] {
175 match c {
176 '\t' => self.out.push_str("\\t"),
177 '\r' => self.out.push_str("\\r"),
178 '\n' => self.out.push_str("\\n"),
179 '\u{8}' => self.out.push_str("\\b"),
180 '\u{c}' => self.out.push_str("\\f"),
181 '\\' | '"' => {
182 self.out.push('\\');
183 self.out.push(c);
184 }
185 c if (' '..='~').contains(&c) => self.out.push(c),
188 c if (c as u32) < 0x20 || (0x7f..=0x9f).contains(&(c as u32)) => {
189 let _ = write!(self.out, "\\u{:04x}", c as u32);
190 }
191 c => self.out.push(c),
192 }
193 }
194 self.out.push('"');
195 if chars.len() > self.limits.max_string_length {
196 let more = chars.len() - self.limits.max_string_length;
197 let _ = write!(
198 self.out,
199 "... {more} more character{}",
200 if more > 1 { "s" } else { "" }
201 );
202 }
203 }
204
205 fn print_object(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
206 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
209 let _ = write!(self.out, "[circular {index}]");
210 return Ok(());
211 }
212 if self.stack.len() >= self.limits.max_depth {
213 let class = self.class_name(object);
214 let _ = write!(self.out, "[{class}]");
215 return Ok(());
216 }
217 self.stack.push(object.clone());
218 let result = self.print_object_body(object);
219 self.stack.pop();
220 result
221 }
222
223 fn class_name(&mut self, object: &Gc<JsObject>) -> String {
226 if object.is_array() {
227 return "Array".to_string();
228 }
229 if object.is_callable() {
230 return "Function".to_string();
231 }
232 if object.typed_array_parts().is_some() {
233 return "TypedArray".to_string();
234 }
235 if object.array_buffer_storage().is_some() {
236 return "ArrayBuffer".to_string();
237 }
238 if let Some(is_set) = object.collection_is_set() {
239 return if is_set { "Set" } else { "Map" }.to_string();
240 }
241 if let Some(boxed) = self.interp.internal_get(object, "_value") {
244 let name = match boxed {
245 Value::Bool(_) => "Boolean",
246 Value::String(_) => "String",
247 Value::Int(_) | Value::Float(_) => "Number",
248 Value::Symbol(_) => "Symbol",
249 _ => "Object",
250 };
251 return name.to_string();
252 }
253 match self.interp.internal_get(object, "_class") {
254 Some(class) => class.to_js_string(),
255 None => "Object".to_string(),
256 }
257 }
258
259 fn print_object_body(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
260 let class = self.class_name(object);
261
262 if object.is_callable() {
264 let name = object
265 .own_property("name")
266 .and_then(|property| property.value)
267 .map(|value| value.to_js_string())
268 .unwrap_or_default();
269 self.out.push_str("[Function ");
270 self.out.push_str(if name.is_empty() {
271 "(anonymous)"
272 } else {
273 &name
274 });
275 self.out.push(']');
276 return Ok(());
277 }
278
279 if let Some(is_set) = object.collection_is_set() {
281 let entries = object.collection_entries().unwrap_or_default();
282 let _ = write!(self.out, "{class}({}) {{ ", entries.len());
283 let mut comma = Comma::First;
284 let mut shown = 0usize;
285 for (key, value) in &entries {
286 if shown >= self.limits.max_item_count {
287 break;
288 }
289 comma.before(&mut self.out);
290 if is_set {
291 self.print_value(key)?;
294 } else {
295 self.print_value(key)?;
296 self.out.push_str(" => ");
297 self.print_value(value)?;
298 }
299 shown += 1;
300 }
301 if shown < entries.len() {
302 Self::print_more(&mut self.out, &mut comma, entries.len() - shown);
303 }
304 self.out.push_str(" }");
305 return Ok(());
306 }
307
308 if let Some(data) = object.regexp() {
312 let _ = write!(self.out, "/{}/{}", regexp_source(&data.source), data.flags);
313 return Ok(());
314 }
315 if class == "Date" {
316 if let Some(value) = self.interp.internal_get(object, "_date_value") {
317 if value.to_number().is_finite() {
320 let _ = write!(self.out, "{}", iso_date(value.to_number()));
321 return Ok(());
322 }
323 }
324 }
325 if class.ends_with("Error") || class == "Error" {
326 self.print_error(object)?;
327 return Ok(());
328 }
329
330 if let Some((_, element, offset, length)) = object.typed_array_parts() {
333 let _ = write!(self.out, "{}({length}) [ ", element.name());
334 let mut comma = Comma::First;
335 let shown = length.min(self.limits.max_item_count);
336 let big = matches!(
340 element,
341 crate::builtins::typedarray::ElementType::BigInt64
342 | crate::builtins::typedarray::ElementType::BigUint64
343 );
344 for index in 0..shown {
345 comma.before(&mut self.out);
346 match object.typed_array_element(offset + index) {
347 Some(Value::BigInt(integer)) if big => {
348 self.out.push_str(&integer.to_decimal_string());
349 }
350 Some(value) if big => self.print_value(&value)?,
351 Some(value) => self.print_value(&value)?,
352 None => self.out.push_str("undefined"),
353 }
354 }
355 if shown < length {
356 Self::print_more(&mut self.out, &mut comma, length - shown);
357 }
358 self.out.push_str(" ]");
359 return Ok(());
360 }
361
362 if object.is_array() {
363 return self.print_array(object);
364 }
365 self.print_plain_object(object, &class)
366 }
367
368 fn print_error(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
370 let read = |interp: &mut Interp<'_>, name: &str| -> String {
374 let key = PropertyKey::String(crate::value::Wtf8::new(name));
375 match interp.get_property_key(object, &key) {
376 Ok(Some(value)) => value.to_js_string(),
377 _ => String::new(),
378 }
379 };
380 let name = read(self.interp, "name");
381 self.out
382 .push_str(if name.is_empty() { "Error" } else { &name });
383 let message = read(self.interp, "message");
384 if !message.is_empty() {
385 self.out.push_str(": ");
386 self.out.push_str(&message);
387 }
388 let stack = {
394 let key = PropertyKey::String(crate::value::Wtf8::new("stack"));
395 match self.interp.get_property_key(object, &key) {
396 Ok(Some(Value::String(text))) => Some(text.to_string_lossy().to_string()),
397 _ => None,
398 }
399 };
400 if let Some(stack) = stack {
401 self.out.push('\n');
402 self.out.push_str(stack.trim_end_matches('\n'));
403 }
404 Ok(())
405 }
406
407 fn print_array(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
411 let length = object.array_length().unwrap_or(0);
412 let mut present: Vec<usize> = Vec::new();
413 for index in 0..length {
414 let key = PropertyKey::String(crate::value::Wtf8::new(index.to_string()));
415 if crate::object::own_property_including_array(object, &key).is_some() {
418 present.push(index);
419 }
420 }
421 let sparse = present
423 .iter()
424 .enumerate()
425 .any(|(expected, index)| *index != expected);
426 self.out.push_str("[ ");
427 let mut comma = Comma::First;
428 for (order, index) in present.iter().enumerate() {
429 if order >= self.limits.max_item_count {
430 Self::print_more(&mut self.out, &mut comma, present.len() - order);
431 self.out.push_str(" ]");
432 return Ok(());
433 }
434 comma.before(&mut self.out);
435 let key = PropertyKey::String(crate::value::Wtf8::new(index.to_string()));
436 if sparse {
437 let _ = write!(self.out, "{index}: ");
438 }
439 match self.interp.get_property_key(object, &key)? {
440 Some(value) => self.print_value(&value)?,
441 None => self.out.push_str("undefined"),
442 }
443 }
444 if !sparse && present.len() < length {
445 let holes = length - present.len();
446 if !present.is_empty() {
449 comma.before(&mut self.out);
450 }
451 let _ = write!(
452 self.out,
453 "<{holes} empty item{}>",
454 if holes > 1 { "s" } else { "" }
455 );
456 }
457 for key in object.own_property_keys_in_definition_order() {
460 let PropertyKey::String(name) = &key else {
461 continue;
462 };
463 let text = name.to_string_lossy();
464 if !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) {
465 continue;
466 }
467 if text == "length" {
468 continue;
469 }
470 let Some(property) = object.own_property_key(&key) else {
471 continue;
472 };
473 if !property.enumerable {
474 continue;
475 }
476 comma.before(&mut self.out);
477 self.print_key(&key);
478 self.out.push_str(": ");
479 if let Some(value) = property.value.clone() {
480 self.print_value(&value)?;
481 }
482 }
483 self.out.push_str(" ]");
484 Ok(())
485 }
486
487 fn print_plain_object(&mut self, object: &Gc<JsObject>, class: &str) -> JsResult<()> {
489 if class != "Object" || object.proxy_state().is_some() {
492 let _ = write!(self.out, "{class} ");
493 }
494 self.out.push_str("{ ");
495 let boxed = matches!(class, "Boolean" | "Number" | "String" | "Symbol")
498 && self.interp.internal_get(object, "_value").is_some();
499 let keys = if boxed {
500 Vec::new()
501 } else {
502 object.own_property_keys_in_definition_order()
503 };
504 let mut comma = Comma::First;
505 let mut shown = 0usize;
506 for key in &keys {
507 let Some(property) = object.own_property_key(key) else {
508 continue;
509 };
510 if !property.enumerable {
511 continue;
512 }
513 if shown >= self.limits.max_item_count {
514 Self::print_more(&mut self.out, &mut comma, keys.len() - shown);
515 break;
516 }
517 shown += 1;
518 comma.before(&mut self.out);
519 self.print_key(key);
520 self.out.push_str(": ");
521 if property.getter.is_some() || property.setter.is_some() {
524 self.out.push_str(
525 match (property.getter.is_some(), property.setter.is_some()) {
526 (true, true) => "[Getter/Setter]",
527 (true, false) => "[Getter]",
528 _ => "[Setter]",
529 },
530 );
531 } else if let Some(value) = property.value.clone() {
532 self.print_value(&value)?;
533 }
534 }
535 self.out.push_str(" }");
536 Ok(())
537 }
538
539 fn print_more(out: &mut String, comma: &mut Comma, rest: usize) {
540 comma.before(out);
541 let _ = write!(
542 out,
543 "... {rest} more item{}",
544 if rest > 1 { "s" } else { "" }
545 );
546 }
547
548 fn print_key(&mut self, key: &PropertyKey) {
551 match key {
552 PropertyKey::Symbol(symbol) => {
553 let _ = write!(
554 self.out,
555 "[Symbol(\"{}\")]",
556 symbol.description().unwrap_or_default()
557 );
558 }
559 PropertyKey::String(text) => {
560 let name = text.to_string_lossy();
561 let bare_index = !name.is_empty()
565 && name.bytes().all(|b| b.is_ascii_digit())
566 && (name == "0" || !name.starts_with('0'));
567 if bare_index || is_identifier(&name) {
568 self.out.push_str(&name);
569 } else {
570 self.print_string(&name);
571 }
572 }
573 }
574 }
575}
576
577fn is_identifier(name: &str) -> bool {
580 let mut chars = name.chars();
581 let Some(first) = chars.next() else {
582 return false;
583 };
584 if !(first.is_ascii_alphabetic() || first == '_' || first == '$') {
585 return false;
586 }
587 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
588}
589
590fn regexp_source(source: &str) -> String {
594 if source.is_empty() {
595 return "(?:)".to_string();
596 }
597 let mut out = String::with_capacity(source.len());
598 let mut chars = source.chars().peekable();
599 while let Some(c) = chars.next() {
600 match c {
601 '/' => out.push_str("\\/"),
602 '\\' => {
604 out.push_str("\\\\");
605 if let Some(next) = chars.next() {
606 out.push(next);
607 }
608 }
609 '\n' => out.push_str("\\n"),
610 '\r' => out.push_str("\\r"),
611 c => out.push(c),
612 }
613 }
614 out
615}
616
617fn iso_date(milliseconds: f64) -> String {
619 if !milliseconds.is_finite() {
620 return "Invalid Date".to_string();
621 }
622 let ms = milliseconds;
626 let seconds_total = (ms / 1000.0).floor();
627 let millis = (ms - seconds_total * 1000.0).round() as i64;
628 let seconds = seconds_total as i64;
629 let days = seconds.div_euclid(86_400);
630 let time_of_day = seconds.rem_euclid(86_400);
631 let (hour, minute, second) = (
632 time_of_day / 3600,
633 (time_of_day % 3600) / 60,
634 time_of_day % 60,
635 );
636 let (year, month, day) = civil_from_days(days);
637 if !(0..=9999).contains(&year) {
638 return format!(
639 "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z"
640 );
641 }
642 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
643}
644
645fn civil_from_days(days: i64) -> (i64, i64, i64) {
647 let z = days + 719_468;
648 let era = z.div_euclid(146_097);
649 let doe = z.rem_euclid(146_097);
650 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
651 let y = yoe + era * 400;
652 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
653 let mp = (5 * doy + 2) / 153;
654 let d = doy - (153 * mp + 2) / 5 + 1;
655 let m = if mp < 10 { mp + 3 } else { mp - 9 };
656 (if m <= 2 { y + 1 } else { y }, m, d)
657}