Skip to main content

quickjs/
print.rs

1//! `std.__sprintObject` / `std.__printObject`: the reference's `JS_PrintValue`.
2//!
3//! # Not `JSON.stringify`, and not `console.log`
4//!
5//! `JS_PrintValue` is quickjs's own dumper, with its own rules, and both of quickjs's
6//! front-ends print through it. It is not JSON: keys are bare when they are identifiers,
7//! values are truncated, cycles are marked, and a `Map` prints as a `Map` rather than as
8//! `{}`. Matching it byte for byte is the whole job, so every rule below is taken from
9//! `js_print_value`/`js_print_object` in `quickjs.c` rather than invented:
10//!
11//! ```text
12//! [ 1, 2, 3 ]              arrays get spaces inside the brackets
13//! [  ]                     and so does an empty one
14//! {  }                     an empty object has two spaces
15//! { a: 1, "a b": 2 }       bare key when it is an identifier, quoted otherwise
16//! { a: { b: [Array] } }    past `max_depth` (2) an object prints as its class name
17//! { self: [circular 0] }   a cycle names the depth it was first seen at
18//! [ 0: 1, 2: 3 ]           a sparse array prints index: value pairs
19//! Map(1) { 1 => 2 }
20//! Set(2) { 1, 2 }
21//! [Function f]
22//! ```
23//!
24//! The defaults are the reference's: `max_depth = 2`, `max_string_length = 1000`,
25//! `max_item_count = 100`. Hitting a limit is visible in the output (`... 3 more items`,
26//! `... 5 more characters`), which is why the numbers have to be exact.
27
28use std::fmt::Write as _;
29
30use crate::builtins::regexp::escaped_source;
31use crate::object::PropertyKey;
32use crate::{Gc, Interp, JsObject, JsResult, Value};
33
34/// How deep objects are expanded before they print as `[ClassName]`.
35const MAX_DEPTH: usize = 2;
36/// How many characters of a string are printed.
37const MAX_STRING_LENGTH: usize = 1000;
38/// How many items of a collection are printed.
39const MAX_ITEM_COUNT: usize = 100;
40
41/// The three limits a print may have. [`PrintLimits::default`] is the reference's
42/// `JS_PRINT_MAX_*` set, which is what `qjs` uses when it dumps an uncaught exception.
43///
44/// These exist so `JS_PrintValue` can honour the options a host passes: the C API's
45/// `JSPrintValueOptions` is this structure with a different spelling, and a host that sets
46/// `max_depth = 1` expects `{ a: [Object] }` rather than the engine's default expansion.
47/// Keeping them here rather than in the C layer is what makes the limits apply *inside* the
48/// walk instead of truncating the rendered text afterwards — which would cut a string in the
49/// middle of an escape and a structure in the middle of a bracket.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub struct PrintLimits {
52    /// Objects nested deeper than this print as `[ClassName]`.
53    pub max_depth: usize,
54    /// Characters of a string before the `... N more characters` tail.
55    pub max_string_length: usize,
56    /// Items of a collection before the `... N more items` tail.
57    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
70/// `std.__sprintObject(value)` — the same text `std.__printObject` would write.
71pub fn sprint(interp: &mut Interp<'_>, value: &Value) -> JsResult<String> {
72    sprint_limited(interp, value, PrintLimits::default())
73}
74
75/// [`sprint`] with the limits a caller chooses.
76pub 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    /// The objects being printed, outermost first. A hit is a cycle, reported by index.
95    stack: Vec<Gc<JsObject>>,
96    /// How deep, how long and how many, for this print.
97    limits: PrintLimits,
98}
99
100/// How the next separator should be written, the part of the reference's `comma_state` that
101/// still applies here.
102///
103/// `comma_state` in `quickjs.c` has a third value, `2`, which suppresses the closing ` }`
104/// after a `Function`/`RegExp`/`Date`/`Error`. That case does not arise here because those
105/// classes return before a brace body is opened at all, so there is nothing to suppress.
106#[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            // `js_print_float64` uses `JS_DTOA_MINUS_ZERO`, so `-0` keeps its sign where
131            // `String(-0)` would print `0`. Everything else is the ordinary JS form,
132            // including `1e+21` and `NaN`.
133            Value::Float(number) => {
134                if *number == 0.0 && number.is_sign_negative() {
135                    // `JS_DTOA_MINUS_ZERO`: the one place the printer differs from
136                    // `String()`, which prints `0`.
137                    self.out.push_str("-0");
138                } else {
139                    // Everything else is the ordinary JS form — `1e+21`, `1e-7`,
140                    // `Infinity` — because that is what `js_dtoa(JS_DTOA_FORMAT_FREE)` is.
141                    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            // `Value` is non-exhaustive in spirit: anything else has no reference name.
161            other => {
162                let _ = write!(self.out, "[unknown value {}]", other.type_of());
163            }
164        }
165        Ok(())
166    }
167}
168
169impl Printer<'_, '_> {
170    /// A string in double quotes, with the reference's escaping.
171    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                // Printable ASCII is literal; the C1 range is escaped as well, because it
187                // is invisible in a terminal.
188                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        // A cycle is reported by the depth it was first seen at, which is what makes two
208        // cycles in one value distinguishable.
209        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    /// The class tag, matching `Object.prototype.toString`'s `[object X]` name so the
225    /// printer and the builtin cannot disagree.
226    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        // A boxed primitive names itself after what it wraps: `Object(true)` is
243        // `Boolean {  }`. `_value` is the engine's marker for exactly that.
244        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        // A function prints as one token: `[Function name]`, `(anonymous)` when unnamed.
264        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        // `Map(n) { k => v }` and `Set(n) { v, ... }`.
281        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                    // A `Set`'s record keeps the member in the key slot and `undefined` in
293                    // the value slot.
294                    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        // A `RegExp` prints as its own literal, `Date` as ISO and `Error` as its name, its
310        // message and its stack — the reference's `js_print_regexp`, `get_date_string` and
311        // `js_print_error`. Each prints as one token, so the `{ }` wrapper is skipped.
312        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                // An invalid Date makes `toISOString` throw in the reference, which drops it
324                // to the default object form: `Date {  }`.
325                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        // `Uint8Array(3) [ 1, 2, 255 ]`: the element type names itself and the body is a
337        // plain list of the values in the buffer.
338        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            // `BigInt64Array`/`BigUint64Array` print their elements as plain integers: the
343            // reference formats them with `%lld`/`%llu`, not through the BigInt path, so
344            // there is no `n` suffix.
345            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    /// `name: message` and then the stack, without the trailing newline the reference strips.
375    fn print_error(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
376        // `name` and `message` may be inherited (`TypeError.prototype.name`), so these are
377        // full property reads rather than own-property lookups — the reference's
378        // `get_prop_string` runs the same lookup, getters included.
379        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        // The reference tests `JS_IsString(stack)`, not emptiness: an error built with no
395        // JavaScript frames has an empty trace and still gets the newline, which is why a
396        // module link error prints a blank line where testing emptiness printed none.
397        // A script that sets `stack` to a non-string gets no newline, and `None` here is
398        // that case.
399        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    /// `[ v, v ]`, `<N empty items>` for a hole at the end, or `i: v` pairs when the array
414    /// is sparse (a hole *before* a value), which is how the reference's fast-array and
415    /// shape-property paths differ.
416    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            // A dense array keeps its elements in a vector, not in the property table, so
422            // the property lookup alone finds nothing.
423            if crate::object::own_property_including_array(object, &key).is_some() {
424                present.push(index);
425            }
426        }
427        // Dense iff the values are the first `present.len()` indices.
428        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            // `[ <3 empty items> ]`: the count takes the place of the values, and the
453            // space after `[ ` is already there.
454            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        // Non-index properties on an array still print, as `x: 4`. The reference reaches
464        // the same place: its array branch runs first and the shape loop after it.
465        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    /// `{ key: value, ... }`, with the class name in front when it is not a plain object.
494    fn print_plain_object(&mut self, object: &Gc<JsObject>, class: &str) -> JsResult<()> {
495        // A `Proxy` has the class *name* `Object` but is not `JS_CLASS_OBJECT`, so the
496        // reference prefixes it like any other non-plain class.
497        if class != "Object" || object.proxy_state().is_some() {
498            let _ = write!(self.out, "{class} ");
499        }
500        self.out.push_str("{ ");
501        // A boxed primitive prints as an empty body: its wrapped value and (for `String`)
502        // its index properties are internal in the reference, so `String {  }` is right.
503        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            // An accessor prints as its kind rather than being invoked: printing must not
528            // run a script's getter.
529            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    /// A property name: bare when it is an identifier, quoted otherwise, and
555    /// `[Symbol("x")]` for a symbol key.
556    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                // Two ways a key goes in bare: it is an array index (the reference stores
568                // those as tagged integers and writes them with `%u`), or it is already an
569                // identifier. Everything else is quoted.
570                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
583/// Whether `name` can be written without quotes, matching `is_ascii_ident` in the reference:
584/// ASCII letters, digits, `_` and `$`, not starting with a digit.
585fn 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
596/// A time value as `toISOString()` writes it, including the `Invalid Date` case.
597fn iso_date(milliseconds: f64) -> String {
598    if !milliseconds.is_finite() {
599        return "Invalid Date".to_string();
600    }
601    // `toISOString` covers years 0000–9999 with four digits; outside that range it throws,
602    // and the reference falls back to the plain-object form. Printing the raw range here
603    // keeps the value readable instead of inventing an error.
604    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
624/// Days since 1970-01-01 to a civil date, by Howard Hinnant's `civil_from_days`.
625fn 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}