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/// The three limits a print may have. [`PrintLimits::default`] is the reference's
41/// `JS_PRINT_MAX_*` set, which is what `qjs` uses when it dumps an uncaught exception.
42///
43/// These exist so `JS_PrintValue` can honour the options a host passes: the C API's
44/// `JSPrintValueOptions` is this structure with a different spelling, and a host that sets
45/// `max_depth = 1` expects `{ a: [Object] }` rather than the engine's default expansion.
46/// Keeping them here rather than in the C layer is what makes the limits apply *inside* the
47/// walk instead of truncating the rendered text afterwards — which would cut a string in the
48/// middle of an escape and a structure in the middle of a bracket.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct PrintLimits {
51    /// Objects nested deeper than this print as `[ClassName]`.
52    pub max_depth: usize,
53    /// Characters of a string before the `... N more characters` tail.
54    pub max_string_length: usize,
55    /// Items of a collection before the `... N more items` tail.
56    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
69/// `std.__sprintObject(value)` — the same text `std.__printObject` would write.
70pub fn sprint(interp: &mut Interp<'_>, value: &Value) -> JsResult<String> {
71    sprint_limited(interp, value, PrintLimits::default())
72}
73
74/// [`sprint`] with the limits a caller chooses.
75pub 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    /// The objects being printed, outermost first. A hit is a cycle, reported by index.
94    stack: Vec<Gc<JsObject>>,
95    /// How deep, how long and how many, for this print.
96    limits: PrintLimits,
97}
98
99/// How the next separator should be written, the part of the reference's `comma_state` that
100/// still applies here.
101///
102/// `comma_state` in `quickjs.c` has a third value, `2`, which suppresses the closing ` }`
103/// after a `Function`/`RegExp`/`Date`/`Error`. That case does not arise here because those
104/// classes return before a brace body is opened at all, so there is nothing to suppress.
105#[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            // `js_print_float64` uses `JS_DTOA_MINUS_ZERO`, so `-0` keeps its sign where
130            // `String(-0)` would print `0`. Everything else is the ordinary JS form,
131            // including `1e+21` and `NaN`.
132            Value::Float(number) => {
133                if *number == 0.0 && number.is_sign_negative() {
134                    // `JS_DTOA_MINUS_ZERO`: the one place the printer differs from
135                    // `String()`, which prints `0`.
136                    self.out.push_str("-0");
137                } else {
138                    // Everything else is the ordinary JS form — `1e+21`, `1e-7`,
139                    // `Infinity` — because that is what `js_dtoa(JS_DTOA_FORMAT_FREE)` is.
140                    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            // `Value` is non-exhaustive in spirit: anything else has no reference name.
160            other => {
161                let _ = write!(self.out, "[unknown value {}]", other.type_of());
162            }
163        }
164        Ok(())
165    }
166}
167
168impl Printer<'_, '_> {
169    /// A string in double quotes, with the reference's escaping.
170    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                // Printable ASCII is literal; the C1 range is escaped as well, because it
186                // is invisible in a terminal.
187                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        // A cycle is reported by the depth it was first seen at, which is what makes two
207        // cycles in one value distinguishable.
208        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    /// The class tag, matching `Object.prototype.toString`'s `[object X]` name so the
224    /// printer and the builtin cannot disagree.
225    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        // A boxed primitive names itself after what it wraps: `Object(true)` is
242        // `Boolean {  }`. `_value` is the engine's marker for exactly that.
243        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        // A function prints as one token: `[Function name]`, `(anonymous)` when unnamed.
263        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        // `Map(n) { k => v }` and `Set(n) { v, ... }`.
280        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                    // A `Set`'s record keeps the member in the key slot and `undefined` in
292                    // the value slot.
293                    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        // A `RegExp` prints as its own literal, `Date` as ISO and `Error` as its name, its
309        // message and its stack — the reference's `js_print_regexp`, `get_date_string` and
310        // `js_print_error`. Each prints as one token, so the `{ }` wrapper is skipped.
311        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                // An invalid Date makes `toISOString` throw in the reference, which drops it
318                // to the default object form: `Date {  }`.
319                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        // `Uint8Array(3) [ 1, 2, 255 ]`: the element type names itself and the body is a
331        // plain list of the values in the buffer.
332        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            // `BigInt64Array`/`BigUint64Array` print their elements as plain integers: the
337            // reference formats them with `%lld`/`%llu`, not through the BigInt path, so
338            // there is no `n` suffix.
339            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    /// `name: message` and then the stack, without the trailing newline the reference strips.
369    fn print_error(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
370        // `name` and `message` may be inherited (`TypeError.prototype.name`), so these are
371        // full property reads rather than own-property lookups — the reference's
372        // `get_prop_string` runs the same lookup, getters included.
373        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        // The reference tests `JS_IsString(stack)`, not emptiness: an error built with no
389        // JavaScript frames has an empty trace and still gets the newline, which is why a
390        // module link error prints a blank line where testing emptiness printed none.
391        // A script that sets `stack` to a non-string gets no newline, and `None` here is
392        // that case.
393        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    /// `[ v, v ]`, `<N empty items>` for a hole at the end, or `i: v` pairs when the array
408    /// is sparse (a hole *before* a value), which is how the reference's fast-array and
409    /// shape-property paths differ.
410    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            // A dense array keeps its elements in a vector, not in the property table, so
416            // the property lookup alone finds nothing.
417            if crate::object::own_property_including_array(object, &key).is_some() {
418                present.push(index);
419            }
420        }
421        // Dense iff the values are the first `present.len()` indices.
422        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            // `[ <3 empty items> ]`: the count takes the place of the values, and the
447            // space after `[ ` is already there.
448            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        // Non-index properties on an array still print, as `x: 4`. The reference reaches
458        // the same place: its array branch runs first and the shape loop after it.
459        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    /// `{ key: value, ... }`, with the class name in front when it is not a plain object.
488    fn print_plain_object(&mut self, object: &Gc<JsObject>, class: &str) -> JsResult<()> {
489        // A `Proxy` has the class *name* `Object` but is not `JS_CLASS_OBJECT`, so the
490        // reference prefixes it like any other non-plain class.
491        if class != "Object" || object.proxy_state().is_some() {
492            let _ = write!(self.out, "{class} ");
493        }
494        self.out.push_str("{ ");
495        // A boxed primitive prints as an empty body: its wrapped value and (for `String`)
496        // its index properties are internal in the reference, so `String {  }` is right.
497        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            // An accessor prints as its kind rather than being invoked: printing must not
522            // run a script's getter.
523            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    /// A property name: bare when it is an identifier, quoted otherwise, and
549    /// `[Symbol("x")]` for a symbol key.
550    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                // Two ways a key goes in bare: it is an array index (the reference stores
562                // those as tagged integers and writes them with `%u`), or it is already an
563                // identifier. Everything else is quoted.
564                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
577/// Whether `name` can be written without quotes, matching `is_ascii_ident` in the reference:
578/// ASCII letters, digits, `_` and `$`, not starting with a digit.
579fn 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
590/// A `RegExp` source with `/` escaped, which is what `js_print_regexp` does so the literal
591/// stays readable. An empty pattern prints as `(?:)` rather than `//`, which would be a
592/// comment.
593fn 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            // A `\` in the pattern keeps its escape and gets one of its own.
603            '\\' => {
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
617/// A time value as `toISOString()` writes it, including the `Invalid Date` case.
618fn iso_date(milliseconds: f64) -> String {
619    if !milliseconds.is_finite() {
620        return "Invalid Date".to_string();
621    }
622    // `toISOString` covers years 0000–9999 with four digits; outside that range it throws,
623    // and the reference falls back to the plain-object form. Printing the raw range here
624    // keeps the value readable instead of inventing an error.
625    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
645/// Days since 1970-01-01 to a civil date, by Howard Hinnant's `civil_from_days`.
646fn 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}