1
use base64::Engine;
2
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
3

            
4
use super::value::{Fraction, Pair, Value};
5
use crate::ast::Number;
6

            
7
const BYTES_INLINE_THRESHOLD: usize = 32;
8

            
9
/// How values print: strings quoted and escaped or bare as `princ` does, and
10
/// a whole scalar as `n/1` or, for a display cell, as `n`.
11
#[derive(Clone, Copy)]
12
enum Style {
13
    Readable,
14
    Plain,
15
    Display,
16
}
17

            
18
#[must_use]
19
4820016
pub fn format_value(value: &Value) -> String {
20
4820016
    render(value, Style::Readable)
21
4820016
}
22

            
23
/// Prints `value` as `PRINT` does: strings bare at every depth.
24
#[must_use]
25
73635
pub fn format_value_plain(value: &Value) -> String {
26
73635
    render(value, Style::Plain)
27
73635
}
28

            
29
/// Prints `value` for a display cell: as the readable form, but a whole
30
/// scalar as its integer.
31
#[must_use]
32
112532
pub fn format_value_display(value: &Value) -> String {
33
112532
    render(value, Style::Display)
34
112532
}
35

            
36
/// A money amount: an integer when whole, else `n/d`.
37
#[must_use]
38
12693
pub fn format_amount(amount: Fraction) -> String {
39
12693
    if amount.is_integer() {
40
2292
        amount.numer().to_string()
41
    } else {
42
10401
        format!("{}/{}", amount.numer(), amount.denom())
43
    }
44
12693
}
45

            
46
24524680
fn number_text(number: Number, style: Style) -> String {
47
24524680
    match (number, style) {
48
11027
        (Number::Scalar(scalar), Style::Display) => format_amount(scalar),
49
24513653
        _ => number.to_string(),
50
    }
51
24524680
}
52

            
53
5006183
fn render(value: &Value, style: Style) -> String {
54
5006183
    let mut out = String::new();
55
5006183
    write_value(&mut out, value, style);
56
5006183
    out
57
5006183
}
58

            
59
31026798
fn write_value(out: &mut String, value: &Value, style: Style) {
60
31026798
    match value {
61
55121
        Value::Nil => out.push_str("nil"),
62
50130
        Value::T => out.push('t'),
63
24524680
        Value::Number(n) => out.push_str(&number_text(*n, style)),
64
4935222
        Value::String(s) => match style {
65
4920452
            Style::Readable | Style::Display => write_string_literal(out, s),
66
14770
            Style::Plain => out.push_str(s),
67
        },
68
670807
        Value::Symbol(s) => out.push_str(s),
69
7287
        Value::Bytes(b) => write_bytes_literal(out, b),
70
528328
        Value::Pair(pair) => write_pair_or_list(out, pair, style),
71
1
        Value::Vector(items) => write_vector(out, items, style),
72
30994
        Value::Closure(c) => match c.code_id {
73
26625
            Some(site) => out.push_str(&format!("#<closure:{site}>")),
74
4369
            None => out.push_str("#<closure>"),
75
        },
76
4784
        Value::Condition => out.push_str("#<condition>"),
77
217778
        Value::Struct { name, fields } => write_struct(out, name, fields, style),
78
        Value::Commodity {
79
            amount,
80
            commodity_id,
81
        } => {
82
            // Plist envelope keeps the wire shape uniform with native
83
            // results: emacs `(read)` recovers `(:commodity <ratio> :id "<uuid>")`.
84
1666
            out.push_str("(:commodity ");
85
1666
            out.push_str(&format_amount(*amount));
86
1666
            out.push_str(" :id ");
87
1666
            write_value(out, &Value::String(commodity_id.to_string()), style);
88
1666
            out.push(')');
89
        }
90
    }
91
31026798
}
92

            
93
4920452
fn write_string_literal(out: &mut String, s: &str) {
94
4920452
    out.push('"');
95
4920452
    for ch in s.chars() {
96
299508607
        match ch {
97
252929
            '\\' => out.push_str("\\\\"),
98
2789906
            '"' => out.push_str("\\\""),
99
113985
            '\n' => out.push_str("\\n"),
100
            '\t' => out.push_str("\\t"),
101
2496
            '\r' => out.push_str("\\r"),
102
296349291
            other => out.push(other),
103
        }
104
    }
105
4920452
    out.push('"');
106
4920452
}
107

            
108
7287
fn write_bytes_literal(out: &mut String, bytes: &[u8]) {
109
7287
    if bytes.len() <= BYTES_INLINE_THRESHOLD {
110
628
        out.push_str("#u8(");
111
628
        let mut first = true;
112
628
        for byte in bytes {
113
3575
            if first {
114
627
                first = false;
115
            } else {
116
2948
                out.push(' ');
117
            }
118
3575
            out.push_str(&byte.to_string());
119
        }
120
628
        out.push(')');
121
    } else {
122
6659
        out.push_str("#\"");
123
6659
        out.push_str(&BASE64_STANDARD.encode(bytes));
124
6659
        out.push('"');
125
    }
126
7287
}
127

            
128
528328
fn write_pair_or_list(out: &mut String, pair: &Pair, style: Style) {
129
528328
    out.push('(');
130
528328
    write_value(out, &pair.car, style);
131
528328
    let mut cdr = &pair.cdr;
132
    loop {
133
25800959
        match cdr {
134
528326
            Value::Nil => break,
135
            Value::Pair(next) => {
136
25272631
                out.push(' ');
137
25272631
                write_value(out, &next.car, style);
138
25272631
                cdr = &next.cdr;
139
            }
140
            other => {
141
2
                out.push_str(" . ");
142
2
                write_value(out, other, style);
143
2
                break;
144
            }
145
        }
146
    }
147
528328
    out.push(')');
148
528328
}
149

            
150
1
fn write_vector(out: &mut String, items: &[Value], style: Style) {
151
1
    out.push_str("#(");
152
1
    let mut first = true;
153
1
    for item in items {
154
2
        if first {
155
1
            first = false;
156
        } else {
157
1
            out.push(' ');
158
        }
159
2
        write_value(out, item, style);
160
    }
161
1
    out.push(')');
162
1
}
163

            
164
217778
fn write_struct(out: &mut String, name: &str, fields: &[(String, Value)], style: Style) {
165
217778
    out.push_str("#S(");
166
217778
    out.push_str(name);
167
217778
    for (field, value) in fields {
168
217986
        out.push_str(" :");
169
217986
        out.push_str(field);
170
217986
        out.push(' ');
171
217986
        write_value(out, value, style);
172
    }
173
217778
    out.push(')');
174
217778
}
175

            
176
#[cfg(test)]
177
mod tests {
178
    use super::super::value::{Closure, Fraction, Pair};
179
    use super::*;
180
    use crate::ast::{Expr, Number};
181
    use crate::reader::Reader;
182

            
183
    #[test]
184
1
    fn formats_keywords_in_upper_case() {
185
1
        let plist = Pair::cons(
186
1
            Value::Symbol(":ROWS".into()),
187
1
            Pair::cons(Value::Symbol(":HAS-MORE".into()), Value::Nil),
188
1
        );
189
1
        assert_eq!(format_value(&plist), "(:ROWS :HAS-MORE)");
190
1
    }
191

            
192
    #[test]
193
1
    fn keeps_plain_symbols_as_stored() {
194
1
        assert_eq!(format_value(&Value::Symbol("OK".into())), "OK");
195
1
    }
196

            
197
    #[test]
198
1
    fn formats_nil() {
199
1
        assert_eq!(format_value(&Value::Nil), "nil");
200
1
    }
201

            
202
    #[test]
203
1
    fn formats_t() {
204
1
        assert_eq!(format_value(&Value::T), "t");
205
1
    }
206

            
207
    #[test]
208
1
    fn a_list_ending_in_nil_prints_as_a_proper_list() {
209
1
        let list = Pair::cons(Value::Symbol("A".into()), Value::Nil);
210
1
        assert_eq!(format_value(&list), "(A)");
211
1
    }
212

            
213
    #[test]
214
1
    fn formats_integer_number() {
215
1
        assert_eq!(format_value(&Value::Number(Number::Index(42))), "42");
216
1
    }
217

            
218
    #[test]
219
1
    fn formats_negative_integer() {
220
1
        assert_eq!(format_value(&Value::Number(Number::Index(-7))), "-7");
221
1
    }
222

            
223
    #[test]
224
1
    fn formats_proper_fraction() {
225
1
        assert_eq!(
226
1
            format_value(&Value::Number(Number::Scalar(Fraction::new(3, 4)))),
227
1
            "3/4"
228
        );
229
1
    }
230

            
231
    #[test]
232
1
    fn a_whole_scalar_prints_its_denominator() {
233
1
        let whole = Value::Number(Number::Scalar(Fraction::from_integer(2)));
234
1
        assert_eq!(format_value(&whole), "2/1");
235
1
        assert_eq!(format_value_plain(&whole), "2/1");
236
1
    }
237

            
238
    #[test]
239
1
    fn a_display_cell_prints_a_whole_scalar_as_an_integer() {
240
1
        let whole = Value::Number(Number::Scalar(Fraction::from_integer(100)));
241
1
        let list = Pair::cons(
242
1
            whole.clone(),
243
1
            Pair::cons(Value::Number(Number::Index(3)), Value::Nil),
244
1
        );
245
1
        assert_eq!(format_value_display(&whole), "100");
246
1
        assert_eq!(format_value_display(&list), "(100 3)");
247
1
        let fraction = Value::Number(Number::Scalar(Fraction::new(1, 4)));
248
1
        assert_eq!(format_value_display(&fraction), "1/4");
249
1
        assert_eq!(format_value_display(&Value::String("a".into())), "\"a\"");
250
1
    }
251

            
252
    #[test]
253
1
    fn formats_string_with_escapes() {
254
1
        let v = Value::String("a\nb\"c\\d".to_string());
255
1
        assert_eq!(format_value(&v), "\"a\\nb\\\"c\\\\d\"");
256
1
    }
257

            
258
    #[test]
259
1
    fn formats_symbol_verbatim() {
260
1
        assert_eq!(format_value(&Value::Symbol("FOO".into())), "FOO");
261
1
    }
262

            
263
    #[test]
264
1
    fn formats_short_bytes_as_u8_literal() {
265
1
        let v = Value::Bytes(vec![0, 1, 255]);
266
1
        assert_eq!(format_value(&v), "#u8(0 1 255)");
267
1
    }
268

            
269
    #[test]
270
1
    fn formats_empty_bytes_as_u8_literal() {
271
1
        assert_eq!(format_value(&Value::Bytes(Vec::new())), "#u8()");
272
1
    }
273

            
274
    #[test]
275
1
    fn formats_bytes_at_inline_threshold() {
276
1
        let bytes: Vec<u8> = (0..BYTES_INLINE_THRESHOLD as u8).collect();
277
1
        let formatted = format_value(&Value::Bytes(bytes.clone()));
278
1
        assert!(formatted.starts_with("#u8("));
279
1
        assert!(formatted.ends_with(')'));
280
1
    }
281

            
282
    #[test]
283
1
    fn formats_long_bytes_as_base64_literal() {
284
1
        let bytes: Vec<u8> = (0..=BYTES_INLINE_THRESHOLD as u8).collect();
285
1
        let formatted = format_value(&Value::Bytes(bytes.clone()));
286
1
        assert!(formatted.starts_with("#\""));
287
1
        assert!(formatted.ends_with('"'));
288
1
        let payload = &formatted[2..formatted.len() - 1];
289
1
        let decoded = BASE64_STANDARD.decode(payload).unwrap();
290
1
        assert_eq!(decoded, bytes);
291
1
    }
292

            
293
    #[test]
294
1
    fn formats_proper_list() {
295
1
        let list = Pair::cons(
296
1
            Value::Number(Number::Index(1)),
297
1
            Pair::cons(
298
1
                Value::Number(Number::Index(2)),
299
1
                Pair::cons(Value::Number(Number::Index(3)), Value::Nil),
300
1
            ),
301
1
        );
302
1
        assert_eq!(format_value(&list), "(1 2 3)");
303
1
    }
304

            
305
    #[test]
306
1
    fn formats_dotted_pair() {
307
1
        let pair = Pair::cons(Value::Symbol("A".into()), Value::Symbol("B".into()));
308
1
        assert_eq!(format_value(&pair), "(A . B)");
309
1
    }
310

            
311
    #[test]
312
1
    fn formats_improper_list() {
313
1
        let list = Pair::cons(
314
1
            Value::Number(Number::Index(1)),
315
1
            Pair::cons(
316
1
                Value::Number(Number::Index(2)),
317
1
                Value::Number(Number::Index(3)),
318
1
            ),
319
1
        );
320
1
        assert_eq!(format_value(&list), "(1 2 . 3)");
321
1
    }
322

            
323
    #[test]
324
1
    fn formats_vector() {
325
1
        let v = Value::Vector(vec![Value::Number(Number::Index(1)), Value::T]);
326
1
        assert_eq!(format_value(&v), "#(1 t)");
327
1
    }
328

            
329
    #[test]
330
1
    fn formats_closure() {
331
1
        let c = Value::Closure(Closure::new(7, vec![]));
332
1
        assert_eq!(format_value(&c), "#<closure:7>");
333
1
    }
334

            
335
    #[test]
336
1
    fn formats_siteless_closure() {
337
1
        let c = Value::Closure(Closure::siteless());
338
1
        assert_eq!(format_value(&c), "#<closure>");
339
1
    }
340

            
341
    #[test]
342
1
    fn formats_struct() {
343
1
        let s = Value::Struct {
344
1
            name: "ACCOUNT".into(),
345
1
            fields: vec![("ID".into(), Value::Number(Number::Index(42)))],
346
1
        };
347
1
        assert_eq!(format_value(&s), "#S(ACCOUNT :ID 42)");
348
1
    }
349

            
350
    #[test]
351
1
    fn round_trip_short_bytes_through_reader() {
352
1
        let v = Value::Bytes(vec![0xCA, 0xFE, 0xBA, 0xBE]);
353
1
        let formatted = format_value(&v);
354
1
        let parsed = Reader::parse(&formatted).unwrap();
355
1
        assert_eq!(
356
1
            parsed.exprs,
357
1
            vec![Expr::Bytes(vec![0xCA, 0xFE, 0xBA, 0xBE])]
358
        );
359
1
    }
360

            
361
    #[test]
362
1
    fn round_trip_long_bytes_through_reader() {
363
1
        let bytes: Vec<u8> = (0..=255).chain(0..=255).collect();
364
1
        let formatted = format_value(&Value::Bytes(bytes.clone()));
365
1
        let parsed = Reader::parse(&formatted).unwrap();
366
1
        assert_eq!(parsed.exprs, vec![Expr::Bytes(bytes)]);
367
1
    }
368

            
369
    #[test]
370
1
    fn round_trip_full_byte_range_through_reader() {
371
1
        let bytes: Vec<u8> = (0..=255).collect();
372
1
        let formatted = format_value(&Value::Bytes(bytes.clone()));
373
1
        let parsed = Reader::parse(&formatted).unwrap();
374
1
        assert_eq!(parsed.exprs, vec![Expr::Bytes(bytes)]);
375
1
    }
376

            
377
    #[test]
378
1
    fn round_trip_rational_through_reader() {
379
1
        for (num, den) in [(1i64, 2i64), (-3, 4), (1, 3), (7, 11)] {
380
4
            let v = Value::Number(Number::Scalar(Fraction::new(num, den)));
381
4
            let formatted = format_value(&v);
382
4
            let parsed = Reader::parse(&formatted).unwrap();
383
4
            assert_eq!(
384
4
                parsed.exprs,
385
4
                vec![Expr::Number(Number::Scalar(Fraction::new(num, den)))]
386
            );
387
        }
388
1
    }
389

            
390
    #[test]
391
1
    fn plain_style_prints_the_commodity_id_bare() {
392
1
        let money = Value::Commodity {
393
1
            amount: Fraction::from_integer(3),
394
1
            commodity_id: uuid::Uuid::nil(),
395
1
        };
396
1
        let id = "00000000-0000-0000-0000-000000000000";
397
1
        assert_eq!(
398
1
            format_value_plain(&money),
399
1
            format!("(:commodity 3 :id {id})")
400
        );
401
1
        assert_eq!(format_value(&money), format!("(:commodity 3 :id \"{id}\")"));
402
1
    }
403

            
404
    #[test]
405
1
    fn plain_style_prints_strings_bare_at_every_depth() {
406
1
        let list = Pair::cons(
407
1
            Value::String("a\"b".into()),
408
1
            Pair::cons(Value::Number(Number::Index(1)), Value::Nil),
409
1
        );
410
1
        assert_eq!(format_value_plain(&list), "(a\"b 1)");
411
1
        assert_eq!(format_value(&list), "(\"a\\\"b\" 1)");
412
1
    }
413
}