dbgfmt 0.3.0

Pretty-print Rust Debug trait output with proper indentation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use crate::tokenizer::Token;

pub trait Emitter {
    fn emit_bracket(&mut self, output: &mut String, ch: char);
    fn emit_type_name(&mut self, output: &mut String, text: &str);
    fn emit_key(&mut self, output: &mut String, text: &str);
    fn emit_value(&mut self, output: &mut String, text: &str);
    fn emit_punctuation(&mut self, output: &mut String, text: &str);
}

pub struct PlainEmitter;

impl Emitter for PlainEmitter {
    fn emit_bracket(&mut self, output: &mut String, ch: char) {
        output.push(ch);
    }
    fn emit_type_name(&mut self, output: &mut String, text: &str) {
        output.push_str(text);
    }
    fn emit_key(&mut self, output: &mut String, text: &str) {
        output.push_str(text);
    }
    fn emit_value(&mut self, output: &mut String, text: &str) {
        output.push_str(text);
    }
    fn emit_punctuation(&mut self, output: &mut String, text: &str) {
        output.push_str(text);
    }
}

pub fn format_tokens(tokens: &[Token], indent_width: usize) -> String {
    format_tokens_with_emitter(tokens, indent_width, &mut PlainEmitter)
}

pub fn format_tokens_with_emitter(
    tokens: &[Token],
    indent_width: usize,
    emitter: &mut dyn Emitter,
) -> String {
    let mut output = String::new();
    let mut indent_level: usize = 0;
    let indent_unit = " ".repeat(indent_width);
    let len = tokens.len();
    let mut i = 0;

    while i < len {
        match &tokens[i] {
            Token::OpenBrace | Token::OpenBracket | Token::OpenParen => {
                let ch = match &tokens[i] {
                    Token::OpenBrace => '{',
                    Token::OpenBracket => '[',
                    Token::OpenParen => '(',
                    _ => unreachable!(),
                };

                // Check if next token is the matching close delimiter (empty body)
                let is_empty = i + 1 < len
                    && matches!(
                        (&tokens[i], &tokens[i + 1]),
                        (Token::OpenBrace, Token::CloseBrace)
                            | (Token::OpenBracket, Token::CloseBracket)
                            | (Token::OpenParen, Token::CloseParen)
                    );

                if is_empty {
                    let close_ch = match ch {
                        '{' => '}',
                        '[' => ']',
                        '(' => ')',
                        _ => unreachable!(),
                    };
                    emitter.emit_bracket(&mut output, ch);
                    emitter.emit_bracket(&mut output, close_ch);
                    i += 2; // skip both open and close
                    continue;
                }

                // Check if paren contains a single value with no commas (e.g. Some(42))
                // Keep inline as Some(42) instead of expanding to multiple lines
                if matches!(&tokens[i], Token::OpenParen) {
                    if let Some(single) = single_paren_value(&tokens[i..]) {
                        emitter.emit_bracket(&mut output, '(');
                        emitter.emit_value(&mut output, &single);
                        emitter.emit_bracket(&mut output, ')');
                        // Skip open paren + value + optional trailing comma + close paren
                        let mut skip = 1; // skip open paren (already at i)
                        skip += 1; // skip value
                        if i + skip < len && matches!(tokens[i + skip], Token::Comma) {
                            skip += 1; // skip trailing comma
                        }
                        skip += 1; // skip close paren
                        i += skip;
                        continue;
                    }
                }

                emitter.emit_bracket(&mut output, ch);
                indent_level += 1;
                output.push('\n');
                push_indent(&mut output, &indent_unit, indent_level);
            }
            Token::CloseBrace | Token::CloseBracket | Token::CloseParen => {
                let ch = match &tokens[i] {
                    Token::CloseBrace => '}',
                    Token::CloseBracket => ']',
                    Token::CloseParen => ')',
                    _ => unreachable!(),
                };
                // Add trailing comma if the previous token wasn't a comma
                if i > 0
                    && !matches!(
                        tokens[i - 1],
                        Token::Comma | Token::OpenBrace | Token::OpenBracket | Token::OpenParen
                    )
                {
                    emitter.emit_punctuation(&mut output, ",");
                }
                indent_level = indent_level.saturating_sub(1);
                output.push('\n');
                push_indent(&mut output, &indent_unit, indent_level);
                emitter.emit_bracket(&mut output, ch);
            }
            Token::Comma => {
                emitter.emit_punctuation(&mut output, ",");
                // Skip newline if next token is a close delimiter (input already has trailing comma)
                let next_is_close = i + 1 < len
                    && matches!(
                        tokens[i + 1],
                        Token::CloseBrace | Token::CloseBracket | Token::CloseParen
                    );
                if !next_is_close {
                    output.push('\n');
                    push_indent(&mut output, &indent_unit, indent_level);
                }
            }
            Token::Colon => {
                emitter.emit_punctuation(&mut output, ": ");
            }
            Token::Text(text) => {
                if i + 1 < len && matches!(tokens[i + 1], Token::OpenBrace) {
                    // Type name (before {)
                    emitter.emit_type_name(&mut output, text);
                    output.push(' ');
                } else if i + 1 < len && matches!(tokens[i + 1], Token::Colon) {
                    // Key (before :)
                    emitter.emit_key(&mut output, text);
                } else if i + 1 < len
                    && matches!(tokens[i + 1], Token::OpenParen | Token::OpenBracket)
                {
                    // Type name (before ( or [)
                    emitter.emit_type_name(&mut output, text);
                } else {
                    // Value
                    emitter.emit_value(&mut output, text);
                }
            }
        }
        i += 1;
    }

    output
}

/// Check if a paren group contains exactly one simple text value.
/// Returns the text if so, None otherwise.
/// Matches: `(value)` or `(value,)` where value is a single Text token.
fn single_paren_value(tokens: &[Token]) -> Option<String> {
    if tokens.len() < 3 {
        return None;
    }
    if !matches!(tokens[0], Token::OpenParen) {
        return None;
    }
    let value = match &tokens[1] {
        Token::Text(s) => s.clone(),
        _ => return None,
    };
    // (value) or (value,)
    match tokens.get(2) {
        Some(Token::CloseParen) => Some(value),
        Some(Token::Comma) => {
            if matches!(tokens.get(3), Some(Token::CloseParen)) {
                Some(value)
            } else {
                None
            }
        }
        _ => None,
    }
}

fn push_indent(output: &mut String, indent_unit: &str, level: usize) {
    for _ in 0..level {
        output.push_str(indent_unit);
    }
}

#[cfg(test)]
mod tests {
    use crate::tokenizer::tokenize;

    use super::*;

    fn fmt(input: &str) -> String {
        let tokens = tokenize(input);
        format_tokens(&tokens, 2)
    }

    #[test]
    fn format_simple_struct() {
        assert_eq!(
            fmt("Foo { bar: 1, baz: 2 }"),
            "\
Foo {
  bar: 1,
  baz: 2,
}"
        );
    }

    #[test]
    fn format_nested_struct() {
        assert_eq!(
            fmt("Foo { bar: 1, inner: Bar { x: 2 } }"),
            "\
Foo {
  bar: 1,
  inner: Bar {
    x: 2,
  },
}"
        );
    }

    #[test]
    fn format_array() {
        assert_eq!(
            fmt("[1, 2, 3]"),
            "\
[
  1,
  2,
  3,
]"
        );
    }

    #[test]
    fn format_empty_struct() {
        assert_eq!(fmt("Foo {}"), "Foo {}");
    }

    #[test]
    fn format_empty_array() {
        assert_eq!(fmt("[]"), "[]");
    }

    #[test]
    fn format_enum_some() {
        // Single value in parens stays inline
        assert_eq!(fmt("Some(42)"), "Some(42)");
    }

    #[test]
    fn format_enum_some_with_trailing_comma() {
        // Single value with trailing comma stays inline
        assert_eq!(fmt("Some(42,)"), "Some(42)");
    }

    #[test]
    fn format_deeply_nested() {
        assert_eq!(
            fmt("A { b: B { c: C { d: 1 } } }"),
            "\
A {
  b: B {
    c: C {
      d: 1,
    },
  },
}"
        );
    }

    #[test]
    fn format_mixed_delimiters() {
        assert_eq!(
            fmt("Foo { items: [1, 2], pair: (3, 4) }"),
            "\
Foo {
  items: [
    1,
    2,
  ],
  pair: (
    3,
    4,
  ),
}"
        );
    }

    #[test]
    fn format_with_string_value() {
        assert_eq!(
            fmt(r#"Foo { name: "hello", count: 5 }"#),
            "\
Foo {
  name: \"hello\",
  count: 5,
}"
        );
    }

    #[test]
    fn format_single_value() {
        assert_eq!(fmt("42"), "42");
    }

    #[test]
    fn format_none() {
        assert_eq!(fmt("None"), "None");
    }

    #[test]
    fn format_trailing_comma_in_input() {
        // Single value with trailing comma stays inline
        assert_eq!(fmt("Foo(1,)"), "Foo(1)");
    }

    #[test]
    fn format_multi_value_paren() {
        // Multiple values in parens still expand
        assert_eq!(
            fmt("Foo(1, 2)"),
            "\
Foo(
  1,
  2,
)"
        );
    }

    #[test]
    fn format_hashmap() {
        assert_eq!(
            fmt("{1: \"a\", 2: \"b\"}"),
            "\
{
  1: \"a\",
  2: \"b\",
}"
        );
    }

    #[test]
    fn format_hashset() {
        assert_eq!(
            fmt("{1, 2, 3}"),
            "\
{
  1,
  2,
  3,
}"
        );
    }

    #[test]
    fn format_unicode() {
        assert_eq!(
            fmt("Foo { name: \"太郎\", emoji: \"🦀\" }"),
            "\
Foo {
  name: \"太郎\",
  emoji: \"🦀\",
}"
        );
    }

    #[test]
    fn format_indent_zero() {
        let tokens = tokenize("Foo { x: 1 }");
        assert_eq!(
            format_tokens(&tokens, 0),
            "\
Foo {
x: 1,
}"
        );
    }

    #[test]
    fn format_custom_indent() {
        let tokens = tokenize("Foo { x: 1 }");
        assert_eq!(
            format_tokens(&tokens, 4),
            "\
Foo {
    x: 1,
}"
        );
    }
}