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