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::object::PropertyKey;
31use crate::{Gc, Interp, JsObject, JsResult, Value};
32
33/// How deep objects are expanded before they print as `[ClassName]`.
34const MAX_DEPTH: usize = 2;
35/// How many characters of a string are printed.
36const MAX_STRING_LENGTH: usize = 1000;
37/// How many items of a collection are printed.
38const MAX_ITEM_COUNT: usize = 100;
39
40/// `std.__sprintObject(value)` — the same text `std.__printObject` would write.
41pub fn sprint(interp: &mut Interp<'_>, value: &Value) -> JsResult<String> {
42    let mut printer = Printer {
43        interp,
44        out: String::new(),
45        stack: Vec::new(),
46    };
47    printer.print_value(value)?;
48    Ok(printer.out)
49}
50
51struct Printer<'i, 'a> {
52    interp: &'i mut Interp<'a>,
53    out: String,
54    /// The objects being printed, outermost first. A hit is a cycle, reported by index.
55    stack: Vec<Gc<JsObject>>,
56}
57
58/// How the next separator should be written, the part of the reference's `comma_state` that
59/// still applies here.
60///
61/// `comma_state` in `quickjs.c` has a third value, `2`, which suppresses the closing ` }`
62/// after a `Function`/`RegExp`/`Date`/`Error`. That case does not arise here because those
63/// classes return before a brace body is opened at all, so there is nothing to suppress.
64#[derive(Clone, Copy, PartialEq, Eq)]
65enum Comma {
66    First,
67    Next,
68}
69
70impl Comma {
71    fn before(&mut self, out: &mut String) {
72        if *self == Comma::Next {
73            out.push_str(", ");
74        }
75        *self = Comma::Next;
76    }
77}
78
79impl Printer<'_, '_> {
80    fn print_value(&mut self, value: &Value) -> JsResult<()> {
81        match value {
82            Value::Undefined => self.out.push_str("undefined"),
83            Value::Null => self.out.push_str("null"),
84            Value::Bool(flag) => self.out.push_str(if *flag { "true" } else { "false" }),
85            Value::Int(number) => {
86                let _ = write!(self.out, "{number}");
87            }
88            // `js_print_float64` uses `JS_DTOA_MINUS_ZERO`, so `-0` keeps its sign where
89            // `String(-0)` would print `0`. Everything else is the ordinary JS form,
90            // including `1e+21` and `NaN`.
91            Value::Float(number) => {
92                if *number == 0.0 && number.is_sign_negative() {
93                    // `JS_DTOA_MINUS_ZERO`: the one place the printer differs from
94                    // `String()`, which prints `0`.
95                    self.out.push_str("-0");
96                } else {
97                    // Everything else is the ordinary JS form — `1e+21`, `1e-7`,
98                    // `Infinity` — because that is what `js_dtoa(JS_DTOA_FORMAT_FREE)` is.
99                    self.out.push_str(&value.to_js_string());
100                }
101            }
102            Value::BigInt(big) => {
103                self.out.push_str(&big.to_decimal_string());
104                self.out.push('n');
105            }
106            Value::Symbol(symbol) => {
107                let _ = write!(
108                    self.out,
109                    "Symbol({:?})",
110                    symbol.description().unwrap_or_default()
111                );
112            }
113            Value::String(_) => {
114                let text = value.to_js_string();
115                self.print_string(&text);
116            }
117            Value::Object(object) => self.print_object(object)?,
118            // `Value` is non-exhaustive in spirit: anything else has no reference name.
119            other => {
120                let _ = write!(self.out, "[unknown value {}]", other.type_of());
121            }
122        }
123        Ok(())
124    }
125}
126
127impl Printer<'_, '_> {
128    /// A string in double quotes, with the reference's escaping.
129    fn print_string(&mut self, text: &str) {
130        self.out.push('"');
131        let chars: Vec<char> = text.chars().collect();
132        let shown = chars.len().min(MAX_STRING_LENGTH);
133        for &c in &chars[..shown] {
134            match c {
135                '\t' => self.out.push_str("\\t"),
136                '\r' => self.out.push_str("\\r"),
137                '\n' => self.out.push_str("\\n"),
138                '\u{8}' => self.out.push_str("\\b"),
139                '\u{c}' => self.out.push_str("\\f"),
140                '\\' | '"' => {
141                    self.out.push('\\');
142                    self.out.push(c);
143                }
144                // Printable ASCII is literal; the C1 range is escaped as well, because it
145                // is invisible in a terminal.
146                c if (' '..='~').contains(&c) => self.out.push(c),
147                c if (c as u32) < 0x20 || (0x7f..=0x9f).contains(&(c as u32)) => {
148                    let _ = write!(self.out, "\\u{:04x}", c as u32);
149                }
150                c => self.out.push(c),
151            }
152        }
153        self.out.push('"');
154        if chars.len() > MAX_STRING_LENGTH {
155            let more = chars.len() - MAX_STRING_LENGTH;
156            let _ = write!(
157                self.out,
158                "... {more} more character{}",
159                if more > 1 { "s" } else { "" }
160            );
161        }
162    }
163
164    fn print_object(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
165        // A cycle is reported by the depth it was first seen at, which is what makes two
166        // cycles in one value distinguishable.
167        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
168            let _ = write!(self.out, "[circular {index}]");
169            return Ok(());
170        }
171        if self.stack.len() >= MAX_DEPTH {
172            let class = self.class_name(object);
173            let _ = write!(self.out, "[{class}]");
174            return Ok(());
175        }
176        self.stack.push(object.clone());
177        let result = self.print_object_body(object);
178        self.stack.pop();
179        result
180    }
181
182    /// The class tag, matching `Object.prototype.toString`'s `[object X]` name so the
183    /// printer and the builtin cannot disagree.
184    fn class_name(&mut self, object: &Gc<JsObject>) -> String {
185        if object.is_array() {
186            return "Array".to_string();
187        }
188        if object.is_callable() {
189            return "Function".to_string();
190        }
191        if object.typed_array_parts().is_some() {
192            return "TypedArray".to_string();
193        }
194        if object.array_buffer_storage().is_some() {
195            return "ArrayBuffer".to_string();
196        }
197        if let Some(is_set) = object.collection_is_set() {
198            return if is_set { "Set" } else { "Map" }.to_string();
199        }
200        // A boxed primitive names itself after what it wraps: `Object(true)` is
201        // `Boolean {  }`. `_value` is the engine's marker for exactly that.
202        if let Some(boxed) = self.interp.internal_get(object, "_value") {
203            let name = match boxed {
204                Value::Bool(_) => "Boolean",
205                Value::String(_) => "String",
206                Value::Int(_) | Value::Float(_) => "Number",
207                Value::Symbol(_) => "Symbol",
208                _ => "Object",
209            };
210            return name.to_string();
211        }
212        match self.interp.internal_get(object, "_class") {
213            Some(class) => class.to_js_string(),
214            None => "Object".to_string(),
215        }
216    }
217
218    fn print_object_body(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
219        let class = self.class_name(object);
220
221        // A function prints as one token: `[Function name]`, `(anonymous)` when unnamed.
222        if object.is_callable() {
223            let name = object
224                .own_property("name")
225                .and_then(|property| property.value)
226                .map(|value| value.to_js_string())
227                .unwrap_or_default();
228            self.out.push_str("[Function ");
229            self.out.push_str(if name.is_empty() {
230                "(anonymous)"
231            } else {
232                &name
233            });
234            self.out.push(']');
235            return Ok(());
236        }
237
238        // `Map(n) { k => v }` and `Set(n) { v, ... }`.
239        if let Some(is_set) = object.collection_is_set() {
240            let entries = object.collection_entries().unwrap_or_default();
241            let _ = write!(self.out, "{class}({}) {{ ", entries.len());
242            let mut comma = Comma::First;
243            let mut shown = 0usize;
244            for (key, value) in &entries {
245                if shown >= MAX_ITEM_COUNT {
246                    break;
247                }
248                comma.before(&mut self.out);
249                if is_set {
250                    // A `Set`'s record keeps the member in the key slot and `undefined` in
251                    // the value slot.
252                    self.print_value(key)?;
253                } else {
254                    self.print_value(key)?;
255                    self.out.push_str(" => ");
256                    self.print_value(value)?;
257                }
258                shown += 1;
259            }
260            if shown < entries.len() {
261                Self::print_more(&mut self.out, &mut comma, entries.len() - shown);
262            }
263            self.out.push_str(" }");
264            return Ok(());
265        }
266
267        // A `RegExp` prints as its own literal, `Date` as ISO and `Error` as its name, its
268        // message and its stack — the reference's `js_print_regexp`, `get_date_string` and
269        // `js_print_error`. Each prints as one token, so the `{ }` wrapper is skipped.
270        if let Some(data) = object.regexp() {
271            let _ = write!(self.out, "/{}/{}", regexp_source(&data.source), data.flags);
272            return Ok(());
273        }
274        if class == "Date" {
275            if let Some(value) = self.interp.internal_get(object, "_date_value") {
276                // An invalid Date makes `toISOString` throw in the reference, which drops it
277                // to the default object form: `Date {  }`.
278                if value.to_number().is_finite() {
279                    let _ = write!(self.out, "{}", iso_date(value.to_number()));
280                    return Ok(());
281                }
282            }
283        }
284        if class.ends_with("Error") || class == "Error" {
285            self.print_error(object)?;
286            return Ok(());
287        }
288
289        // `Uint8Array(3) [ 1, 2, 255 ]`: the element type names itself and the body is a
290        // plain list of the values in the buffer.
291        if let Some((_, element, offset, length)) = object.typed_array_parts() {
292            let _ = write!(self.out, "{}({length}) [ ", element.name());
293            let mut comma = Comma::First;
294            let shown = length.min(MAX_ITEM_COUNT);
295            // `BigInt64Array`/`BigUint64Array` print their elements as plain integers: the
296            // reference formats them with `%lld`/`%llu`, not through the BigInt path, so
297            // there is no `n` suffix.
298            let big = matches!(
299                element,
300                crate::builtins::typedarray::ElementType::BigInt64
301                    | crate::builtins::typedarray::ElementType::BigUint64
302            );
303            for index in 0..shown {
304                comma.before(&mut self.out);
305                match object.typed_array_element(offset + index) {
306                    Some(Value::BigInt(integer)) if big => {
307                        self.out.push_str(&integer.to_decimal_string());
308                    }
309                    Some(value) if big => self.print_value(&value)?,
310                    Some(value) => self.print_value(&value)?,
311                    None => self.out.push_str("undefined"),
312                }
313            }
314            if shown < length {
315                Self::print_more(&mut self.out, &mut comma, length - shown);
316            }
317            self.out.push_str(" ]");
318            return Ok(());
319        }
320
321        if object.is_array() {
322            return self.print_array(object);
323        }
324        self.print_plain_object(object, &class)
325    }
326
327    /// `name: message` and then the stack, without the trailing newline the reference strips.
328    fn print_error(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
329        // `name` and `message` may be inherited (`TypeError.prototype.name`), so these are
330        // full property reads rather than own-property lookups — the reference's
331        // `get_prop_string` runs the same lookup, getters included.
332        let read = |interp: &mut Interp<'_>, name: &str| -> String {
333            let key = PropertyKey::String(crate::value::Wtf8::new(name));
334            match interp.get_property_key(object, &key) {
335                Ok(Some(value)) => value.to_js_string(),
336                _ => String::new(),
337            }
338        };
339        let name = read(self.interp, "name");
340        self.out
341            .push_str(if name.is_empty() { "Error" } else { &name });
342        let message = read(self.interp, "message");
343        if !message.is_empty() {
344            self.out.push_str(": ");
345            self.out.push_str(&message);
346        }
347        // The reference tests `JS_IsString(stack)`, not emptiness: an error built with no
348        // JavaScript frames has an empty trace and still gets the newline, which is why a
349        // module link error prints a blank line where testing emptiness printed none.
350        // A script that sets `stack` to a non-string gets no newline, and `None` here is
351        // that case.
352        let stack = {
353            let key = PropertyKey::String(crate::value::Wtf8::new("stack"));
354            match self.interp.get_property_key(object, &key) {
355                Ok(Some(Value::String(text))) => Some(text.to_string_lossy().to_string()),
356                _ => None,
357            }
358        };
359        if let Some(stack) = stack {
360            self.out.push('\n');
361            self.out.push_str(stack.trim_end_matches('\n'));
362        }
363        Ok(())
364    }
365
366    /// `[ v, v ]`, `<N empty items>` for a hole at the end, or `i: v` pairs when the array
367    /// is sparse (a hole *before* a value), which is how the reference's fast-array and
368    /// shape-property paths differ.
369    fn print_array(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
370        let length = object.array_length().unwrap_or(0);
371        let mut present: Vec<usize> = Vec::new();
372        for index in 0..length {
373            let key = PropertyKey::String(crate::value::Wtf8::new(index.to_string()));
374            // A dense array keeps its elements in a vector, not in the property table, so
375            // the property lookup alone finds nothing.
376            if crate::object::own_property_including_array(object, &key).is_some() {
377                present.push(index);
378            }
379        }
380        // Dense iff the values are the first `present.len()` indices.
381        let sparse = present
382            .iter()
383            .enumerate()
384            .any(|(expected, index)| *index != expected);
385        self.out.push_str("[ ");
386        let mut comma = Comma::First;
387        for (order, index) in present.iter().enumerate() {
388            if order >= MAX_ITEM_COUNT {
389                Self::print_more(&mut self.out, &mut comma, present.len() - order);
390                self.out.push_str(" ]");
391                return Ok(());
392            }
393            comma.before(&mut self.out);
394            let key = PropertyKey::String(crate::value::Wtf8::new(index.to_string()));
395            if sparse {
396                let _ = write!(self.out, "{index}: ");
397            }
398            match self.interp.get_property_key(object, &key)? {
399                Some(value) => self.print_value(&value)?,
400                None => self.out.push_str("undefined"),
401            }
402        }
403        if !sparse && present.len() < length {
404            let holes = length - present.len();
405            // `[ <3 empty items> ]`: the count takes the place of the values, and the
406            // space after `[ ` is already there.
407            if !present.is_empty() {
408                comma.before(&mut self.out);
409            }
410            let _ = write!(
411                self.out,
412                "<{holes} empty item{}>",
413                if holes > 1 { "s" } else { "" }
414            );
415        }
416        // Non-index properties on an array still print, as `x: 4`. The reference reaches
417        // the same place: its array branch runs first and the shape loop after it.
418        for key in object.own_property_keys_in_definition_order() {
419            let PropertyKey::String(name) = &key else {
420                continue;
421            };
422            let text = name.to_string_lossy();
423            if !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) {
424                continue;
425            }
426            if text == "length" {
427                continue;
428            }
429            let Some(property) = object.own_property_key(&key) else {
430                continue;
431            };
432            if !property.enumerable {
433                continue;
434            }
435            comma.before(&mut self.out);
436            self.print_key(&key);
437            self.out.push_str(": ");
438            if let Some(value) = property.value.clone() {
439                self.print_value(&value)?;
440            }
441        }
442        self.out.push_str(" ]");
443        Ok(())
444    }
445
446    /// `{ key: value, ... }`, with the class name in front when it is not a plain object.
447    fn print_plain_object(&mut self, object: &Gc<JsObject>, class: &str) -> JsResult<()> {
448        // A `Proxy` has the class *name* `Object` but is not `JS_CLASS_OBJECT`, so the
449        // reference prefixes it like any other non-plain class.
450        if class != "Object" || object.proxy_state().is_some() {
451            let _ = write!(self.out, "{class} ");
452        }
453        self.out.push_str("{ ");
454        // A boxed primitive prints as an empty body: its wrapped value and (for `String`)
455        // its index properties are internal in the reference, so `String {  }` is right.
456        let boxed = matches!(class, "Boolean" | "Number" | "String" | "Symbol")
457            && self.interp.internal_get(object, "_value").is_some();
458        let keys = if boxed {
459            Vec::new()
460        } else {
461            object.own_property_keys_in_definition_order()
462        };
463        let mut comma = Comma::First;
464        let mut shown = 0usize;
465        for key in &keys {
466            let Some(property) = object.own_property_key(key) else {
467                continue;
468            };
469            if !property.enumerable {
470                continue;
471            }
472            if shown >= MAX_ITEM_COUNT {
473                Self::print_more(&mut self.out, &mut comma, keys.len() - shown);
474                break;
475            }
476            shown += 1;
477            comma.before(&mut self.out);
478            self.print_key(key);
479            self.out.push_str(": ");
480            // An accessor prints as its kind rather than being invoked: printing must not
481            // run a script's getter.
482            if property.getter.is_some() || property.setter.is_some() {
483                self.out.push_str(
484                    match (property.getter.is_some(), property.setter.is_some()) {
485                        (true, true) => "[Getter/Setter]",
486                        (true, false) => "[Getter]",
487                        _ => "[Setter]",
488                    },
489                );
490            } else if let Some(value) = property.value.clone() {
491                self.print_value(&value)?;
492            }
493        }
494        self.out.push_str(" }");
495        Ok(())
496    }
497
498    fn print_more(out: &mut String, comma: &mut Comma, rest: usize) {
499        comma.before(out);
500        let _ = write!(
501            out,
502            "... {rest} more item{}",
503            if rest > 1 { "s" } else { "" }
504        );
505    }
506
507    /// A property name: bare when it is an identifier, quoted otherwise, and
508    /// `[Symbol("x")]` for a symbol key.
509    fn print_key(&mut self, key: &PropertyKey) {
510        match key {
511            PropertyKey::Symbol(symbol) => {
512                let _ = write!(
513                    self.out,
514                    "[Symbol(\"{}\")]",
515                    symbol.description().unwrap_or_default()
516                );
517            }
518            PropertyKey::String(text) => {
519                let name = text.to_string_lossy();
520                // Two ways a key goes in bare: it is an array index (the reference stores
521                // those as tagged integers and writes them with `%u`), or it is already an
522                // identifier. Everything else is quoted.
523                let bare_index = !name.is_empty()
524                    && name.bytes().all(|b| b.is_ascii_digit())
525                    && (name == "0" || !name.starts_with('0'));
526                if bare_index || is_identifier(&name) {
527                    self.out.push_str(&name);
528                } else {
529                    self.print_string(&name);
530                }
531            }
532        }
533    }
534}
535
536/// Whether `name` can be written without quotes, matching `is_ascii_ident` in the reference:
537/// ASCII letters, digits, `_` and `$`, not starting with a digit.
538fn is_identifier(name: &str) -> bool {
539    let mut chars = name.chars();
540    let Some(first) = chars.next() else {
541        return false;
542    };
543    if !(first.is_ascii_alphabetic() || first == '_' || first == '$') {
544        return false;
545    }
546    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
547}
548
549/// A `RegExp` source with `/` escaped, which is what `js_print_regexp` does so the literal
550/// stays readable. An empty pattern prints as `(?:)` rather than `//`, which would be a
551/// comment.
552fn regexp_source(source: &str) -> String {
553    if source.is_empty() {
554        return "(?:)".to_string();
555    }
556    let mut out = String::with_capacity(source.len());
557    let mut chars = source.chars().peekable();
558    while let Some(c) = chars.next() {
559        match c {
560            '/' => out.push_str("\\/"),
561            // A `\` in the pattern keeps its escape and gets one of its own.
562            '\\' => {
563                out.push_str("\\\\");
564                if let Some(next) = chars.next() {
565                    out.push(next);
566                }
567            }
568            '\n' => out.push_str("\\n"),
569            '\r' => out.push_str("\\r"),
570            c => out.push(c),
571        }
572    }
573    out
574}
575
576/// A time value as `toISOString()` writes it, including the `Invalid Date` case.
577fn iso_date(milliseconds: f64) -> String {
578    if !milliseconds.is_finite() {
579        return "Invalid Date".to_string();
580    }
581    // `toISOString` covers years 0000–9999 with four digits; outside that range it throws,
582    // and the reference falls back to the plain-object form. Printing the raw range here
583    // keeps the value readable instead of inventing an error.
584    let ms = milliseconds;
585    let seconds_total = (ms / 1000.0).floor();
586    let millis = (ms - seconds_total * 1000.0).round() as i64;
587    let seconds = seconds_total as i64;
588    let days = seconds.div_euclid(86_400);
589    let time_of_day = seconds.rem_euclid(86_400);
590    let (hour, minute, second) = (
591        time_of_day / 3600,
592        (time_of_day % 3600) / 60,
593        time_of_day % 60,
594    );
595    let (year, month, day) = civil_from_days(days);
596    if !(0..=9999).contains(&year) {
597        return format!(
598            "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z"
599        );
600    }
601    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
602}
603
604/// Days since 1970-01-01 to a civil date, by Howard Hinnant's `civil_from_days`.
605fn civil_from_days(days: i64) -> (i64, i64, i64) {
606    let z = days + 719_468;
607    let era = z.div_euclid(146_097);
608    let doe = z.rem_euclid(146_097);
609    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
610    let y = yoe + era * 400;
611    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
612    let mp = (5 * doy + 2) / 153;
613    let d = doy - (153 * mp + 2) / 5 + 1;
614    let m = if mp < 10 { mp + 3 } else { mp - 9 };
615    (if m <= 2 { y + 1 } else { y }, m, d)
616}