rlsp-fmt 0.1.9

A reusable pretty-printing engine for rlsp language servers
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
405
406
407
408
409
410
411
// SPDX-License-Identifier: MIT

use crate::FormatOptions;
use crate::ir::Doc;

/// Rendering mode for the printer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    Flat,
    Break,
}

/// Work item: current indent level, mode, and document reference.
struct Work<'a> {
    indent: usize,
    mode: Mode,
    doc: &'a Doc,
}

/// Render a `Doc` to a `String` using the Wadler-Lindig algorithm.
///
/// The algorithm processes a work stack of `(indent, mode, doc)` triples.
/// `Group` nodes attempt flat mode by checking whether the group fits within
/// the remaining line width (`fits` lookahead). If it doesn't fit, the group
/// switches to break mode.
///
/// # Examples
///
/// ```
/// use rlsp_fmt::{concat, group, indent, line, text, format, FormatOptions};
///
/// let doc = group(concat(vec![
///     text("["),
///     indent(concat(vec![line(), text("a"), text(","), line(), text("b")])),
///     line(),
///     text("]"),
/// ]));
///
/// // Wide enough: rendered flat on one line.
/// let wide = format(&doc, &FormatOptions::default());
/// assert_eq!(wide, "[ a, b ]");
///
/// // Narrow: rendered across multiple lines.
/// let opts = FormatOptions { print_width: 5, ..Default::default() };
/// assert!(format(&doc, &opts).contains('\n'));
/// ```
#[must_use]
pub fn format(doc: &Doc, options: &FormatOptions) -> String {
    let mut output = String::new();
    let mut col: usize = 0; // current column position

    let mut stack: Vec<Work<'_>> = vec![Work {
        indent: 0,
        mode: Mode::Break,
        doc,
    }];

    while let Some(Work { indent, mode, doc }) = stack.pop() {
        match doc {
            Doc::Text(s) => {
                output.push_str(s);
                col += s.len();
            }
            Doc::HardLine => {
                output.push('\n');
                push_indent(&mut output, indent, options);
                col = indent_width(indent, options);
            }
            Doc::Line => match mode {
                Mode::Flat => {
                    output.push(' ');
                    col += 1;
                }
                Mode::Break => {
                    output.push('\n');
                    push_indent(&mut output, indent, options);
                    col = indent_width(indent, options);
                }
            },
            Doc::Indent(inner) => {
                stack.push(Work {
                    indent: indent + 1,
                    mode,
                    doc: inner,
                });
            }
            Doc::Concat(docs) => {
                // Push in reverse so the first element is processed first.
                for child in docs.iter().rev() {
                    stack.push(Work {
                        indent,
                        mode,
                        doc: child,
                    });
                }
            }
            Doc::Group(inner) => {
                // Try flat mode first; fall back to break if it doesn't fit.
                let effective_mode =
                    if mode == Mode::Flat || fits(inner, options.print_width.saturating_sub(col)) {
                        Mode::Flat
                    } else {
                        Mode::Break
                    };
                stack.push(Work {
                    indent,
                    mode: effective_mode,
                    doc: inner,
                });
            }
            Doc::FlatAlt { flat, break_ } => {
                let chosen = match mode {
                    Mode::Flat => flat.as_ref(),
                    Mode::Break => break_.as_ref(),
                };
                stack.push(Work {
                    indent,
                    mode,
                    doc: chosen,
                });
            }
        }
    }

    output
}

/// Returns `true` if `doc` fits within `remaining` columns when rendered flat.
///
/// The lookahead uses its own flat-mode stack. It returns `false` as soon as
/// any content would exceed `remaining`, or when a `HardLine` is encountered
/// (which forces a break regardless of mode).
fn fits(doc: &Doc, remaining: usize) -> bool {
    // Track remaining space using a saturating sentinel: if consumed > 0 after
    // saturation we know it didn't fit.
    let mut rem: Option<usize> = Some(remaining);
    let mut stack: Vec<&Doc> = vec![doc];

    while let Some(doc) = stack.pop() {
        if rem.is_none() {
            return false;
        }
        match doc {
            Doc::Text(s) => {
                rem = rem.and_then(|r| r.checked_sub(s.len()));
            }
            Doc::HardLine => {
                // Hard line always breaks — doesn't fit in flat lookahead.
                return false;
            }
            Doc::Line => {
                // In flat mode, Line renders as a single space.
                rem = rem.and_then(|r| r.checked_sub(1));
            }
            Doc::Indent(inner) | Doc::Group(inner) => {
                stack.push(inner);
            }
            Doc::Concat(docs) => {
                for child in docs.iter().rev() {
                    stack.push(child);
                }
            }
            Doc::FlatAlt { flat, .. } => {
                // Lookahead is always flat — use the flat variant.
                stack.push(flat.as_ref());
            }
        }
    }

    rem.is_some()
}

/// Write the indentation string for a given indent level to `out`.
fn push_indent(out: &mut String, indent: usize, options: &FormatOptions) {
    if options.use_tabs {
        for _ in 0..indent {
            out.push('\t');
        }
    } else {
        let spaces = indent * options.tab_width;
        for _ in 0..spaces {
            out.push(' ');
        }
    }
}

/// Return the column width of an indentation level.
const fn indent_width(indent: usize, options: &FormatOptions) -> usize {
    if options.use_tabs {
        // Tabs are visually ambiguous; count as 1 column each for fit checks.
        indent
    } else {
        indent * options.tab_width
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::FormatOptions;
    use crate::ir::{concat, flat_alt, group, hard_line, indent, join, line, text};

    fn opts(print_width: usize) -> FormatOptions {
        FormatOptions {
            print_width,
            ..Default::default()
        }
    }

    // Simple text renders as-is.
    #[test]
    fn simple_text() {
        let doc = text("hello");
        assert_eq!(format(&doc, &opts(80)), "hello");
    }

    // Group that fits on one line → flat mode (single line).
    #[test]
    fn group_fits_flat() {
        let doc = group(concat(vec![
            text("["),
            indent(concat(vec![
                line(),
                text("a"),
                text(","),
                line(),
                text("b"),
            ])),
            line(),
            text("]"),
        ]));
        let result = format(&doc, &opts(80));
        // In flat mode, Line → space
        assert_eq!(result, "[ a, b ]");
    }

    // Group that doesn't fit → break mode (multi-line).
    #[test]
    fn group_breaks_when_too_wide() {
        let doc = group(concat(vec![
            text("["),
            indent(concat(vec![
                line(),
                text("long_item_a"),
                text(","),
                line(),
                text("long_item_b"),
            ])),
            line(),
            text("]"),
        ]));
        let result = format(&doc, &opts(10));
        // In break mode, Line → newline + indent
        assert!(
            result.contains('\n'),
            "expected newline in result: {result:?}"
        );
    }

    // Nested groups: inner group that fits stays flat even when outer breaks.
    #[test]
    fn nested_groups_independent() {
        // The inner group ("a b" = 3 chars when flat) is placed on a new
        // indented line when the outer breaks. At width 5 the outer cannot fit
        // on one line ("prefix: a b" = 12 chars), so it breaks. The inner
        // group starts fresh at col=2 (indent), where 3 chars fit → flat.
        let inner = group(concat(vec![text("a"), line(), text("b")]));
        let outer = group(concat(vec![
            text("prefix:"),
            indent(concat(vec![line(), inner])),
        ]));
        // Wide: everything fits on one line.
        assert_eq!(format(&outer, &opts(80)), "prefix: a b");
        // Narrow: outer breaks, inner stays flat on the indented line.
        let result = format(&outer, &opts(5));
        assert!(result.contains('\n'), "expected outer to break: {result:?}");
        assert!(
            result.contains("a b"),
            "expected inner to stay flat: {result:?}"
        );
    }

    // Indent increases indentation in break mode.
    #[test]
    fn indent_increases_indentation() {
        let doc = group(concat(vec![
            text("key:"),
            indent(concat(vec![line(), text("value")])),
        ]));
        let result = format(&doc, &opts(5));
        // Should break and indent "value" by tab_width (default 2)
        assert_eq!(result, "key:\n  value");
    }

    // HardLine forces break even inside a flat group.
    #[test]
    fn hard_line_forces_break_in_flat() {
        let doc = group(concat(vec![text("a"), hard_line(), text("b")]));
        let result = format(&doc, &opts(80));
        assert_eq!(result, "a\nb");
    }

    // FlatAlt uses flat variant in flat mode and break variant in break mode.
    #[test]
    fn flat_alt_modes() {
        let doc_flat = group(flat_alt(text("flat"), text("break")));
        assert_eq!(format(&doc_flat, &opts(80)), "flat");

        // Force break by making the group too wide.
        let doc_break = group(concat(vec![
            text("very_long_prefix_that_will_not_fit_on_one_line"),
            flat_alt(text("_flat"), text("_break")),
        ]));
        let result = format(&doc_break, &opts(10));
        assert!(result.ends_with("_break"), "result: {result:?}");
    }

    // join() intersperse separator between items.
    #[test]
    fn join_intersperse() {
        let sep = text(", ");
        let items = vec![text("a"), text("b"), text("c")];
        let doc = join(&sep, items);
        assert_eq!(format(&doc, &opts(80)), "a, b, c");
    }

    // join() with empty list returns empty.
    #[test]
    fn join_empty() {
        let sep = text(", ");
        let doc = join(&sep, vec![]);
        assert_eq!(format(&doc, &opts(80)), "");
    }

    // use_tabs produces tab characters.
    #[test]
    fn use_tabs() {
        let doc = group(concat(vec![
            text("key:"),
            indent(concat(vec![line(), text("value")])),
        ]));
        let options = FormatOptions {
            print_width: 5,
            use_tabs: true,
            tab_width: 4,
        };
        let result = format(&doc, &options);
        assert_eq!(result, "key:\n\tvalue");
    }

    // Various print_width settings.
    #[test]
    fn print_width_controls_breaks() {
        let items = vec![text("item_one"), text("item_two"), text("item_three")];
        let sep = concat(vec![text(","), line()]);
        let doc = group(concat(vec![
            text("["),
            indent(concat(vec![line(), join(&sep, items)])),
            line(),
            text("]"),
        ]));

        // Wide enough to fit on one line.
        let wide = format(&doc, &opts(80));
        assert!(!wide.contains('\n'));

        // Narrow: must break.
        let narrow = format(&doc, &opts(10));
        assert!(narrow.contains('\n'));
    }

    // GAP-F1: Group(FlatAlt { flat: short_doc, expanded: long_doc }) where short_doc
    // fits — printer must choose flat mode and render the flat variant.
    #[test]
    fn group_flat_alt_short_fits_uses_flat_variant() {
        // "ok" (2 chars) fits in any reasonable width; long_doc is long enough to
        // guarantee break mode if the printer were to mis-choose.
        let short_doc = text("ok");
        let long_doc = text("this_is_a_very_long_expanded_form_that_would_not_fit");
        let doc = Doc::Group(Box::new(Doc::FlatAlt {
            flat: Box::new(short_doc),
            break_: Box::new(long_doc),
        }));
        let result = format(&doc, &opts(80));
        // Flat mode selected because "ok" fits; flat variant ("ok") must be rendered.
        assert_eq!(result, "ok");
    }

    // GAP-F2: indent_width with use_tabs=true returns the indent level itself (1 per
    // tab, not 1 * tab_width), because tabs are counted as 1 column for fit checks.
    #[test]
    fn indent_width_use_tabs_counts_tabs_as_one_column_each() {
        // With use_tabs=true, indent_width(3, options) must return 3 (not 3 * tab_width).
        // This prevents over-estimating available width when computing fits() with tabs.
        let options = FormatOptions {
            print_width: 80,
            tab_width: 4, // tab_stop is 4, but must NOT be multiplied
            use_tabs: true,
        };
        // indent_width(3, ...) → 3 (each tab = 1 column for width accounting)
        assert_eq!(indent_width(3, &options), 3);
    }

    // GAP-F3: format(Doc::Concat(vec![]), ...) returns an empty string.
    #[test]
    fn concat_empty_vec_renders_empty_string() {
        let doc = Doc::Concat(vec![]);
        let result = format(&doc, &opts(80));
        assert_eq!(result, "");
    }
}