nixfmt_rs 0.1.1

Rust implementation of nixfmt with exact Haskell compatibility
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
//! `PrettySimple` implementations for AST nodes

use super::{
    NUMBER_COLOR, PrettySimple, STRING_CONTENT_COLOR, STRING_QUOTE_COLOR, Writer, escape_string,
    format_bracket_list, sub_expr, with_brackets,
};
use crate::format_constructor;
use crate::format_enum;
use crate::format_record;
use crate::types::{
    Ann, Binder, Expression, Item, ParamAttr, Parameter, Selector, SimpleSelector, Span,
    StringPart, Term, Token, TrailingComment, Trivia, Trivium, Whole,
};

/// Generate a `PrettySimple` impl for a primitive/atomic type:
/// `is_simple` and `is_atomic` are always `true`; only `format` varies.
macro_rules! simple_atom {
    ($ty:ty, |$self_:ident, $w:ident| $body:expr) => {
        impl PrettySimple for $ty {
            fn format<W: Writer>(&self, $w: &mut W) {
                let $self_ = self;
                $body
            }
            fn is_simple(&self) -> bool {
                true
            }
            fn is_atomic(&self) -> bool {
                true
            }
        }
    };
}

// &str / String: quoted string literals (pretty-simple's StringLit)
simple_atom!(&str, |s, w| {
    w.write_colored("\"", STRING_QUOTE_COLOR);
    // Escape special characters to match Haskell's show behavior
    w.write_colored(&escape_string(s), STRING_CONTENT_COLOR);
    w.write_colored("\"", STRING_QUOTE_COLOR);
});
simple_atom!(String, |s, w| s.as_str().format(w));

// isize / usize: number literals (pretty-simple's NumberLit)
simple_atom!(isize, |n, w| w.write_colored(&n.to_string(), NUMBER_COLOR));
simple_atom!(usize, |n, w| w.write_colored(&n.to_string(), NUMBER_COLOR));

simple_atom!(bool, |b, w| w.write_plain(if *b {
    "True"
} else {
    "False"
}));

impl PrettySimple for Whole<Expression> {
    fn format<W: Writer>(&self, w: &mut W) {
        self.value.format(w);
        w.newline(); // Final newline at end of output
    }
}

impl PrettySimple for Expression {
    fn format<W: Writer>(&self, w: &mut W) {
        format_enum!(self, w, {
            Term(term) => [term],
            With(kw, expr1, semi, expr2) => [kw, &**expr1, semi, &**expr2],
            Let(kw, items, in_kw, body) => [kw, &items.0, in_kw, &**body],
            Assert(kw, expr1, semi, expr2) => [kw, &**expr1, semi, &**expr2],
            If(if_kw, cond, then_kw, then_expr, else_kw, else_expr) => [if_kw, &**cond, then_kw, &**then_expr, else_kw, &**else_expr],
            Abstraction(param, colon, body) => [param, colon, &**body],
            Application(func, arg) => [&**func, &**arg],
            Operation(left, op, right) => [&**left, op, &**right],
            MemberCheck(expr, question, selectors) => [&**expr, question, selectors],
            Negation(minus, expr) => [minus, &**expr],
            Inversion(not, expr) => [not, &**expr],
        });
    }
}

impl PrettySimple for Term {
    fn format<W: Writer>(&self, w: &mut W) {
        format_enum!(self, w, {
            Token(leaf) => [leaf],
            SimpleString(string) => [string],
            IndentedString(string) => [string],
            Path(path) => [path],
            List(open, items, close) => [open, &items.0, close],
            Set(rec, open, items, close) => [rec, open, &items.0, close],
            Selection(term, selectors, or_default) => [&**term, selectors, or_default],
            Parenthesized(open, expr, close) => [open, &**expr, close],
        });
    }
}

impl<T: PrettySimple> PrettySimple for Item<T> {
    fn format<W: Writer>(&self, w: &mut W) {
        match self {
            Self::Item(inner) => {
                format_constructor!(w, "Item", [inner]);
            }
            Self::Comments(trivia) => {
                w.write_plain("Comments");
                sub_expr(w, trivia);
            }
        }
    }

    fn is_simple(&self) -> bool {
        match self {
            Self::Item(_) => false,
            Self::Comments(trivia) => trivia.is_simple(),
        }
    }
}

impl PrettySimple for Binder {
    fn format<W: Writer>(&self, w: &mut W) {
        format_enum!(self, w, {
            Inherit(kw, from, selectors, semi) => [kw, from, selectors, semi],
            Assignment(sels, eq, expr, semi) => [sels, eq, expr, semi],
        });
    }
}

impl PrettySimple for Selector {
    fn format<W: Writer>(&self, w: &mut W) {
        format_constructor!(w, "Selector", [&self.dot, &self.selector]);
    }
}

impl PrettySimple for SimpleSelector {
    fn format<W: Writer>(&self, w: &mut W) {
        // Use Haskell constructor names for compatibility with nixfmt --ast output
        match self {
            Self::ID(leaf) => {
                format_constructor!(w, "IDSelector", [leaf]);
            }
            Self::Interpol(part) => {
                format_constructor!(w, "InterpolSelector", [part]);
            }
            Self::String(string) => {
                format_constructor!(w, "StringSelector", [string]);
            }
        }
    }
}

impl PrettySimple for Trivium {
    fn format<W: Writer>(&self, w: &mut W) {
        format_enum!(self, w, {
            EmptyLine() => [],
            LineComment(text) => [text],
            BlockComment(is_doc, lines) => [is_doc, lines],
            LanguageAnnotation(text) => [text],
        });
    }

    fn is_simple(&self) -> bool {
        // In Haskell: constructor applications with simple args can be simple
        // BlockComment True ["doc"] → all arguments simple → renders inline
        // BlockComment True ["a","b","c"] → Vec with 3 elements NOT simple → renders multiline
        match self {
            // Nullary constructor / single string arg are simple.
            Self::EmptyLine() | Self::LineComment(_) | Self::LanguageAnnotation(_) => true,
            Self::BlockComment(_is_doc, lines) => lines.is_simple(),
        }
    }

    fn is_atomic(&self) -> bool {
        // Only nullary constructors are atomic (single element in parsed form)
        // EmptyLine → Other "EmptyLine" → atomic
        // LineComment "x" → Other "LineComment " + StringLit → not atomic
        matches!(self, Self::EmptyLine())
    }
}

// Haskell `Trivia` is `Seq Trivium` since nixfmt 1.2.0; Show renders as `fromList [..]`.
impl PrettySimple for Trivia {
    fn format<W: Writer>(&self, w: &mut W) {
        w.write_plain("fromList");
        sub_expr(w, &self.to_vec());
    }

    fn renders_inline_parens(&self) -> bool {
        // `( fromList [ EmptyLine ] )` stays on one line when the inner list is simple.
        self.to_vec().is_simple()
    }
}

impl PrettySimple for Parameter {
    fn format<W: Writer>(&self, w: &mut W) {
        // Use Haskell constructor names for compatibility with nixfmt --ast output
        match self {
            Self::ID(leaf) => {
                format_constructor!(w, "IDParameter", [leaf]);
            }
            Self::Set(open, attrs, close) => {
                format_constructor!(w, "SetParameter", [open, attrs, close]);
            }
            Self::Context(left, at, right) => {
                format_constructor!(w, "ContextParameter", [&**left, at, &**right]);
            }
        }
    }
}

impl PrettySimple for ParamAttr {
    fn format<W: Writer>(&self, w: &mut W) {
        format_enum!(self, w, {
            ParamAttr(name, default, comma) => [name, default, comma],
            ParamEllipsis(ellipsis) => [ellipsis],
        });
    }
}

impl PrettySimple for StringPart {
    fn format<W: Writer>(&self, w: &mut W) {
        match self {
            Self::TextPart(text) => {
                format_constructor!(w, "TextPart", [text]);
            }
            Self::Interpolation(whole) => {
                w.write_plain("Interpolation");
                w.write_plain(" ");
                whole.value.format(w);
            }
        }
    }

    fn is_simple(&self) -> bool {
        // For Vec inline rendering: constructor applications with simple args behave as simple
        // In Haskell: the row [Other "TextPart ", StringLit "hello"] passes `all isSimple`
        // So [TextPart "hello"] can be rendered inline
        //
        // However, for structural simplicity (Vec::is_simple), this creates a multi-element row,
        // so the Brackets itself is NOT simple. That's handled by Vec::is_simple logic.
        match self {
            Self::TextPart(_) => true,
            Self::Interpolation(_) => false,
        }
    }
}

/// `PrettySimple` for Token - constructor applications for data-carrying tokens
impl PrettySimple for Token {
    fn format<W: Writer>(&self, w: &mut W) {
        format_enum!(self, w, {
            Integer(s) => [&s.as_str()],
            Float(s) => [&s.as_str()],
            Identifier(s) => [&s.as_str()],
            EnvPath(s) => [&s.as_str()],
            _ => {
                w.write_plain(&format!("{self:?}"));
            }
        });
    }

    fn is_simple(&self) -> bool {
        true
    }
}

/// Helper wrapper for formatting span as "Pos N" for Haskell compatibility
/// Even though we use Span internally, the pretty-printed AST should match Haskell
#[derive(Debug)]
struct SpanWrapper(Span);

impl PrettySimple for SpanWrapper {
    fn format<W: Writer>(&self, w: &mut W) {
        use crate::error::context::ErrorContext;

        w.write_plain("Pos ");
        let ctx = ErrorContext::new(w.source(), None);
        let pos = ctx.position(self.0.start);
        pos.line.format(w);
    }

    fn is_simple(&self) -> bool {
        true
    }
}

/// `PrettySimple` for `TrailingComment` - constructor with comment contents
/// In Haskell's Show output, this becomes a Parens with simple elements,
/// so it formats inline as: ( `TrailingComment` "text" )
impl PrettySimple for TrailingComment {
    fn format<W: Writer>(&self, w: &mut W) {
        with_brackets(w, "(", ")", true, |w, _| {
            w.write_plain(" ");
            format_constructor!(w, "TrailingComment", [&&*self.0]);
            w.write_plain(" ");
        });
    }

    fn has_delimiters(&self) -> bool {
        true
    }
}

impl<T: PrettySimple> PrettySimple for Ann<T> {
    fn format<W: Writer>(&self, w: &mut W) {
        w.write_plain("Ann");

        format_record!(
            w,
            [
                ("preTrivia", &self.pre_trivia),
                ("sourceLine", &SpanWrapper(self.span)),
                ("value", &self.value),
                ("trailComment", &self.trail_comment),
            ]
        );
    }
}

/// Generic `PrettySimple` for Vec<T>
/// Based on pretty-simple's Brackets in Show output
/// Implements the `list` function logic:
/// - Vec<T> in Rust corresponds to a single "row" [[T]] in Haskell's `CommaSeparated`
/// - Empty vec: []
/// - All elements simple: [ elem1, elem2, ... ] (inline, space-separated with commas)
/// - Any element complex: multiline with comma-first
impl<T: PrettySimple> PrettySimple for Vec<T> {
    fn format<W: Writer>(&self, w: &mut W) {
        format_bracket_list(w, self, true);
    }

    fn is_simple(&self) -> bool {
        // Mirrors pretty-simple's isListSimple:
        // isListSimple [[e]] = isSimple e && case e of Other s -> not $ any isSpace s ; _ -> True
        // isListSimple _:_ = False
        // isListSimple [] = True
        if self.is_empty() {
            return true;
        }
        // Single element: simple if it's atomic OR (simple AND has delimiters)
        // In Haskell: [[e]] matches only when the row has ONE element
        // - [EmptyLine] → row: [Other "EmptyLine"] → 1 element → atomic → simple
        // - [TextPart "x"] → row: [Other, StringLit] → 2 elements → NOT simple
        // - [[]] → row: [Brackets []] → 1 element, simple delimited → simple
        if self.len() == 1 {
            let item = &self[0];
            return item.is_atomic() || (item.is_simple() && item.has_delimiters());
        }
        false
    }

    fn has_delimiters(&self) -> bool {
        true
    }

    fn is_empty(&self) -> bool {
        <Self>::is_empty(self)
    }
}

/// Generic `PrettySimple` for Option<T>
/// Based on Haskell's Show instance for Maybe
impl<T: PrettySimple> PrettySimple for Option<T> {
    fn format<W: Writer>(&self, w: &mut W) {
        match self {
            Some(value) => {
                format_constructor!(w, "Just", [value]);
            }
            None => {
                w.write_plain("Nothing");
            }
        }
    }

    fn is_simple(&self) -> bool {
        self.is_none()
    }
}

/// `PrettySimple` for tuples (A, B)
/// Based on Haskell's Show instance for tuples
impl<A: PrettySimple, B: PrettySimple> PrettySimple for (A, B) {
    fn format<W: Writer>(&self, w: &mut W) {
        with_brackets(w, "(", ")", true, |w, paren_color| {
            w.write_plain(" ");
            self.0.format(w);
            w.newline();
            w.write_colored(",", paren_color);
            w.write_plain(" ");
            self.1.format(w);
            w.newline();
        });
    }

    fn has_delimiters(&self) -> bool {
        true
    }
}

/// `PrettySimple` for Box<T>
/// Box is transparent in Haskell's Show output
impl<T: PrettySimple> PrettySimple for Box<T> {
    fn format<W: Writer>(&self, w: &mut W) {
        (**self).format(w);
    }

    fn is_simple(&self) -> bool {
        (**self).is_simple()
    }
}