Skip to main content

nodejs/stdlib/
console.rs

1//! Node `console` module (`require('console')`), sharing the exact rendering the
2//! global `console.*` uses: every argument is run through `JsHost::console_format`
3//! (strings verbatim, everything else via `util.inspect`) and space-joined — the
4//! same pipeline `builtins::print_line` drives — so module output is identical to
5//! the global. `log`/`info`/`debug` go to stdout; `error`/`warn`/`trace`/`assert`
6//! to stderr. `count`, `group` and `time` keep per-thread state here (a monotonic
7//! `Instant` backs the timers, so `timeEnd` reports a real elapsed duration).
8
9use crate::host::{with_host, JsObj};
10use fusevm::Value;
11use indexmap::IndexMap;
12use std::cell::{Cell, RefCell};
13use std::collections::HashMap;
14use std::io::IsTerminal;
15use std::time::Instant;
16
17pub const METHODS: &[&str] = &[
18    "log",
19    "info",
20    "debug",
21    "error",
22    "warn",
23    "dir",
24    "dirxml",
25    "trace",
26    "assert",
27    "count",
28    "countReset",
29    "group",
30    "groupCollapsed",
31    "groupEnd",
32    "time",
33    "timeEnd",
34    "timeLog",
35    "table",
36    "clear",
37    "timeStamp",
38    "profile",
39    "profileEnd",
40];
41
42/// The instance method names for a `console.Console` object (`@@native = "Console"`),
43/// wired by the parent `mod.rs`. Identical to the free-function surface.
44pub const CONSOLE_METHODS: &[&str] = METHODS;
45
46thread_local! {
47    /// Current `console.group` nesting depth (2 spaces per level).
48    static GROUP_DEPTH: Cell<usize> = const { Cell::new(0) };
49    /// `console.count` label → invocation tally.
50    static COUNTS: RefCell<HashMap<String, u64>> = RefCell::new(HashMap::new());
51    /// `console.time` label → start instant.
52    static TIMERS: RefCell<HashMap<String, Instant>> = RefCell::new(HashMap::new());
53    /// Active output sink `(stdout, stderr)` for a `Console` instance call. When
54    /// set, `emit` writes formatted lines to these streams instead of the process
55    /// std streams, so a `new Console({stdout, stderr})` honors custom writables.
56    static SINK: RefCell<Option<(Value, Value)>> = const { RefCell::new(None) };
57}
58
59pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
60    Some(match method {
61        "log" | "info" | "debug" | "dirxml" => {
62            // A throwing directive aborts the call BEFORE anything is written,
63            // which is what node does: `console.log('%j', 1n)` prints no line.
64            match format_args(args) {
65                Ok(s) => {
66                    emit(&s, false);
67                    Ok(Value::Undef)
68                }
69                Err(e) => Err(e),
70            }
71        }
72        "error" | "warn" => match format_args(args) {
73            Ok(s) => {
74                emit(&s, true);
75                Ok(Value::Undef)
76            }
77            Err(e) => Err(e),
78        },
79        // `console.dir(obj, options)` is lib/internal/console/constructor.js's
80        // `inspect(object, { customInspect: false, ...options })`: a value's
81        // own `[util.inspect.custom]` is skipped unless the options turn it
82        // back on, and every other inspect option (`depth`, `sorted`, …) is
83        // honoured.
84        "dir" => {
85            let opts = dir_options(args.get(1));
86            let target = args.first().cloned().unwrap_or(Value::Undef);
87            match crate::stdlib::util::call("inspect", &[target, opts]) {
88                Some(Ok(s)) => {
89                    emit(&with_host(|h| h.str_of(&s)), false);
90                    Ok(Value::Undef)
91                }
92                Some(Err(e)) => Err(e),
93                None => Ok(Value::Undef),
94            }
95        }
96        // `console.trace` prints a "Trace:"-prefixed message to stderr. A full
97        // captured stack is not attached here (no cheap synchronous stack source
98        // at this layer); the message content matches Node.
99        "trace" => {
100            let msg = match format_args(args) {
101                Ok(s) => s,
102                Err(e) => return Some(Err(e)),
103            };
104            let line = if msg.is_empty() {
105                "Trace".to_string()
106            } else {
107                format!("Trace: {msg}")
108            };
109            emit(&line, true);
110            Ok(Value::Undef)
111        }
112        // `console.assert(cond, ...msg)`: on a falsy condition, write
113        // "Assertion failed" (plus any message) to stderr; otherwise no output.
114        "assert" => {
115            let ok = with_host(|h| h.truthy(&args.first().cloned().unwrap_or(Value::Undef)));
116            if !ok {
117                let msg = match format_args(&args[1.min(args.len())..]) {
118                    Ok(s) => s,
119                    Err(e) => return Some(Err(e)),
120                };
121                let line = if msg.is_empty() {
122                    "Assertion failed".to_string()
123                } else {
124                    format!("Assertion failed: {msg}")
125                };
126                emit(&line, true);
127            }
128            Ok(Value::Undef)
129        }
130        "count" => {
131            let label = label_arg(args, "default");
132            let n = COUNTS.with(|c| {
133                let mut m = c.borrow_mut();
134                let e = m.entry(label.clone()).or_insert(0);
135                *e += 1;
136                *e
137            });
138            emit(&format!("{label}: {n}"), false);
139            Ok(Value::Undef)
140        }
141        "countReset" => {
142            let label = label_arg(args, "default");
143            COUNTS.with(|c| c.borrow_mut().remove(&label));
144            Ok(Value::Undef)
145        }
146        // `group`/`groupCollapsed` print their label (if any) then indent all
147        // subsequent output one level; `groupEnd` pops a level.
148        "group" | "groupCollapsed" => {
149            if !args.is_empty() {
150                match format_args(args) {
151                    Ok(s) => emit(&s, false),
152                    Err(e) => return Some(Err(e)),
153                }
154            }
155            GROUP_DEPTH.with(|d| d.set(d.get() + 1));
156            Ok(Value::Undef)
157        }
158        "groupEnd" => {
159            GROUP_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
160            Ok(Value::Undef)
161        }
162        "time" => {
163            let label = label_arg(args, "default");
164            TIMERS.with(|t| t.borrow_mut().insert(label, Instant::now()));
165            Ok(Value::Undef)
166        }
167        "timeEnd" | "timeLog" => {
168            let label = label_arg(args, "default");
169            let elapsed = TIMERS.with(|t| {
170                let m = t.borrow();
171                m.get(&label).map(|start| start.elapsed())
172            });
173            match elapsed {
174                Some(d) => {
175                    let ms = d.as_secs_f64() * 1000.0;
176                    // Any extra args after the label are appended, matching Node.
177                    let extra = if args.len() > 1 {
178                        match format_args(&args[1..]) {
179                            Ok(s) => format!(" {s}"),
180                            Err(e) => return Some(Err(e)),
181                        }
182                    } else {
183                        String::new()
184                    };
185                    emit(&format!("{label}: {ms:.3}ms{extra}"), false);
186                    if method == "timeEnd" {
187                        TIMERS.with(|t| t.borrow_mut().remove(&label));
188                    }
189                }
190                None => emit(
191                    &format!("Warning: No such label '{label}' for console.{method}()"),
192                    true,
193                ),
194            }
195            Ok(Value::Undef)
196        }
197        // `console.table(data[, properties])`: render an ASCII box table. Non-tabular
198        // input (a primitive, a function, …) falls back to `console.log`.
199        "table" => {
200            match render_table(args) {
201                Err(e) => return Some(Err(e)),
202                Ok(Some(t)) => emit(&t, false),
203                // `this.log(tabularData)`: only the data, never `properties`.
204                Ok(None) => match format_args(&args[..args.len().min(1)]) {
205                    Ok(s) => emit(&s, false),
206                    Err(e) => return Some(Err(e)),
207                },
208            }
209            Ok(Value::Undef)
210        }
211        // `console.clear()`: emit the clear-screen sequence only to a TTY (a no-op
212        // when output is redirected), matching Node.
213        "clear" => {
214            let is_tty = SINK.with(|s| s.borrow().is_some()) || std::io::stdout().is_terminal();
215            if is_tty {
216                emit("\u{1b}[2J\u{1b}[0f", false);
217            }
218            Ok(Value::Undef)
219        }
220        // Devtools-only timeline hooks — no timeline here, so no-ops (as in Node
221        // when not under an inspector).
222        "timeStamp" | "profile" | "profileEnd" => Ok(Value::Undef),
223        _ => return None,
224    })
225}
226
227/// `new console.Console(stdout[, stderr])` or `new console.Console({stdout, stderr})`
228/// → an object tagged `@@native = "Console"` carrying its target streams. Parent
229/// `mod.rs` wires construction and `instance_call`.
230pub fn construct(args: &[Value]) -> Result<Value, String> {
231    let first = args.first().cloned().unwrap_or(Value::Undef);
232    // Options form: a plain object exposing a `stdout` property.
233    let is_options = with_host(|h| match h.get(&first) {
234        Some(JsObj::Object(m)) => m.contains_key("stdout"),
235        _ => false,
236    });
237    let (stdout, stderr) = if is_options {
238        let out = crate::builtins::get_property(&first, "stdout").unwrap_or(Value::Undef);
239        let err = match crate::builtins::get_property(&first, "stderr") {
240            Ok(Value::Undef) | Err(_) => out.clone(),
241            Ok(v) => v,
242        };
243        (out, err)
244    } else {
245        let err = args
246            .get(1)
247            .cloned()
248            .filter(|v| !matches!(v, Value::Undef))
249            .unwrap_or_else(|| first.clone());
250        (first, err)
251    };
252    Ok(with_host(|h| {
253        let mut m = IndexMap::new();
254        m.insert("@@native".into(), h.new_str("Console"));
255        m.insert("@@stdout".into(), stdout);
256        m.insert("@@stderr".into(), stderr);
257        h.new_object(m)
258    }))
259}
260
261/// Dispatch a method on a `Console` instance: install the instance's streams as the
262/// active output sink, run the same formatting/state logic the free functions use,
263/// then restore the previous sink.
264pub fn instance_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
265    let streams = with_host(|h| match h.get(recv) {
266        Some(JsObj::Object(m)) => Some((
267            m.get("@@stdout").cloned().unwrap_or(Value::Undef),
268            m.get("@@stderr").cloned().unwrap_or(Value::Undef),
269        )),
270        _ => None,
271    });
272    let prev = SINK.with(|s| s.borrow_mut().take());
273    SINK.with(|s| *s.borrow_mut() = streams);
274    let r = call(method, &args).unwrap_or(Ok(Value::Undef));
275    SINK.with(|s| *s.borrow_mut() = prev);
276    r
277}
278
279/// Space-join every argument through the shared console formatter (identical to
280/// the global `console.log` path in `builtins::print_line`).
281fn format_args(args: &[Value]) -> Result<String, String> {
282    // console.log(...args) === util.format(...args): printf substitution when the
283    // first arg is a format string, else inspect-and-join.
284    super::util::format(args)
285}
286
287/// The label argument (`args[0]`) as a string, or `fallback` when absent.
288/// `{ customInspect: false, ...options }` for `console.dir`. A non-object
289/// `options` (absent, `null`, a number) spreads to nothing, as in node.
290fn dir_options(options: Option<&Value>) -> Value {
291    let mut props: IndexMap<String, Value> = IndexMap::new();
292    props.insert("customInspect".into(), Value::Bool(false));
293    if let Some(o) = options.filter(|o| matches!(o, Value::Obj(_))) {
294        // A getter on the options object runs, exactly as object spread does.
295        for (k, v) in crate::host::own_enum_entries_deep(o).unwrap_or_default() {
296            props.insert(k, v);
297        }
298    }
299    with_host(|h| h.new_object(props))
300}
301
302fn label_arg(args: &[Value], fallback: &str) -> String {
303    match args.first() {
304        Some(v) => with_host(|h| h.str_of(v)),
305        None => fallback.to_string(),
306    }
307}
308
309/// Write a line with the current `console.group` indentation applied to every
310/// physical line. Routes to the active `Console` instance sink stream if one is
311/// installed, else to the process stdout/stderr.
312fn emit(line: &str, stderr: bool) {
313    let depth = GROUP_DEPTH.with(|d| d.get());
314    let out = if depth == 0 {
315        line.to_string()
316    } else {
317        let pad = "  ".repeat(depth);
318        format!("{pad}{}", line.replace('\n', &format!("\n{pad}")))
319    };
320    // A `Console` instance with a real (heap-object) stream: write through it.
321    let stream = SINK.with(|s| {
322        s.borrow().as_ref().and_then(|(o, e)| {
323            let target = if stderr { e } else { o };
324            matches!(target, Value::Obj(_)).then(|| target.clone())
325        })
326    });
327    if let Some(stream) = stream {
328        let payload = with_host(|h| h.new_str(format!("{out}\n")));
329        if crate::host::call_method(&stream, "write", vec![payload]).is_ok() {
330            return;
331        }
332    }
333    with_host(|h| h.write_out(&format!("{out}\n"), stderr));
334}
335
336// ── console.table ────────────────────────────────────────────────────────────
337//
338// A port of node's `Console.prototype.table` (lib/internal/console/
339// constructor.js) and of `lib/internal/cli_table.js`, which draws the box.
340
341/// The key/value pairs a Map-shaped `console.table` source is read as.
342type TableEntries = Vec<(Value, Value)>;
343
344/// `console.table(data[, properties])` as node renders it, or `Ok(None)` when
345/// `data` is not an object — the caller then logs it as `console.log` would.
346fn render_table(args: &[Value]) -> Result<Option<String>, String> {
347    let data = args.first().cloned().unwrap_or(Value::Undef);
348    let properties = args.get(1).cloned().unwrap_or(Value::Undef);
349    let properties: Option<Vec<Value>> = match with_host(|h| h.get(&properties).cloned()) {
350        _ if matches!(properties, Value::Undef) => None,
351        Some(JsObj::Array(items)) => Some(items),
352        _ => {
353            return Err(crate::host::coded_error(
354                "TypeError",
355                "ERR_INVALID_ARG_TYPE",
356                &format!(
357                    "The \"properties\" argument must be an instance of Array. Received {}",
358                    crate::stdlib::received_desc(&properties)
359                ),
360            ))
361        }
362    };
363    if with_host(|h| crate::host::is_primitive(h, &data) || h.is_null(&data)) {
364        return Ok(None);
365    }
366    let index_array = |n: usize| -> Result<Vec<Option<String>>, String> {
367        (0..n)
368            .map(|i| table_inspect(&Value::Float(i as f64)).map(Some))
369            .collect()
370    };
371
372    // A Map, or a Map/Set iterator, is read without being consumed
373    // (`previewEntries`); a Map entries iterator and a Map are key/value.
374    let view = with_host(|h| crate::builtins::collection_iterator_view(h, &data));
375    let (map_entries, set_values): (Option<TableEntries>, Option<Vec<Value>>) =
376        match (view, with_host(|h| h.get(&data).cloned())) {
377            (Some(("Map Entries", rest)), _) => (Some(rest), None),
378            // `previewEntries` of a Set entries iterator is the flat
379            // `[v, v, …]` list, each value twice.
380            (Some(("Set Entries", rest)), _) => (
381                None,
382                Some(rest.into_iter().flat_map(|(k, v)| [k, v]).collect()),
383            ),
384            (Some((_, rest)), _) => (None, Some(rest.into_iter().map(|(k, _)| k).collect())),
385            (None, Some(JsObj::Map { entries, .. })) => {
386                (Some(entries.values().cloned().collect()), None)
387            }
388            (None, Some(JsObj::Set { entries, .. })) => {
389                (None, Some(entries.values().cloned().collect()))
390            }
391            _ => (None, None),
392        };
393    if let Some(pairs) = map_entries {
394        let mut keys = Vec::with_capacity(pairs.len());
395        let mut values = Vec::with_capacity(pairs.len());
396        for (k, v) in &pairs {
397            keys.push(Some(table_inspect(k)?));
398            values.push(Some(table_inspect(v)?));
399        }
400        let head = ["(iteration index)", "Key", "Values"].map(str::to_string);
401        return Ok(Some(cli_table(
402            &head,
403            &[index_array(pairs.len())?, keys, values],
404        )));
405    }
406    if let Some(items) = set_values {
407        let values = items
408            .iter()
409            .map(|v| table_inspect(v).map(Some))
410            .collect::<Result<Vec<_>, _>>()?;
411        let head = ["(iteration index)", "Values"].map(str::to_string);
412        return Ok(Some(cli_table(&head, &[index_array(items.len())?, values])));
413    }
414
415    // One column per key, in `ObjectKeys` order of first appearance; a row
416    // that lacks the key leaves its cell empty.
417    let index_keys = object_keys(&data)?;
418    let mut map: Vec<(String, Vec<Option<String>>)> = Vec::new();
419    let mut has_primitives = false;
420    let mut values_column: Vec<Option<String>> = Vec::new();
421    for (i, k) in index_keys.iter().enumerate() {
422        let item = crate::builtins::get_property(&data, k)?;
423        let primitive = with_host(|h| h.is_nullish(&item) || crate::host::is_primitive(h, &item));
424        if properties.is_none() && primitive {
425            has_primitives = true;
426            set_cell(&mut values_column, i, table_inspect(&item)?);
427            continue;
428        }
429        let keys: Vec<String> = match &properties {
430            Some(p) => p
431                .iter()
432                .map(crate::host::to_property_key)
433                .collect::<Result<_, _>>()?,
434            None => object_keys(&item)?,
435        };
436        for key in keys {
437            let pos = match map.iter().position(|(k, _)| *k == key) {
438                Some(p) => p,
439                None => {
440                    map.push((key.clone(), Vec::new()));
441                    map.len() - 1
442                }
443            };
444            let cell = if (primitive && properties.is_some()) || !has_own(&item, &key)? {
445                String::new()
446            } else {
447                table_inspect(&crate::builtins::get_property(&item, &key)?)?
448            };
449            set_cell(&mut map[pos].1, i, cell);
450        }
451    }
452    // `ObjectKeys(map)` of the null-prototype accumulator: integer keys first.
453    let (mut ordered, rest): (Vec<_>, Vec<_>) = map
454        .into_iter()
455        .partition(|(k, _)| crate::host::array_index(k).is_some());
456    ordered.sort_by_key(|(k, _)| crate::host::array_index(k));
457    ordered.extend(rest);
458    let mut head = vec!["(index)".to_string()];
459    let mut columns = vec![index_keys.into_iter().map(Some).collect::<Vec<_>>()];
460    for (k, col) in ordered {
461        head.push(k);
462        columns.push(col);
463    }
464    if has_primitives {
465        head.push("Values".to_string());
466        columns.push(values_column);
467    }
468    Ok(Some(cli_table(&head, &columns)))
469}
470
471/// `map[key][i] = cell`: a sparse column grows to `i + 1`, its gaps holes.
472fn set_cell(column: &mut Vec<Option<String>>, i: usize, cell: String) {
473    if column.len() <= i {
474        column.resize(i + 1, None);
475    }
476    column[i] = Some(cell);
477}
478
479/// `ObjectKeys(v)` as strings.
480fn object_keys(v: &Value) -> Result<Vec<String>, String> {
481    let keys = crate::builtins::call_builtin_function("Object.keys", vec![v.clone()])?;
482    Ok(with_host(|h| match h.get(&keys) {
483        Some(JsObj::Array(items)) => items.iter().map(|k| h.str_of(k)).collect(),
484        _ => Vec::new(),
485    }))
486}
487
488fn has_own(v: &Value, key: &str) -> Result<bool, String> {
489    let k = with_host(|h| h.new_str(key.to_string()));
490    let r = crate::builtins::object_builtin_method(v, "hasOwnProperty", vec![k])?;
491    Ok(with_host(|h| h.truthy(&r)))
492}
493
494/// The table's `_inspect`: an object with more than two own keys collapses to
495/// `[Object]` (depth -1), everything else shows one level; at most three array
496/// items; never wrapped.
497fn table_inspect(v: &Value) -> Result<String, String> {
498    // node's `isArray` here also admits typed arrays and Buffers.
499    let view = matches!(
500        crate::stdlib::native_tag(v).as_deref(),
501        Some("TypedArray" | "Buffer")
502    );
503    let collapse = !view
504        && with_host(|h| {
505            !crate::host::is_primitive(h, v)
506                && !h.is_nullish(v)
507                && !matches!(h.get(v), Some(JsObj::Array(_)))
508        })
509        && object_keys(v)?.len() > 2;
510    let opts = with_host(|h| {
511        let mut m: IndexMap<String, Value> = IndexMap::new();
512        m.insert(
513            "depth".into(),
514            Value::Float(if collapse { -1.0 } else { 0.0 }),
515        );
516        m.insert("maxArrayLength".into(), Value::Float(3.0));
517        m.insert("breakLength".into(), Value::Float(f64::INFINITY));
518        h.new_object(m)
519    });
520    let out = crate::stdlib::util::call("inspect", &[v.clone(), opts])
521        .unwrap_or_else(|| Ok(with_host(|h| h.new_str(h.inspect(v)))))?;
522    Ok(with_host(|h| h.str_of(&out)))
523}
524
525/// node's `getStringWidth` (the build without ICU data, which is the one
526/// written out in `lib/internal/util/inspect.js`): VT escapes removed, NFC,
527/// then one column per code point except the zero-width ones, two for the
528/// East Asian full-width ranges.
529fn string_width(s: &str) -> usize {
530    use unicode_normalization::UnicodeNormalization;
531    let s: String = crate::stdlib::util::strip_vt(s).nfc().collect();
532    s.chars()
533        .map(|c| {
534            let code = c as u32;
535            if is_full_width(code) {
536                2
537            } else if is_zero_width(code) {
538                0
539            } else {
540                1
541            }
542        })
543        .sum()
544}
545
546fn is_zero_width(code: u32) -> bool {
547    code <= 0x1F
548        || (0x7F..=0x9F).contains(&code)
549        || (0x300..=0x36F).contains(&code)
550        || (0x200B..=0x200F).contains(&code)
551        || (0x20D0..=0x20FF).contains(&code)
552        || (0xFE00..=0xFE0F).contains(&code)
553        || (0xFE20..=0xFE2F).contains(&code)
554        || (0xE0100..=0xE01EF).contains(&code)
555}
556
557fn is_full_width(code: u32) -> bool {
558    code >= 0x1100
559        && (code <= 0x115f
560            || code == 0x2329
561            || code == 0x232a
562            || ((0x2e80..=0x3247).contains(&code) && code != 0x303f)
563            || (0x3250..=0x4dbf).contains(&code)
564            || (0x4e00..=0xa4c6).contains(&code)
565            || (0xa960..=0xa97c).contains(&code)
566            || (0xac00..=0xd7a3).contains(&code)
567            || (0xf900..=0xfaff).contains(&code)
568            || (0xfe10..=0xfe19).contains(&code)
569            || (0xfe30..=0xfe6b).contains(&code)
570            || (0xff01..=0xff60).contains(&code)
571            || (0xffe0..=0xffe6).contains(&code)
572            || (0x1b000..=0x1b001).contains(&code)
573            || (0x1f200..=0x1f251).contains(&code)
574            || (0x1f300..=0x1f64f).contains(&code)
575            || (0x20000..=0x3fffd).contains(&code))
576}
577
578/// `cli_table(head, columns)`: every column as wide as its widest cell, each
579/// cell LEFT-justified, a missing cell (a hole, or past the column's end)
580/// blank.
581fn cli_table(head: &[String], columns: &[Vec<Option<String>>]) -> String {
582    let longest = columns.iter().map(Vec::len).max().unwrap_or(0);
583    let mut widths: Vec<usize> = head.iter().map(|h| string_width(h)).collect();
584    let mut rows: Vec<Vec<String>> = vec![Vec::with_capacity(head.len()); longest];
585    for (i, column) in columns.iter().enumerate() {
586        for (j, row) in rows.iter_mut().enumerate() {
587            let value = column.get(j).cloned().flatten().unwrap_or_default();
588            widths[i] = widths[i].max(string_width(&value));
589            row.push(value);
590        }
591    }
592    let render_row = |row: &[String]| -> String {
593        let cells: Vec<String> = row
594            .iter()
595            .zip(&widths)
596            .map(|(cell, w)| format!("{cell}{}", " ".repeat(w.saturating_sub(string_width(cell)))))
597            .collect();
598        format!("│ {} │", cells.join(" │ "))
599    };
600    let divider: Vec<String> = widths.iter().map(|w| "─".repeat(w + 2)).collect();
601    let mut out = format!(
602        "┌{}┐\n{}\n├{}┤\n",
603        divider.join("┬"),
604        render_row(head),
605        divider.join("┼")
606    );
607    for row in &rows {
608        out.push_str(&render_row(row));
609        out.push('\n');
610    }
611    out.push_str(&format!("└{}┘", divider.join("┴")));
612    out
613}