eon_syntax 0.2.0

Describes the syntax of the Eon config format, with parsing and pretty-printing
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Serialize a [`TokenTree`] to an Eon string.

use crate::token_tree::{TokenKeyValue, TokenList, TokenMap, TokenTree, TokenValue, TokenVariant};

/// How to format an Eon document.
///
/// If you mess up the options too much (e.g. set the indentation to something that is not whitespace)
/// you might end up with a document that is not valid Eon syntax.
#[derive(Clone, Debug)]
pub struct FormatOptions {
    /// `"\t"`
    pub indentation: String,

    /// `"\n"`
    pub newline: String,

    /// `" "`
    pub space_before_suffix_comment: String,

    /// `": "`
    pub key_value_separator: String,

    /// Surround the top-level map in { } with an extra level of indentation.
    pub always_include_outer_braces: bool,
}

impl Default for FormatOptions {
    fn default() -> Self {
        Self {
            // A tab character allows users to configure their preferred indentation size in their editor.
            // It's the best default.
            indentation: "\t".to_owned(),
            newline: "\n".to_owned(),
            space_before_suffix_comment: " ".to_owned(),
            key_value_separator: ": ".to_owned(),
            always_include_outer_braces: false,
        }
    }
}

impl FormatOptions {
    /// Create a new [`FormatOptions`] with the default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the indentation string.
    pub fn with_indentation(mut self, indentation: String) -> Self {
        self.indentation = indentation;
        self
    }

    /// Set the newline string.
    pub fn with_newline(mut self, newline: String) -> Self {
        self.newline = newline;
        self
    }
}

impl TokenTree<'_> {
    /// Format as an Eon string.
    pub fn format(&self, options: &FormatOptions) -> String {
        let mut f = Formatter::new(options);

        if !f.options.always_include_outer_braces {
            if let TokenValue::Map(map) = &self.value {
                f.indented_comments(&self.prefix_comments);
                f.map_content(map);
                f.suffix_comment(&self.suffix_comment);
                return f.finish();
            }
        }

        f.indented_value(self);
        f.finish()
    }
}

struct Formatter<'o> {
    options: &'o FormatOptions,
    indent: usize,
    out: String,
}

impl<'o> Formatter<'o> {
    fn new(options: &'o FormatOptions) -> Self {
        Self {
            options,
            indent: 0,
            out: String::new(),
        }
    }

    fn finish(self) -> String {
        debug_assert_eq!(
            self.indent, 0,
            "Formatter finished with non-zero indent of {}",
            self.indent
        );
        self.out
    }

    fn newline(&mut self) {
        self.out.push_str(&self.options.newline);
    }

    fn add_indent(&mut self) {
        for _ in 0..self.indent {
            self.out.push_str(&self.options.indentation);
        }
    }

    fn indented_comments(&mut self, comments: &[&str]) {
        for &comment in comments {
            self.add_indent();
            self.out.push_str(comment);
            self.newline();
        }
    }

    fn indented_value(&mut self, value: &TokenTree<'_>) {
        let TokenTree {
            prefix_comments,
            value,
            suffix_comment,
            span: _,
        } = value;
        self.indented_comments(prefix_comments);
        self.add_indent();
        self.value(value);
        self.suffix_comment(suffix_comment);
    }

    #[expect(clippy::ref_option_ref)]
    fn suffix_comment(&mut self, suffix_comment: &Option<&str>) {
        if let Some(suffix_comment) = suffix_comment {
            self.out.push(' ');
            self.out.push_str(suffix_comment);
        }
    }

    fn value(&mut self, value: &TokenValue<'_>) {
        match value {
            TokenValue::Identifier(slice)
            | TokenValue::Number(slice)
            | TokenValue::QuotedString(slice) => {
                self.out.push_str(slice);
            }
            TokenValue::List(list) => {
                self.list(list);
            }
            TokenValue::Map(map) => {
                self.map(map);
            }
            TokenValue::Variant(variant) => {
                self.variant(variant);
            }
        }
    }

    fn list(&mut self, list: &TokenList<'_>) {
        let TokenList {
            values,
            closing_comments,
        } = list;

        if list.values.is_empty() && closing_comments.is_empty() {
            self.out.push_str("[]");
            return;
        }

        if should_format_list_on_one_line(list) {
            self.out.push('[');
            for (i, value) in values.iter().enumerate() {
                self.value(&value.value);
                if i + 1 < values.len() {
                    self.out.push_str(", "); // We use commas for single-line lists, just for extra readability
                }
            }
            self.out.push(']');
        } else {
            self.out.push('[');
            self.indent += 1;
            self.newline();
            self.list_content(list);
            self.indent -= 1;
            self.add_indent();
            self.out.push(']');
        }
    }

    fn list_content(&mut self, list: &TokenList<'_>) {
        let TokenList {
            values,
            closing_comments,
        } = list;

        for (i, value) in values.iter().enumerate() {
            if 0 < i && !value.prefix_comments.is_empty() {
                self.newline();
            }
            self.indented_value(value);
            self.newline();
        }

        if !closing_comments.is_empty() {
            if !values.is_empty() {
                self.newline();
            }
            self.indented_comments(closing_comments);
        }
    }

    fn map(&mut self, map: &TokenMap<'_>) {
        let TokenMap {
            key_values,
            closing_comments,
        } = map;

        if key_values.is_empty() && closing_comments.is_empty() {
            self.out.push_str("{}");
            return;
        }

        self.out.push('{');
        self.indent += 1;
        self.newline();
        self.map_content(map);
        self.indent -= 1;
        self.add_indent();
        self.out.push('}');
    }

    fn map_content(&mut self, map: &TokenMap<'_>) {
        let TokenMap {
            key_values,
            closing_comments,
        } = map;

        for (i, key_value) in key_values.iter().enumerate() {
            if 0 < i && !key_value.key.prefix_comments.is_empty() {
                self.newline();
            }
            self.indented_key_value(key_value);
            self.newline();
        }

        if !closing_comments.is_empty() {
            if !key_values.is_empty() {
                self.newline();
            }
            self.indented_comments(closing_comments);
        }
    }

    fn indented_key_value(&mut self, key_value: &TokenKeyValue<'_>) {
        let TokenKeyValue { key, value } = key_value;
        self.indented_comments(&key.prefix_comments);
        self.indented_comments(&value.prefix_comments);
        self.add_indent();
        self.value(&key.value);
        self.out.push_str(&self.options.key_value_separator);
        self.value(&value.value);
        self.suffix_comment(&value.suffix_comment);
    }

    fn variant(&mut self, variant: &TokenVariant<'_>) {
        let TokenVariant {
            name_span: _,
            quoted_name,
            values,
            closing_comments,
        } = variant;

        if values.is_empty() && closing_comments.is_empty() {
            self.out.push_str(quoted_name); // Omit parentheses if no values
            return;
        }

        if should_format_variant_on_one_line(variant) {
            self.out.push_str(quoted_name);
            self.out.push('(');
            for (i, value) in values.iter().enumerate() {
                self.value(&value.value);
                if i + 1 < values.len() {
                    self.out.push_str(", "); // We use commas for single-line variants, just for extra readability
                }
            }
            self.out.push(')');
        } else if closing_comments.is_empty()
            && values.len() == 1
            && matches!(values[0].value, TokenValue::Map(_))
        {
            let TokenValue::Map(map) = &values[0].value else {
                unreachable!() // TODO(emilk): replace with if-let chains
            };

            if map.key_values.is_empty() && map.closing_comments.is_empty() {
                self.out.push_str(quoted_name);
                self.out.push_str("({ })");
            } else {
                // A single map variant, like `"VariantName"({ key: value, … })`.
                // Here we avoid double-indenting for nicer/more compact output.
                self.out.push_str(quoted_name);
                self.out.push_str("({");
                self.indent += 1;
                self.newline();
                self.map_content(map);
                self.indent -= 1;
                self.add_indent();
                self.out.push_str("})");
            }
        } else if closing_comments.is_empty()
            && values.len() == 1
            && matches!(values[0].value, TokenValue::List(_))
        {
            let TokenValue::List(list) = &values[0].value else {
                unreachable!() // TODO(emilk): replace with if-let chains
            };

            if list.values.is_empty() && list.closing_comments.is_empty() {
                self.out.push_str(quoted_name);
                self.out.push_str("([ ])");
            } else {
                // A single list variant, like `"VariantName"({ key: value, … })`.
                // Here we avoid double-indenting for nicer/more compact output.
                self.out.push_str(quoted_name);
                self.out.push_str("([");
                self.indent += 1;
                self.newline();
                self.list_content(list);
                self.indent -= 1;
                self.add_indent();
                self.out.push_str("])");
            }
        } else {
            self.out.push_str(quoted_name);
            self.out.push('(');
            self.indent += 1;
            self.newline();
            for (i, value) in values.iter().enumerate() {
                if 0 < i && !value.prefix_comments.is_empty() {
                    self.newline();
                }
                self.newline();
            }

            if !closing_comments.is_empty() {
                if !values.is_empty() {
                    self.newline();
                }
                self.indented_comments(closing_comments);
            }

            self.indent -= 1;
            self.add_indent();
            self.out.push(')');
        }
    }
}

fn should_format_list_on_one_line(list: &TokenList<'_>) -> bool {
    let TokenList {
        values,
        closing_comments,
    } = list;
    closing_comments.is_empty() && should_format_values_on_one_line(values)
}

fn should_format_variant_on_one_line(variant: &TokenVariant<'_>) -> bool {
    let TokenVariant {
        name_span: _,
        quoted_name: _,
        values,
        closing_comments,
    } = variant;
    closing_comments.is_empty() && should_format_values_on_one_line(values)
}

fn should_format_values_on_one_line(values: &[TokenTree<'_>]) -> bool {
    if !values.iter().all(is_simple) {
        return false;
    }

    if values.len() <= 4 && values.iter().all(|tt| tt.value.is_number()) {
        return true; // e.g. [1 2 3 4]
    }

    if values.len() > 4 {
        return false;
    }

    let mut estimated_width = 0;
    for value in values {
        if let TokenValue::QuotedString(string) = &value.value {
            estimated_width += string.len();
        } else {
            estimated_width += 5;
        }
        estimated_width += 2;
    }

    estimated_width < 60
}

fn is_simple(value: &TokenTree<'_>) -> bool {
    if value.prefix_comments.is_empty() && value.suffix_comment.is_none() {
        match &value.value {
            TokenValue::Identifier(_) | TokenValue::Number(_) => true,

            TokenValue::QuotedString(string) => !string.contains('\n'),

            TokenValue::List(list) => {
                let TokenList {
                    values,
                    closing_comments,
                } = list;
                values.is_empty() && closing_comments.is_empty()
            }

            TokenValue::Map(map) => {
                let TokenMap {
                    key_values,
                    closing_comments,
                } = map;
                key_values.is_empty() && closing_comments.is_empty()
            }

            TokenValue::Variant(variant) => {
                let TokenVariant {
                    name_span: _,
                    quoted_name: _,
                    values,
                    closing_comments,
                } = variant;
                values.is_empty() && closing_comments.is_empty()
            }
        }
    } else {
        false
    }
}