seq-core 5.5.0

Core runtime library for stack-based languages (Value, Stack, Channels)
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! SON (Seq Object Notation) Serialization
//!
//! Serializes Seq Values to SON format - a prefix/postfix notation compatible
//! with Seq syntax. SON values can be evaluated in Seq to recreate the original data.
//!
//! # Format Examples
//!
//! - Int: `42`
//! - Float: `3.14`
//! - Bool: `true` / `false`
//! - String: `"hello"` (with proper escaping)
//! - Symbol: `:my-symbol`
//! - List: `list-of 1 lv 2 lv 3 lv`
//! - Map: `map-of "key" "value" kv`
//! - Variant: `:Tag field1 field2 wrap-2`

use crate::seqstring::SeqString;
use crate::stack::{Stack, pop, push};
use crate::value::{MapKey, Value, VariantData};
use std::collections::HashMap;

/// Configuration for SON output formatting
#[derive(Clone)]
pub struct SonConfig {
    /// Use pretty printing with indentation
    pub pretty: bool,
    /// Number of spaces per indentation level
    pub indent: usize,
}

impl Default for SonConfig {
    fn default() -> Self {
        Self {
            pretty: false,
            indent: 2,
        }
    }
}

impl SonConfig {
    /// Create a compact (single-line) config
    pub fn compact() -> Self {
        Self::default()
    }

    /// Create a pretty-printed config
    pub fn pretty() -> Self {
        Self {
            pretty: true,
            indent: 2,
        }
    }
}

/// Format a Value to SON string
pub fn value_to_son(value: &Value, config: &SonConfig) -> String {
    let mut buf = String::new();
    format_value(value, config, 0, &mut buf);
    buf
}

/// Internal formatting function with indentation tracking
fn format_value(value: &Value, config: &SonConfig, depth: usize, buf: &mut String) {
    match value {
        Value::Int(n) => {
            buf.push_str(&n.to_string());
        }
        Value::Float(f) => {
            let s = f.to_string();
            buf.push_str(&s);
            // Ensure floats always have decimal point for disambiguation
            if !s.contains('.') && f.is_finite() {
                buf.push_str(".0");
            }
        }
        Value::Bool(b) => {
            buf.push_str(if *b { "true" } else { "false" });
        }
        Value::String(s) => {
            format_string(s.as_str(), buf);
        }
        Value::Symbol(s) => {
            buf.push(':');
            buf.push_str(s.as_str());
        }
        Value::Variant(v) => {
            format_variant(v, config, depth, buf);
        }
        Value::Map(m) => {
            format_map(m, config, depth, buf);
        }
        Value::Quotation { .. } => {
            buf.push_str("<quotation>");
        }
        Value::Closure { .. } => {
            buf.push_str("<closure>");
        }
        Value::Channel(_) => {
            buf.push_str("<channel>");
        }
        Value::WeaveCtx { .. } => {
            buf.push_str("<weave-ctx>");
        }
    }
}

/// Format a string with proper escaping
fn format_string(s: &str, buf: &mut String) {
    buf.push('"');
    for c in s.chars() {
        match c {
            '"' => buf.push_str("\\\""),
            '\\' => buf.push_str("\\\\"),
            '\n' => buf.push_str("\\n"),
            '\r' => buf.push_str("\\r"),
            '\t' => buf.push_str("\\t"),
            '\x08' => buf.push_str("\\b"),
            '\x0C' => buf.push_str("\\f"),
            c if c.is_control() => {
                buf.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => buf.push(c),
        }
    }
    buf.push('"');
}

/// Format a variant (includes List as special case)
fn format_variant(v: &VariantData, config: &SonConfig, depth: usize, buf: &mut String) {
    let tag = v.tag.as_str();

    // Special case: List variant uses list-of/lv syntax
    if tag == "List" {
        format_list(&v.fields, config, depth, buf);
    } else {
        // General variant: :Tag field1 field2 wrap-N
        buf.push(':');
        buf.push_str(tag);

        let field_count = v.fields.len();

        if config.pretty && !v.fields.is_empty() {
            for field in v.fields.iter() {
                buf.push('\n');
                push_indent(buf, depth + 1, config.indent);
                format_value(field, config, depth + 1, buf);
            }
            buf.push('\n');
            push_indent(buf, depth, config.indent);
        } else {
            for field in v.fields.iter() {
                buf.push(' ');
                format_value(field, config, depth, buf);
            }
        }

        buf.push_str(&format!(" wrap-{}", field_count));
    }
}

/// Format a list using list-of/lv syntax
fn format_list(fields: &[Value], config: &SonConfig, depth: usize, buf: &mut String) {
    buf.push_str("list-of");

    if fields.is_empty() {
        return;
    }

    if config.pretty {
        for field in fields.iter() {
            buf.push('\n');
            push_indent(buf, depth + 1, config.indent);
            format_value(field, config, depth + 1, buf);
            buf.push_str(" lv");
        }
    } else {
        for field in fields.iter() {
            buf.push(' ');
            format_value(field, config, depth, buf);
            buf.push_str(" lv");
        }
    }
}

/// Format a map using map-of/kv syntax
fn format_map(map: &HashMap<MapKey, Value>, config: &SonConfig, depth: usize, buf: &mut String) {
    buf.push_str("map-of");

    if map.is_empty() {
        return;
    }

    // Sort keys for deterministic output (important for testing/debugging)
    let mut entries: Vec<_> = map.iter().collect();
    entries.sort_by(|(k1, _), (k2, _)| {
        let s1 = map_key_sort_string(k1);
        let s2 = map_key_sort_string(k2);
        s1.cmp(&s2)
    });

    if config.pretty {
        for (key, value) in entries {
            buf.push('\n');
            push_indent(buf, depth + 1, config.indent);
            format_map_key(key, buf);
            buf.push(' ');
            format_value(value, config, depth + 1, buf);
            buf.push_str(" kv");
        }
    } else {
        for (key, value) in entries {
            buf.push(' ');
            format_map_key(key, buf);
            buf.push(' ');
            format_value(value, config, depth, buf);
            buf.push_str(" kv");
        }
    }
}

/// Get a sort key string for a MapKey
fn map_key_sort_string(key: &MapKey) -> String {
    match key {
        MapKey::Int(n) => format!("0_{:020}", n), // Prefix with 0 for ints
        MapKey::Bool(b) => format!("1_{}", b),    // Prefix with 1 for bools
        MapKey::String(s) => format!("2_{}", s.as_str()), // Prefix with 2 for strings
    }
}

/// Format a map key
fn format_map_key(key: &MapKey, buf: &mut String) {
    match key {
        MapKey::Int(n) => buf.push_str(&n.to_string()),
        MapKey::Bool(b) => buf.push_str(if *b { "true" } else { "false" }),
        MapKey::String(s) => format_string(s.as_str(), buf),
    }
}

/// Push indentation spaces
fn push_indent(buf: &mut String, depth: usize, indent_size: usize) {
    for _ in 0..(depth * indent_size) {
        buf.push(' ');
    }
}

// ============================================================================
// Runtime Builtins
// ============================================================================

/// son.dump: Serialize top of stack to SON string (compact)
/// Stack effect: ( Value -- String )
///
/// # Safety
/// - The stack must be a valid stack pointer
/// - The stack must contain at least one value
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_son_dump(stack: Stack) -> Stack {
    unsafe { son_dump_impl(stack, false) }
}

/// son.dump-pretty: Serialize top of stack to SON string (pretty-printed)
/// Stack effect: ( Value -- String )
///
/// # Safety
/// - The stack must be a valid stack pointer
/// - The stack must contain at least one value
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_son_dump_pretty(stack: Stack) -> Stack {
    unsafe { son_dump_impl(stack, true) }
}

/// Implementation for both dump variants
unsafe fn son_dump_impl(stack: Stack, pretty: bool) -> Stack {
    let (rest, value) = unsafe { pop(stack) };

    let config = if pretty {
        SonConfig::pretty()
    } else {
        SonConfig::compact()
    };

    let result = value_to_son(&value, &config);
    let result_str = SeqString::from(result);

    unsafe { push(rest, Value::String(result_str)) }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::seqstring::global_string;
    use std::sync::Arc;

    #[test]
    fn test_int() {
        let v = Value::Int(42);
        assert_eq!(value_to_son(&v, &SonConfig::default()), "42");
    }

    #[test]
    fn test_negative_int() {
        let v = Value::Int(-123);
        assert_eq!(value_to_son(&v, &SonConfig::default()), "-123");
    }

    #[test]
    fn test_float() {
        let v = Value::Float(2.5);
        assert_eq!(value_to_son(&v, &SonConfig::default()), "2.5");
    }

    #[test]
    fn test_float_whole_number() {
        let v = Value::Float(42.0);
        let s = value_to_son(&v, &SonConfig::default());
        assert!(s.contains('.'), "Float should contain decimal point: {}", s);
    }

    #[test]
    fn test_bool_true() {
        let v = Value::Bool(true);
        assert_eq!(value_to_son(&v, &SonConfig::default()), "true");
    }

    #[test]
    fn test_bool_false() {
        let v = Value::Bool(false);
        assert_eq!(value_to_son(&v, &SonConfig::default()), "false");
    }

    #[test]
    fn test_string_simple() {
        let v = Value::String(global_string("hello".to_string()));
        assert_eq!(value_to_son(&v, &SonConfig::default()), r#""hello""#);
    }

    #[test]
    fn test_string_escaping() {
        let v = Value::String(global_string("hello\nworld".to_string()));
        assert_eq!(value_to_son(&v, &SonConfig::default()), r#""hello\nworld""#);
    }

    #[test]
    fn test_string_quotes() {
        let v = Value::String(global_string(r#"say "hi""#.to_string()));
        assert_eq!(value_to_son(&v, &SonConfig::default()), r#""say \"hi\"""#);
    }

    #[test]
    fn test_symbol() {
        let v = Value::Symbol(global_string("my-symbol".to_string()));
        assert_eq!(value_to_son(&v, &SonConfig::default()), ":my-symbol");
    }

    #[test]
    fn test_empty_list() {
        let list = Value::Variant(Arc::new(VariantData::new(
            global_string("List".to_string()),
            vec![],
        )));
        assert_eq!(value_to_son(&list, &SonConfig::default()), "list-of");
    }

    #[test]
    fn test_list() {
        let list = Value::Variant(Arc::new(VariantData::new(
            global_string("List".to_string()),
            vec![Value::Int(1), Value::Int(2), Value::Int(3)],
        )));
        assert_eq!(
            value_to_son(&list, &SonConfig::default()),
            "list-of 1 lv 2 lv 3 lv"
        );
    }

    #[test]
    fn test_list_pretty() {
        let list = Value::Variant(Arc::new(VariantData::new(
            global_string("List".to_string()),
            vec![Value::Int(1), Value::Int(2)],
        )));
        let expected = "list-of\n  1 lv\n  2 lv";
        assert_eq!(value_to_son(&list, &SonConfig::pretty()), expected);
    }

    #[test]
    fn test_empty_map() {
        let m: HashMap<MapKey, Value> = HashMap::new();
        let v = Value::Map(Box::new(m));
        assert_eq!(value_to_son(&v, &SonConfig::default()), "map-of");
    }

    #[test]
    fn test_map() {
        let mut m = HashMap::new();
        m.insert(
            MapKey::String(global_string("key".to_string())),
            Value::Int(42),
        );
        let v = Value::Map(Box::new(m));
        assert_eq!(
            value_to_son(&v, &SonConfig::default()),
            r#"map-of "key" 42 kv"#
        );
    }

    #[test]
    fn test_variant_no_fields() {
        let v = Value::Variant(Arc::new(VariantData::new(
            global_string("None".to_string()),
            vec![],
        )));
        assert_eq!(value_to_son(&v, &SonConfig::default()), ":None wrap-0");
    }

    #[test]
    fn test_variant_with_fields() {
        let v = Value::Variant(Arc::new(VariantData::new(
            global_string("Point".to_string()),
            vec![Value::Int(10), Value::Int(20)],
        )));
        assert_eq!(
            value_to_son(&v, &SonConfig::default()),
            ":Point 10 20 wrap-2"
        );
    }

    #[test]
    fn test_variant_pretty() {
        let v = Value::Variant(Arc::new(VariantData::new(
            global_string("Point".to_string()),
            vec![Value::Int(10), Value::Int(20)],
        )));
        let expected = ":Point\n  10\n  20\n wrap-2";
        assert_eq!(value_to_son(&v, &SonConfig::pretty()), expected);
    }

    #[test]
    fn test_nested_list_in_map() {
        let list = Value::Variant(Arc::new(VariantData::new(
            global_string("List".to_string()),
            vec![Value::Int(1), Value::Int(2)],
        )));
        let mut m = HashMap::new();
        m.insert(MapKey::String(global_string("items".to_string())), list);
        let v = Value::Map(Box::new(m));
        assert_eq!(
            value_to_son(&v, &SonConfig::default()),
            r#"map-of "items" list-of 1 lv 2 lv kv"#
        );
    }

    #[test]
    fn test_quotation() {
        let v = Value::Quotation {
            wrapper: 0,
            impl_: 0,
        };
        assert_eq!(value_to_son(&v, &SonConfig::default()), "<quotation>");
    }

    #[test]
    fn test_closure() {
        let v = Value::Closure {
            fn_ptr: 0,
            env: Arc::new([]),
        };
        assert_eq!(value_to_son(&v, &SonConfig::default()), "<closure>");
    }
}