Skip to main content

jlf_core/format/
log.rs

1use core::{cmp::Ordering, fmt};
2
3pub use owo_colors::OwoColorize as Colorize;
4
5use super::*;
6use crate::{json::PathToken, Json};
7
8// used for displaying the formatted log to output
9pub struct FormattedLog<'a> {
10    pub(super) formatter: &'a Formatter,
11    pub(super) json: &'a Json<'a>,
12}
13
14/// The current entry bound inside a `$( … )` repetition: `$key`/`$value`.
15struct Binding<'a> {
16    key: BindKey<'a>,
17    value: &'a Json<'a>,
18}
19
20enum BindKey<'a> {
21    Str(&'a str),
22    Index(usize),
23}
24
25impl fmt::Display for FormattedLog<'_> {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        self.write_fmt(f)
28    }
29}
30
31impl FormattedLog<'_> {
32    pub fn write_fmt(&self, f: &mut impl fmt::Write) -> Result<(), fmt::Error> {
33        let Self {
34            formatter:
35                Formatter {
36                    pieces,
37                    args,
38                    has_optional,
39                    columns,
40                },
41            json,
42        } = self;
43
44        let mut used_fields = SmallVec::new();
45
46        // Plain templates write straight through. Only when an optional
47        // `{?field}` is present do we wrap the writer to defer whitespace so an
48        // empty optional can collapse one adjacent space.
49        if *has_optional {
50            let mut w = Trimmer::new(f);
51            render(&mut w, pieces, args, json, columns, &mut used_fields)?;
52            w.flush_ws()?;
53        } else {
54            let mut w = Plain(f);
55            render(&mut w, pieces, args, json, columns, &mut used_fields)?;
56        }
57
58        Ok(())
59    }
60}
61
62fn render<'a>(
63    f: &mut impl Write2,
64    pieces: &'a Vec<Piece>,
65    args: &'a Vec<Arg>,
66    json: &'a Json<'a>,
67    cols: &'a [Column],
68    used_fields: &mut SmallVec<[&'a Field; 5]>,
69) -> fmt::Result {
70    let mut piece_i = 0;
71    while piece_i < pieces.len() {
72        piece_i = write_piece(
73            f,
74            pieces,
75            piece_i,
76            args,
77            json,
78            cols,
79            None,
80            false,
81            used_fields,
82        )?;
83    }
84    Ok(())
85}
86
87#[allow(clippy::too_many_arguments)]
88fn write_piece<'a>(
89    f: &mut impl Write2,
90    pieces: &'a Vec<Piece>,
91    mut piece_i: usize,
92    args: &'a Vec<Arg>,
93    json: &'a Json<'a>,
94    cols: &'a [Column],
95    cur: Option<&Binding<'a>>,
96    skip: bool,
97    used_fields: &mut SmallVec<[&'a Field; 5]>,
98) -> Result<usize, fmt::Error> {
99    use Piece::*;
100
101    match &pieces[piece_i] {
102        Literal(literal) => {
103            if !skip {
104                write!(f, "{}", literal)?
105            }
106        }
107        Arg(i) => {
108            if !skip {
109                let arg = &args[*i];
110                if arg.1.optional {
111                    // Render the optional field aside; if it produced nothing,
112                    // collapse a neighbouring space instead of emitting it. An
113                    // optional rest (`{?..}`) with no leftover fields counts as
114                    // empty too (so it doesn't print a bare `{}`/`[]`).
115                    let mut scratch = String::new();
116                    let empty =
117                        rest_arg_without_content(arg, json, used_fields) || {
118                            write_arg(
119                                &mut scratch,
120                                arg,
121                                json,
122                                cur,
123                                used_fields,
124                            )?;
125                            scratch.is_empty()
126                        };
127                    if empty {
128                        f.collapse_ws();
129                    } else {
130                        f.write_str(&scratch)?;
131                    }
132                } else {
133                    write_arg(f, arg, json, cur, used_fields)?
134                }
135            }
136        }
137        RepStart(src, sep, op) => {
138            let end = find_rep_end(pieces, piece_i);
139            if !skip {
140                render_rep(
141                    f,
142                    pieces,
143                    piece_i,
144                    end,
145                    src,
146                    sep,
147                    *op,
148                    args,
149                    json,
150                    cols,
151                    used_fields,
152                )?;
153            }
154            return Ok(end + 1);
155        }
156        RepEnd => {}
157        CondStart(cond, i) => {
158            // Walk an `if / else if… / else` chain, running the first branch
159            // whose condition holds. `matched` stays set once any branch wins
160            // so later `else if`/`else` arms are skipped. When the
161            // whole block is itself skipped, every branch is
162            // suppressed.
163            let mut matched =
164                !skip && test_cond(cond, args, *i, json, cur, used_fields);
165            let mut should_run = matched;
166
167            piece_i += 1;
168            while piece_i < pieces.len() {
169                match &pieces[piece_i] {
170                    Piece::ElseCond(cond, i) => {
171                        should_run = !skip
172                            && !matched
173                            && test_cond(
174                                cond,
175                                args,
176                                *i,
177                                json,
178                                cur,
179                                used_fields,
180                            );
181                        matched |= should_run;
182                        piece_i += 1;
183                    }
184                    Piece::Else => {
185                        should_run = !skip && !matched;
186                        matched = true;
187                        piece_i += 1;
188                    }
189                    _ => {}
190                }
191
192                if let Piece::CondEnd = pieces[piece_i] {
193                    break;
194                }
195
196                piece_i = write_piece(
197                    f,
198                    pieces,
199                    piece_i,
200                    args,
201                    json,
202                    cols,
203                    cur,
204                    !should_run,
205                    used_fields,
206                )?;
207            }
208        }
209        // Handled in the CondStart case above
210        ElseCond(..) | Else | CondEnd => {}
211        MatchStart(subj) => {
212            let end = find_match_end(pieces, piece_i);
213            if !skip {
214                // Bind the subject to `$value` and render the arm chain in
215                // between; the arms (an if/else-if chain over `$value`) pick
216                // the first matching one. Marking the subject
217                // consumed keeps it out of a later `${..}` rest
218                // dump.
219                let (field_options, _) = &args[*subj];
220                let value =
221                    resolve_subject(json, field_options, cur, used_fields);
222                let binding = Binding {
223                    key: BindKey::Str(""),
224                    value,
225                };
226                let mut i = piece_i + 1;
227                while i < end {
228                    i = write_piece(
229                        f,
230                        pieces,
231                        i,
232                        args,
233                        json,
234                        cols,
235                        Some(&binding),
236                        false,
237                        used_fields,
238                    )?;
239                }
240            }
241            return Ok(end + 1);
242        }
243        MatchEnd => {}
244    }
245
246    Ok(piece_i + 1)
247}
248
249/// Index of the `MatchEnd` matching the `MatchStart` at `start`
250/// (nesting-aware).
251fn find_match_end(pieces: &[Piece], start: usize) -> usize {
252    let mut depth = 0usize;
253    let mut i = start + 1;
254    while i < pieces.len() {
255        match &pieces[i] {
256            Piece::MatchStart(_) => depth += 1,
257            Piece::MatchEnd => {
258                if depth == 0 {
259                    return i;
260                }
261                depth -= 1;
262            }
263            _ => {}
264        }
265        i += 1;
266    }
267    pieces.len().saturating_sub(1)
268}
269
270/// Resolve a `${match}` subject to its value. A plain path is looked up in the
271/// record (and recorded in `used_fields` so a later `${..}` rest dump skips
272/// it); `$value`/`${value.sub}` resolve against the enclosing repetition/match
273/// binding so a match can dispatch on a loop entry. The first non-null option
274/// wins.
275fn resolve_subject<'a>(
276    json: &'a Json<'a>,
277    field_options: &'a [Field],
278    cur: Option<&Binding<'a>>,
279    used_fields: &mut SmallVec<[&'a Field; 5]>,
280) -> &'a Json<'a> {
281    let mut last = json;
282    for field in field_options {
283        last = match field {
284            Field::ColValue => cur.map_or(json, |c| c.value),
285            Field::ColValuePath(names) => {
286                cur.map_or(json, |c| walk(c.value, names))
287            }
288            _ => resolve_field(json, field),
289        };
290        if !last.is_null() {
291            if matches!(field, Field::Names(_)) {
292                used_fields.push(field);
293            }
294            return last;
295        }
296    }
297    last
298}
299
300/// Index of the `RepEnd` matching the `RepStart` at `start` (nesting-aware).
301fn find_rep_end(pieces: &[Piece], start: usize) -> usize {
302    let mut depth = 0usize;
303    let mut i = start + 1;
304    while i < pieces.len() {
305        match &pieces[i] {
306            Piece::RepStart(..) => depth += 1,
307            Piece::RepEnd => {
308                if depth == 0 {
309                    return i;
310                }
311                depth -= 1;
312            }
313            _ => {}
314        }
315        i += 1;
316    }
317    pieces.len().saturating_sub(1)
318}
319
320/// Render a `$( … )` repetition: build the bindings from `src`, render the body
321/// once per binding, and write `sep` between iterations (never trailing).
322#[allow(clippy::too_many_arguments)]
323fn render_rep<'a>(
324    f: &mut impl Write2,
325    pieces: &'a Vec<Piece>,
326    start: usize,
327    end: usize,
328    src: &RepSource,
329    sep: &str,
330    op: RepOp,
331    args: &'a Vec<Arg>,
332    json: &'a Json<'a>,
333    cols: &'a [Column],
334    used_fields: &mut SmallVec<[&'a Field; 5]>,
335) -> fmt::Result {
336    let mut bindings: Vec<Binding<'a>> = Vec::new();
337    match src {
338        RepSource::Columns => {
339            for col in cols {
340                bindings.push(Binding {
341                    key: BindKey::Str(&col.name),
342                    value: resolve_field(json, &col.field),
343                });
344            }
345        }
346        // `$( … )` iterates the record itself; `$path( … )` a sub-object/array.
347        RepSource::Record | RepSource::Path(_) => {
348            let target = match src {
349                RepSource::Path(field) => resolve_field(json, field),
350                _ => json,
351            };
352            // The base path of this iteration, so an object key already shown
353            // by an earlier `${base.key}` reference is skipped here
354            // (like `${..}`).
355            let base: &[FieldType] = match src {
356                RepSource::Path(Field::Names(names)) => names,
357                _ => &[],
358            };
359            if let Some(obj) = target.as_object() {
360                for (k, v) in obj.iter() {
361                    if key_consumed(used_fields, base, k) {
362                        continue;
363                    }
364                    bindings.push(Binding {
365                        key: BindKey::Str(k),
366                        value: v,
367                    });
368                }
369            } else if let Some(arr) = target.as_array() {
370                for (idx, v) in arr.iter().enumerate() {
371                    bindings.push(Binding {
372                        key: BindKey::Index(idx),
373                        value: v,
374                    });
375                }
376            }
377        }
378    }
379
380    // `?` renders at most one iteration; `*`/`+` render them all.
381    let count = if op == RepOp::Question {
382        bindings.len().min(1)
383    } else {
384        bindings.len()
385    };
386
387    for (n, b) in bindings.iter().take(count).enumerate() {
388        if n > 0 {
389            f.write_str(sep)?;
390        }
391        let mut i = start + 1;
392        while i < end {
393            i = write_piece(
394                f,
395                pieces,
396                i,
397                args,
398                json,
399                cols,
400                Some(b),
401                false,
402                used_fields,
403            )?;
404        }
405    }
406
407    Ok(())
408}
409
410/// Walk a name path from a `Json` node (used for `${value.path}` in a rep).
411fn walk<'a>(mut val: &'a Json<'a>, names: &FieldNames) -> &'a Json<'a> {
412    let mut i = 0;
413    while i < names.len() {
414        match &names[i] {
415            FieldType::Index(idx) => {
416                val = val.get_i(*idx);
417                i += 1;
418            }
419            FieldType::Name(n) => {
420                let direct = val.get(n);
421                if !direct.is_null() {
422                    val = direct;
423                    i += 1;
424                    continue;
425                }
426                // Not a nested key: the remaining name tokens may be a single
427                // flattened dotted key (e.g. tracing's `log.file` stored as one
428                // literal key). Try joining consecutive names with '.', keeping
429                // the longest match so the most specific key wins. Nested
430                // lookup is tried first above, so real nesting
431                // still takes precedence.
432                let mut joined = n.clone();
433                let mut best: Option<(String, usize)> = None;
434                let mut j = i + 1;
435                while let Some(FieldType::Name(m)) = names.get(j) {
436                    joined.push('.');
437                    joined.push_str(m);
438                    if !val.get(&joined).is_null() {
439                        best = Some((joined.clone(), j + 1));
440                    }
441                    j += 1;
442                }
443                match best {
444                    Some((key, end)) => {
445                        val = val.get(&key);
446                        i = end;
447                    }
448                    None => return direct,
449                }
450            }
451        }
452    }
453    val
454}
455
456/// True when `base + key` was already consumed by an earlier field reference,
457/// so a repetition over `base` should skip that entry (e.g. `${fields.message}`
458/// up top drops `message` from a later `$fields( … )`). The trailing tokens
459/// after `base` are joined with '.', so a flattened key like `log.file`
460/// (referenced as `${fields.log.file}`) is also recognised and skipped.
461fn key_consumed(
462    used_fields: &SmallVec<[&Field; 5]>,
463    base: &[FieldType],
464    key: &str,
465) -> bool {
466    with_excluded(used_fields, |excluded| {
467        excluded.iter().any(|path| {
468            path.len() > base.len()
469                && base.iter().zip(path.iter()).all(|(b, p)| match (b, p) {
470                    (FieldType::Name(n), PathToken::Name(x)) => x == n,
471                    (FieldType::Index(i), PathToken::Index(x)) => x == i,
472                    _ => false,
473                })
474                && join_names_eq(&path[base.len()..], key)
475        })
476    })
477}
478
479/// Whether the `Name` tokens of `rest` joined with '.' equal `key` (and there
480/// are no `Index` tokens) — recognising a flattened dotted key like `log.file`.
481fn join_names_eq(rest: &[PathToken<'_>], key: &str) -> bool {
482    let mut joined = String::new();
483    for (i, tok) in rest.iter().enumerate() {
484        match tok {
485            PathToken::Name(n) => {
486                if i > 0 {
487                    joined.push('.');
488                }
489                joined.push_str(n);
490            }
491            PathToken::Index(_) => return false,
492        }
493    }
494    joined == key
495}
496
497/// Resolve a field accessor to the pointed-at `Json` (no rest handling).
498fn resolve_field<'a>(json: &'a Json<'a>, field: &Field) -> &'a Json<'a> {
499    match field {
500        Field::Whole
501        | Field::Rest
502        | Field::ColValue
503        | Field::ColKey
504        | Field::ColValuePath(_)
505        | Field::Literal(_) => json,
506        Field::Names(names) => walk(json, names),
507    }
508}
509
510/// True when an optional arg's selected field is the rest (`..`) and there are
511/// no leftover fields to show — so `{?..}` renders empty and collapses its
512/// space rather than printing a bare `{}`/`[]`. A present earlier fallback
513/// (`{?a|..}` with `a` set) returns false, since rest is never reached.
514fn rest_arg_without_content<'a>(
515    (field_options, _): &'a Arg,
516    json: &'a Json<'a>,
517    used_fields: &SmallVec<[&'a Field; 5]>,
518) -> bool {
519    for field in field_options {
520        match field {
521            Field::Whole => return false,
522            Field::ColValue | Field::ColKey | Field::ColValuePath(_) => {
523                return false
524            }
525            Field::Literal(_) => return false,
526            Field::Rest => {
527                return !with_excluded(used_fields, |excluded| {
528                    json.has_rest_content(excluded)
529                });
530            }
531            Field::Names(names) => {
532                let val = walk(json, names);
533                if !val.is_null() {
534                    return false; // this fallback renders; rest isn't reached
535                }
536            }
537        }
538    }
539    false
540}
541
542fn test_cond<'a>(
543    cond: &Cond,
544    args: &[Arg],
545    i: usize,
546    json: &'a Json<'a>,
547    cur: Option<&Binding<'a>>,
548    used_fields: &SmallVec<[&'a Field; 5]>,
549) -> bool {
550    if let Cond::IfConfig(b) = cond {
551        return *b;
552    }
553
554    let (field_options, _) = &args[i];
555    for field in field_options {
556        let matched = match field {
557            Field::Whole => test_cond2(cond, json),
558            Field::ColValue => {
559                cur.map(|c| test_cond2(cond, c.value)).unwrap_or(false)
560            }
561            Field::ColValuePath(names) => cur
562                .map(|c| test_cond2(cond, walk(c.value, names)))
563                .unwrap_or(false),
564            Field::ColKey => cur
565                .map(|c| match c.key {
566                    BindKey::Str(s) => *cond == Cond::Has || !s.is_empty(),
567                    BindKey::Index(_) => true,
568                })
569                .unwrap_or(false),
570            Field::Rest => {
571                // For `key`, `rest` is the base object and always exists. For
572                // `if`, it's truthy only when there are unused fields left.
573                if *cond == Cond::Has {
574                    true
575                } else {
576                    with_excluded(used_fields, |excluded| {
577                        json.has_rest_content(excluded)
578                    })
579                }
580            }
581            Field::Names(names) => {
582                let val = walk(json, names);
583                test_cond2(cond, val)
584            }
585            // A literal is never a directive subject in practice (directives
586            // parse their subject separately), but treat it as present.
587            Field::Literal(s) => *cond == Cond::Has || !s.is_empty(),
588        };
589
590        // A fallback list (`a|b|c`) is satisfied as soon as one option is:
591        // `#key` matches the first option that exists, `#if` the first truthy
592        // one. Earlier present-but-falsey options must not short-circuit `#if`.
593        if matched {
594            return true;
595        }
596    }
597
598    false
599}
600
601fn test_cond2(cond: &Cond, json: &Json<'_>) -> bool {
602    if json.is_null() {
603        return false;
604    }
605
606    match cond {
607        Cond::Has => true,
608        Cond::Cmp(op, rhs) => compare_scalar(json, *op, rhs),
609        Cond::Arm(tests) => match_arm(json, tests),
610        Cond::If => {
611            if json.is_array() || json.is_object() {
612                !json.is_empty()
613            } else if let Some(json) = json.as_str() {
614                !json.is_empty()
615            } else if let Some(json) = json.as_value() {
616                !(json == "false"
617                    || json == "0"
618                    || json == "-0"
619                    || json == "0n"
620                    || json == "undefined"
621                    || json == "NaN")
622            } else {
623                unreachable!("all cases checked")
624            }
625        }
626        Cond::IfConfig(_) => unreachable!("checked above"),
627    }
628}
629
630/// Evaluate `field OP literal`. Ordering ops (`<`,`>`,`<=`,`>=`) compare
631/// leniently — a leading number tolerating a unit suffix like the ` ms` in
632/// `"17.881 ms"`, then a timestamp, else lexicographically — matching the CLI
633/// filter operators. Equality (`==`/`!=`) stays exact: numeric only when both
634/// sides are whole numbers, otherwise a string compare (so `"2xx"` ≠ `"2yy"`).
635/// Objects/arrays never match.
636fn compare_scalar(json: &Json<'_>, op: CmpOp, rhs: &str) -> bool {
637    let Some(lhs) = json.as_str().or_else(|| json.as_value()) else {
638        return false;
639    };
640    let ord = match op {
641        CmpOp::Eq | CmpOp::Ne => match (lhs.parse::<f64>(), rhs.parse::<f64>())
642        {
643            (Ok(a), Ok(b)) => a.partial_cmp(&b),
644            _ => Some(lhs.cmp(rhs)),
645        },
646        _ => order_scalars(lhs, rhs),
647    };
648    let Some(ord) = ord else {
649        return false; // NaN or otherwise not comparable — no ordering
650    };
651    match op {
652        CmpOp::Eq => ord == Ordering::Equal,
653        CmpOp::Ne => ord != Ordering::Equal,
654        CmpOp::Gt => ord == Ordering::Greater,
655        CmpOp::Ge => ord != Ordering::Less,
656        CmpOp::Lt => ord == Ordering::Less,
657        CmpOp::Le => ord != Ordering::Greater,
658    }
659}
660
661/// Order two scalar strings for a `<`/`>`/`<=`/`>=` comparison: numerically
662/// when both parse as numbers (tolerating a unit suffix), else as timestamps,
663/// else lexicographically. Mirrors the CLI filter's ordering semantics.
664fn order_scalars(lhs: &str, rhs: &str) -> Option<Ordering> {
665    if let (Some(a), Some(b)) =
666        (crate::parse_number(lhs), crate::parse_number(rhs))
667    {
668        return a.partial_cmp(&b);
669    }
670    if let (Some(a), Some(b)) =
671        (crate::parse_datetime(lhs), crate::parse_datetime(rhs))
672    {
673        return Some(a.cmp(&b));
674    }
675    Some(lhs.cmp(rhs))
676}
677
678/// Evaluate a `${match}` arm against the (non-null) subject: the wildcard
679/// (empty list) matches any present value; otherwise any listed test may match.
680fn match_arm(json: &Json<'_>, tests: &[ArmTest]) -> bool {
681    if tests.is_empty() {
682        return true; // `_`: the caller already excluded null subjects
683    }
684    tests.iter().any(|t| match t {
685        ArmTest::Cmp(op, rhs) => compare_scalar(json, *op, rhs),
686        ArmTest::Range { lo, hi, hi_inclusive } => json
687            .as_str()
688            .or_else(|| json.as_value())
689            .and_then(crate::parse_number)
690            .is_some_and(|v| {
691                lo.is_none_or(|lo| v >= lo)
692                    && hi.is_none_or(|hi| {
693                        if *hi_inclusive {
694                            v <= hi
695                        } else {
696                            v < hi
697                        }
698                    })
699            }),
700    })
701}
702
703fn write_arg<'a>(
704    f: &mut impl fmt::Write,
705    (field_options, format): &'a (FieldOptions, Format),
706    json: &'a Json<'a>,
707    cur: Option<&Binding<'a>>,
708    used_fields: &mut SmallVec<[&'a Field; 5]>,
709) -> fmt::Result {
710    let mut val = &Json::Null;
711
712    for field in field_options {
713        match field {
714            Field::Whole => {
715                return write_arg2(f, format, json);
716            }
717            Field::Rest => {
718                return write_rest(f, format, json, used_fields);
719            }
720            Field::ColValue => {
721                return match cur {
722                    Some(c) => write_arg2(f, format, c.value),
723                    None => Ok(()),
724                };
725            }
726            Field::ColValuePath(names) => {
727                return match cur {
728                    Some(c) => write_arg2(f, format, walk(c.value, names)),
729                    None => Ok(()),
730                };
731            }
732            Field::ColKey => {
733                return match cur {
734                    Some(c) => match c.key {
735                        BindKey::Str(s) => write_scalar_str(f, format, s),
736                        BindKey::Index(idx) => {
737                            write_scalar_str(f, format, &idx.to_string())
738                        }
739                    },
740                    None => Ok(()),
741                };
742            }
743            Field::Literal(s) => return write_scalar_str(f, format, s),
744            Field::Names(names) => {
745                val = walk(json, names);
746
747                if !val.is_null() {
748                    used_fields.push(field);
749                    break;
750                }
751            }
752        }
753    }
754
755    write_arg2(f, format, val)
756}
757
758/// Write a plain string value with the arg's escape or style applied (used for
759/// `$key`, which is a bare string/index rather than a `Json` node).
760fn write_scalar_str(
761    f: &mut impl fmt::Write,
762    format: &Format,
763    val: &str,
764) -> fmt::Result {
765    if format.escape != Escape::None {
766        return write_escaped(f, format.escape, val);
767    }
768    if let Some(style) = format.style {
769        write!(f, "{}", val.style(style))
770    } else {
771        f.write_str(val)
772    }
773}
774
775fn write_arg2(
776    f: &mut impl fmt::Write,
777    format: &Format,
778    json: &Json<'_>,
779) -> fmt::Result {
780    let Format {
781        style,
782        compact,
783        is_json: _,
784        indent,
785        optional: _,
786        escape,
787        markup_styles: json_styles,
788    } = format;
789    let indent = *indent;
790    let escape = *escape;
791
792    if indent > 0 {
793        write!(f, "{:indent$}", "", indent = indent)?;
794    }
795
796    if let Some(val) = json.as_str() {
797        if escape != Escape::None {
798            write_escaped(f, escape, val)?;
799        } else if let Some(style) = style {
800            write!(f, "{}", val.style(*style))?;
801        } else {
802            write!(f, "{}", val)?;
803        }
804    } else if let Some(val) = json.as_value() {
805        if escape != Escape::None {
806            write_escaped(f, escape, val)?;
807        } else if let Some(style) = style.as_ref() {
808            write!(f, "{}", val.style(*style))?;
809        } else {
810            write!(f, "{}", val)?;
811        }
812    } else if json.is_object() || json.is_array() {
813        if escape != Escape::None {
814            // A table/markup cell must stay on one line and be quoted for its
815            // dialect, so nested objects/arrays render as compact JSON (no
816            // ANSI) and then get escaped — never pretty-printed across rows.
817            write_escaped(f, escape, &json.to_string())?;
818        } else if *compact {
819            if style.is_some() {
820                write!(f, "{}", json.styled(*json_styles))?;
821            } else {
822                write!(f, "{}", json)?;
823            }
824        } else if style.is_some() {
825            write!(f, "{:?}", json.indented(indent).styled(*json_styles))?;
826        } else {
827            write!(f, "{:?}", json.indented(indent))?;
828        }
829    }
830
831    Ok(())
832}
833
834/// Builds the list of already-consumed field paths (as `PathToken` slices) from
835/// `used_fields`, so they can be skipped when rendering the rest object.
836fn build_excluded<'a>(
837    used_fields: &SmallVec<[&'a Field; 5]>,
838) -> SmallVec<[SmallVec<[PathToken<'a>; 2]>; 5]> {
839    let mut paths = SmallVec::new();
840
841    for field in used_fields.iter() {
842        if let Field::Names(names) = field {
843            let tokens = names
844                .iter()
845                .map(|t| match t {
846                    FieldType::Name(name) => PathToken::Name(name.as_str()),
847                    FieldType::Index(index) => PathToken::Index(*index),
848                })
849                .collect();
850            paths.push(tokens);
851        }
852    }
853
854    paths
855}
856
857/// Builds the excluded-path slice view from `used_fields` and runs `f` with it.
858fn with_excluded<R>(
859    used_fields: &SmallVec<[&Field; 5]>,
860    f: impl FnOnce(&[&[PathToken]]) -> R,
861) -> R {
862    let paths = build_excluded(used_fields);
863    let excluded: SmallVec<[&[PathToken]; 5]> =
864        paths.iter().map(|p| p.as_slice()).collect();
865    f(&excluded)
866}
867
868/// Write `s` with the given escape applied.
869fn write_escaped(
870    f: &mut impl fmt::Write,
871    escape: Escape,
872    s: &str,
873) -> fmt::Result {
874    match escape {
875        Escape::None => f.write_str(s),
876        Escape::Html => {
877            for c in s.chars() {
878                match c {
879                    '&' => f.write_str("&amp;")?,
880                    '<' => f.write_str("&lt;")?,
881                    '>' => f.write_str("&gt;")?,
882                    '"' => f.write_str("&quot;")?,
883                    '\'' => f.write_str("&#39;")?,
884                    _ => f.write_char(c)?,
885                }
886            }
887            Ok(())
888        }
889        Escape::Csv => {
890            if s.contains('"')
891                || s.contains('\n')
892                || s.contains('\r')
893                || s.contains(',')
894            {
895                f.write_char('"')?;
896                for c in s.chars() {
897                    if c == '"' {
898                        f.write_str("\"\"")?;
899                    } else {
900                        f.write_char(c)?;
901                    }
902                }
903                f.write_char('"')
904            } else {
905                f.write_str(s)
906            }
907        }
908        Escape::Tsv => {
909            for c in s.chars() {
910                match c {
911                    '\t' | '\n' | '\r' => f.write_char(' ')?,
912                    _ => f.write_char(c)?,
913                }
914            }
915            Ok(())
916        }
917        Escape::Md => {
918            for c in s.chars() {
919                match c {
920                    '|' => f.write_str("\\|")?,
921                    '\n' => f.write_str("<br>")?,
922                    _ => f.write_char(c)?,
923                }
924            }
925            Ok(())
926        }
927    }
928}
929
930/// Renders the rest object (`{..}`) as a filtered view of `json`, skipping the
931/// fields already consumed by earlier args. Mirrors the object/array branch of
932/// [`write_arg2`] but never clones the underlying `Json`.
933fn write_rest(
934    f: &mut impl fmt::Write,
935    format: &Format,
936    json: &Json,
937    used_fields: &SmallVec<[&Field; 5]>,
938) -> fmt::Result {
939    // Scalars can't have "rest" fields removed; fall back to the normal path.
940    if !(json.is_object() || json.is_array()) {
941        return write_arg2(f, format, json);
942    }
943
944    let Format {
945        style,
946        compact,
947        indent,
948        markup_styles,
949        ..
950    } = format;
951    let indent = *indent;
952
953    if indent > 0 {
954        write!(f, "{:indent$}", "", indent = indent)?;
955    }
956
957    let styles = style.map(|_| *markup_styles);
958    with_excluded(used_fields, |excluded| {
959        let view = RestView {
960            json,
961            excluded,
962            indent,
963            styles,
964        };
965
966        if *compact {
967            write!(f, "{}", view)
968        } else {
969            write!(f, "{:?}", view)
970        }
971    })
972}
973
974/// A `Display`/`Debug` wrapper that renders the rest object while skipping the
975/// `excluded` field paths. `Display` => compact, `Debug` => pretty.
976struct RestView<'a> {
977    json: &'a Json<'a>,
978    excluded: &'a [&'a [PathToken<'a>]],
979    indent: usize,
980    styles: Option<MarkupStyles>,
981}
982
983impl fmt::Display for RestView<'_> {
984    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
985        self.json.fmt_rest(f, self.excluded, None, &self.styles)
986    }
987}
988
989impl fmt::Debug for RestView<'_> {
990    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
991        self.json
992            .fmt_rest(f, self.excluded, Some(self.indent), &self.styles)
993    }
994}
995
996/// A writer that can collapse one whitespace separator next to an empty
997/// `{?field}`. Plain writers treat the collapse hooks as no-ops, so
998/// non-optional templates render with zero extra work.
999trait Write2: fmt::Write {
1000    /// An optional field rendered empty: collapse one adjacent space.
1001    fn collapse_ws(&mut self) {}
1002    /// Emit any deferred trailing whitespace.
1003    fn flush_ws(&mut self) -> fmt::Result { Ok(()) }
1004}
1005
1006/// Pass-through writer for templates without any `{?field}`.
1007struct Plain<'a, W: fmt::Write>(&'a mut W);
1008
1009impl<W: fmt::Write> fmt::Write for Plain<'_, W> {
1010    fn write_str(&mut self, s: &str) -> fmt::Result { self.0.write_str(s) }
1011}
1012
1013impl<W: fmt::Write> Write2 for Plain<'_, W> {}
1014
1015/// Whitespace-deferring writer used when a template contains `{?field}`.
1016///
1017/// Trailing whitespace is buffered rather than written immediately, so when an
1018/// empty optional asks to collapse a space we can either drop that buffered run
1019/// (the space *before* the field) or skip the next run (the space *after* it) —
1020/// collapsing exactly one separator so an absent field leaves no stray gap.
1021struct Trimmer<'a, W: fmt::Write> {
1022    inner: &'a mut W,
1023    pending: String,
1024    skip_leading_ws: bool,
1025}
1026
1027impl<'a, W: fmt::Write> Trimmer<'a, W> {
1028    fn new(inner: &'a mut W) -> Self {
1029        Self {
1030            inner,
1031            pending: String::new(),
1032            skip_leading_ws: false,
1033        }
1034    }
1035}
1036
1037impl<W: fmt::Write> fmt::Write for Trimmer<'_, W> {
1038    fn write_str(&mut self, s: &str) -> fmt::Result {
1039        // Collapsible separators include newlines, not just spaces/tabs, so an
1040        // empty optional can absorb a line break (e.g. the `\n` before
1041        // `{?@data}`).
1042        const WS: [char; 4] = [' ', '\t', '\n', '\r'];
1043        let mut s = s;
1044        if self.skip_leading_ws {
1045            let trimmed = s.trim_start_matches(WS);
1046            let stripped_some = trimmed.len() != s.len();
1047            s = trimmed;
1048            // Keep skipping only while the run is still all whitespace; stop
1049            // once real content (this or a later write) appears.
1050            if !stripped_some || !s.is_empty() {
1051                self.skip_leading_ws = false;
1052            }
1053        }
1054        if s.is_empty() {
1055            return Ok(());
1056        }
1057        let core_len = s.trim_end_matches(WS).len();
1058        let (core, trail) = s.split_at(core_len);
1059        if !core.is_empty() {
1060            if !self.pending.is_empty() {
1061                self.inner.write_str(&self.pending)?;
1062                self.pending.clear();
1063            }
1064            self.inner.write_str(core)?;
1065        }
1066        self.pending.push_str(trail);
1067        Ok(())
1068    }
1069}
1070
1071impl<W: fmt::Write> Write2 for Trimmer<'_, W> {
1072    fn collapse_ws(&mut self) {
1073        if self.pending.is_empty() {
1074            self.skip_leading_ws = true;
1075        } else {
1076            self.pending.clear();
1077        }
1078    }
1079
1080    fn flush_ws(&mut self) -> fmt::Result {
1081        if !self.pending.is_empty() {
1082            self.inner.write_str(&self.pending)?;
1083            self.pending.clear();
1084        }
1085        Ok(())
1086    }
1087}