pelagos 0.1.1

Fast Linux container runtime — OCI-compatible, namespaces, cgroups v2, seccomp, networking, image management
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Zero-dependency recursive descent S-expression parser.
//!
//! Grammar: `sexpr = atom | '(' sexpr* ')'`
//! - Atoms: bare words (`foo`, `123`) or `"quoted strings"` with `\"` / `\\` escapes
//! - `;` starts a line comment (to end of line)
//! - Whitespace is insignificant outside quotes

use std::fmt;

/// A parsed S-expression: either an atom, a quoted string, or a list of sub-expressions.
///
/// The distinction between `Atom` and `Str` matters for the Lisp evaluator:
/// - `Atom` is a bare word; the evaluator treats it as a symbol to look up.
/// - `Str` was written with double quotes; the evaluator treats it as a string literal.
///
/// The compose DSL does not care about this distinction — both `as_atom()` and `as_list()`
/// behave identically to the old `Atom`-only world.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SExpr {
    /// An unquoted bare word: a symbol in Lisp context.
    Atom(String),
    /// A double-quoted string literal.
    Str(String),
    List(Vec<SExpr>),
    /// An improper list: `(a b . c)` — head items plus a non-nil tail.
    DottedList(Vec<SExpr>, Box<SExpr>),
}

impl SExpr {
    /// Return the string value, or `None` if this is a list.
    ///
    /// Returns `Some` for both `Atom` and `Str` variants — callers that don't
    /// distinguish between symbols and strings (e.g. the compose DSL) can use
    /// this method unchanged.
    pub fn as_atom(&self) -> Option<&str> {
        match self {
            SExpr::Atom(s) | SExpr::Str(s) => Some(s.as_str()),
            SExpr::List(_) | SExpr::DottedList(_, _) => None,
        }
    }

    /// Return the list contents, or `None` if this is an atom, string, or dotted list.
    pub fn as_list(&self) -> Option<&[SExpr]> {
        match self {
            SExpr::Atom(_) | SExpr::Str(_) | SExpr::DottedList(_, _) => None,
            SExpr::List(v) => Some(v),
        }
    }

    /// Returns `true` if this is a bare-word atom (not a quoted string).
    pub fn is_symbol(&self) -> bool {
        matches!(self, SExpr::Atom(_))
    }
}

impl fmt::Display for SExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SExpr::Atom(s) => {
                if s.contains(|c: char| c.is_whitespace() || c == '(' || c == ')' || c == '"') {
                    write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
                } else {
                    write!(f, "{}", s)
                }
            }
            SExpr::Str(s) => {
                write!(f, "\"")?;
                for c in s.chars() {
                    match c {
                        '"' => write!(f, "\\\"")?,
                        '\\' => write!(f, "\\\\")?,
                        '\n' => write!(f, "\\n")?,
                        '\t' => write!(f, "\\t")?,
                        c => write!(f, "{}", c)?,
                    }
                }
                write!(f, "\"")
            }
            SExpr::List(items) => {
                write!(f, "(")?;
                for (i, item) in items.iter().enumerate() {
                    if i > 0 {
                        write!(f, " ")?;
                    }
                    write!(f, "{}", item)?;
                }
                write!(f, ")")
            }
            SExpr::DottedList(items, tail) => {
                write!(f, "(")?;
                for (i, item) in items.iter().enumerate() {
                    if i > 0 {
                        write!(f, " ")?;
                    }
                    write!(f, "{}", item)?;
                }
                write!(f, " . {}", tail)?;
                write!(f, ")")
            }
        }
    }
}

/// Parse error with position information.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    pub message: String,
    /// Byte offset in the original input.
    pub position: usize,
    /// 1-based line number.
    pub line: usize,
    /// 1-based column number (character, not byte).
    pub col: usize,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "parse error at {}:{}: {}",
            self.line, self.col, self.message
        )
    }
}

/// Convert a byte offset to a (line, col) pair (both 1-based).
fn line_col(input: &str, pos: usize) -> (usize, usize) {
    let prefix = &input[..pos.min(input.len())];
    let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1;
    let col = prefix
        .rfind('\n')
        .map_or(prefix.len(), |n| prefix.len() - n - 1)
        + 1;
    (line, col)
}

/// Build a `ParseError` at `pos` with the given message.
fn make_err(input: &str, pos: usize, message: impl Into<String>) -> ParseError {
    let (line, col) = line_col(input, pos);
    ParseError {
        message: message.into(),
        position: pos,
        line,
        col,
    }
}

impl std::error::Error for ParseError {}

/// Parse an S-expression from input text.
///
/// The input should contain exactly one top-level expression (typically a list).
pub fn parse(input: &str) -> Result<SExpr, ParseError> {
    let mut pos = 0;
    skip_ws_and_comments(input, &mut pos);
    if pos >= input.len() {
        return Err(make_err(input, 0, "empty input"));
    }
    let expr = parse_sexpr(input, &mut pos)?;
    skip_ws_and_comments(input, &mut pos);
    if pos < input.len() {
        return Err(make_err(input, pos, "unexpected trailing input"));
    }
    Ok(expr)
}

/// Parse all top-level S-expressions from `input`.
///
/// Unlike [`parse`], this accepts zero or more expressions and returns them all.
/// Whitespace and comments between expressions are ignored.
/// Used by the Lisp interpreter to read a `.reml` program.
pub fn parse_all(input: &str) -> Result<Vec<SExpr>, ParseError> {
    let mut pos = 0;
    let mut exprs = Vec::new();
    loop {
        skip_ws_and_comments(input, &mut pos);
        if pos >= input.len() {
            break;
        }
        exprs.push(parse_sexpr(input, &mut pos)?);
    }
    Ok(exprs)
}

fn parse_sexpr(input: &str, pos: &mut usize) -> Result<SExpr, ParseError> {
    skip_ws_and_comments(input, pos);
    if *pos >= input.len() {
        return Err(make_err(input, *pos, "unexpected end of input"));
    }

    let ch = input.as_bytes()[*pos];
    match ch {
        b'(' => parse_list(input, pos),
        b')' => Err(make_err(input, *pos, "unexpected ')'")),
        // Reader macros: 'x → (quote x), `x → (quasiquote x),
        //                ,@x → (unquote-splicing x), ,x → (unquote x)
        b'\'' => {
            *pos += 1;
            let inner = parse_sexpr(input, pos)?;
            Ok(SExpr::List(vec![SExpr::Atom("quote".into()), inner]))
        }
        b'`' => {
            *pos += 1;
            let inner = parse_sexpr(input, pos)?;
            Ok(SExpr::List(vec![SExpr::Atom("quasiquote".into()), inner]))
        }
        b',' => {
            *pos += 1;
            if *pos < input.len() && input.as_bytes()[*pos] == b'@' {
                *pos += 1;
                let inner = parse_sexpr(input, pos)?;
                Ok(SExpr::List(vec![
                    SExpr::Atom("unquote-splicing".into()),
                    inner,
                ]))
            } else {
                let inner = parse_sexpr(input, pos)?;
                Ok(SExpr::List(vec![SExpr::Atom("unquote".into()), inner]))
            }
        }
        _ => parse_atom(input, pos),
    }
}

fn parse_list(input: &str, pos: &mut usize) -> Result<SExpr, ParseError> {
    let open_pos = *pos;
    *pos += 1; // skip '('
    let mut items = Vec::new();
    loop {
        skip_ws_and_comments(input, pos);
        if *pos >= input.len() {
            return Err(make_err(input, open_pos, "unmatched '('"));
        }
        if input.as_bytes()[*pos] == b')' {
            *pos += 1; // skip ')'
            return Ok(SExpr::List(items));
        }
        // Dotted pair separator: '.' followed immediately by a delimiter.
        // This distinguishes `(a . b)` from atoms like `.5` or `...`.
        if is_dot_separator(input, *pos) {
            *pos += 1; // skip '.'
            skip_ws_and_comments(input, pos);
            if *pos >= input.len() {
                return Err(make_err(
                    input,
                    open_pos,
                    "dotted pair: expected tail after '.'",
                ));
            }
            let tail = parse_sexpr(input, pos)?;
            skip_ws_and_comments(input, pos);
            if *pos >= input.len() || input.as_bytes()[*pos] != b')' {
                return Err(make_err(
                    input,
                    *pos,
                    "dotted pair: expected ')' after tail expression",
                ));
            }
            *pos += 1; // skip ')'
            return Ok(SExpr::DottedList(items, Box::new(tail)));
        }
        items.push(parse_sexpr(input, pos)?);
    }
}

/// Return `true` if position `pos` is a dotted-pair `.` separator, i.e. a lone `.`
/// followed by whitespace, `(`, `)`, `;`, or end-of-input.
fn is_dot_separator(input: &str, pos: usize) -> bool {
    let bytes = input.as_bytes();
    if bytes[pos] != b'.' {
        return false;
    }
    let next = pos + 1;
    if next >= bytes.len() {
        return true;
    }
    let ch = bytes[next];
    ch.is_ascii_whitespace() || ch == b'(' || ch == b')' || ch == b';' || ch == b'"'
}

fn parse_atom(input: &str, pos: &mut usize) -> Result<SExpr, ParseError> {
    if input.as_bytes()[*pos] == b'"' {
        parse_quoted_string(input, pos)
    } else {
        parse_bare_word(input, pos)
    }
}

fn parse_quoted_string(input: &str, pos: &mut usize) -> Result<SExpr, ParseError> {
    let start = *pos;
    *pos += 1; // skip opening '"'
    let mut s = String::new();
    let bytes = input.as_bytes();
    while *pos < bytes.len() {
        if bytes[*pos] == b'\\' {
            *pos += 1;
            if *pos >= bytes.len() {
                return Err(make_err(input, start, "unterminated escape in string"));
            }
            match bytes[*pos] {
                b'"' => s.push('"'),
                b'\\' => s.push('\\'),
                b'n' => s.push('\n'),
                b't' => s.push('\t'),
                other => {
                    s.push('\\');
                    s.push(other as char); // escape sequences are ASCII
                }
            }
            *pos += 1;
        } else if bytes[*pos] == b'"' {
            *pos += 1; // skip closing '"'
            return Ok(SExpr::Str(s));
        } else {
            // Decode one full Unicode scalar value, advancing by its byte length.
            let ch = input[*pos..].chars().next().unwrap();
            s.push(ch);
            *pos += ch.len_utf8();
        }
    }
    Err(make_err(input, start, "unterminated string"))
}

fn parse_bare_word(input: &str, pos: &mut usize) -> Result<SExpr, ParseError> {
    let start = *pos;
    let bytes = input.as_bytes();
    while *pos < bytes.len() {
        let ch = bytes[*pos];
        if ch.is_ascii_whitespace()
            || ch == b'('
            || ch == b')'
            || ch == b';'
            || ch == b'"'
            || ch == b'\''
            || ch == b'`'
            || ch == b','
        {
            break;
        }
        *pos += 1;
    }
    if *pos == start {
        return Err(make_err(input, start, "expected atom"));
    }
    Ok(SExpr::Atom(input[start..*pos].to_string()))
}

fn skip_ws_and_comments(input: &str, pos: &mut usize) {
    let bytes = input.as_bytes();
    while *pos < bytes.len() {
        if bytes[*pos].is_ascii_whitespace() {
            *pos += 1;
        } else if bytes[*pos] == b';' {
            // Skip to end of line.
            while *pos < bytes.len() && bytes[*pos] != b'\n' {
                *pos += 1;
            }
        } else {
            break;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bare_atom() {
        assert_eq!(parse("hello").unwrap(), SExpr::Atom("hello".into()));
    }

    #[test]
    fn test_quoted_string() {
        assert_eq!(
            parse(r#""hello world""#).unwrap(),
            SExpr::Str("hello world".into())
        );
    }

    #[test]
    fn test_quoted_string_escapes() {
        assert_eq!(
            parse(r#""say \"hi\" \\""#).unwrap(),
            SExpr::Str(r#"say "hi" \"#.into())
        );
    }

    #[test]
    fn test_simple_list() {
        let expr = parse("(a b c)").unwrap();
        let items = expr.as_list().unwrap();
        assert_eq!(items.len(), 3);
        assert_eq!(items[0].as_atom().unwrap(), "a");
        assert_eq!(items[1].as_atom().unwrap(), "b");
        assert_eq!(items[2].as_atom().unwrap(), "c");
    }

    #[test]
    fn test_nested_lists() {
        let expr = parse("(a (b c) (d (e)))").unwrap();
        let items = expr.as_list().unwrap();
        assert_eq!(items.len(), 3);
        assert_eq!(items[0].as_atom().unwrap(), "a");
        let inner1 = items[1].as_list().unwrap();
        assert_eq!(inner1.len(), 2);
        let inner2 = items[2].as_list().unwrap();
        assert_eq!(inner2.len(), 2);
    }

    #[test]
    fn test_comments() {
        let input = "; this is a comment\n(a ; inline comment\n b)";
        let expr = parse(input).unwrap();
        let items = expr.as_list().unwrap();
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].as_atom().unwrap(), "a");
        assert_eq!(items[1].as_atom().unwrap(), "b");
    }

    #[test]
    fn test_empty_list() {
        let expr = parse("()").unwrap();
        assert_eq!(expr.as_list().unwrap().len(), 0);
    }

    #[test]
    fn test_unmatched_open_paren() {
        let err = parse("(a b").unwrap_err();
        assert!(err.message.contains("unmatched '('"), "{}", err);
    }

    #[test]
    fn test_unmatched_close_paren() {
        let err = parse("a)").unwrap_err();
        assert!(
            err.message.contains("trailing input") || err.message.contains("unexpected"),
            "{}",
            err
        );
    }

    #[test]
    fn test_unterminated_string() {
        let err = parse(r#""hello"#).unwrap_err();
        assert!(err.message.contains("unterminated"), "{}", err);
    }

    #[test]
    fn test_empty_input() {
        let err = parse("").unwrap_err();
        assert!(err.message.contains("empty"), "{}", err);
    }

    #[test]
    fn test_comment_only_input() {
        let err = parse("; just a comment\n").unwrap_err();
        assert!(err.message.contains("empty"), "{}", err);
    }

    #[test]
    fn test_keyword_atoms() {
        let expr = parse("(:ready-port 5432)").unwrap();
        let items = expr.as_list().unwrap();
        assert_eq!(items[0].as_atom().unwrap(), ":ready-port");
        assert_eq!(items[1].as_atom().unwrap(), "5432");
    }

    #[test]
    fn test_display_round_trip() {
        let input = "(compose (service db (image \"postgres:16\")))";
        let expr = parse(input).unwrap();
        let printed = expr.to_string();
        let reparsed = parse(&printed).unwrap();
        assert_eq!(expr, reparsed);
    }

    #[test]
    fn test_full_compose_example() {
        let input = r#"
; A typical web application stack
(compose
  (network backend (subnet "10.88.1.0/24"))
  (volume pgdata)

  (service db
    (image "postgres:16")
    (network backend)
    (volume pgdata "/var/lib/postgresql/data")
    (env POSTGRES_PASSWORD "secret")
    (port 5432 5432)
    (memory "512m"))

  (service api
    (image "my-api:latest")
    (network backend)
    (depends-on (db :ready-port 5432))
    (port 8080 8080))

  (service web
    (image "my-web:latest")
    (depends-on (api :ready-port 8080))
    (port 80 3000)
    (command "/bin/sh" "-c" "nginx -g 'daemon off;'")))
"#;
        let expr = parse(input).unwrap();
        let items = expr.as_list().unwrap();
        assert_eq!(items[0].as_atom().unwrap(), "compose");
        // network, volume, 3 services = 5 items + "compose" = 6
        assert_eq!(items.len(), 6);
    }

    #[test]
    fn test_as_atom_on_list() {
        let expr = parse("(a)").unwrap();
        assert!(expr.as_atom().is_none());
    }

    #[test]
    fn test_as_list_on_atom() {
        let expr = parse("hello").unwrap();
        assert!(expr.as_list().is_none());
    }

    #[test]
    fn test_quoted_string_utf8() {
        // Multibyte UTF-8 characters must survive a round-trip through quoted strings.
        let input = r#""héllo wörld 🎉""#;
        let atom = parse(input).unwrap();
        assert_eq!(atom, SExpr::Str("héllo wörld 🎉".into()));
        assert_eq!(atom.as_atom().unwrap(), "héllo wörld 🎉");
    }

    #[test]
    fn test_reader_macro_quote() {
        let expr = parse("'foo").unwrap();
        assert_eq!(
            expr,
            SExpr::List(vec![SExpr::Atom("quote".into()), SExpr::Atom("foo".into())])
        );
    }

    #[test]
    fn test_reader_macro_quasiquote() {
        let expr = parse("`(a ,b ,@c)").unwrap();
        let items = expr.as_list().unwrap();
        assert_eq!(items[0].as_atom().unwrap(), "quasiquote");
        let inner = items[1].as_list().unwrap();
        assert_eq!(inner[0].as_atom().unwrap(), "a");
        // ,b → (unquote b)
        let unquote = inner[1].as_list().unwrap();
        assert_eq!(unquote[0].as_atom().unwrap(), "unquote");
        // ,@c → (unquote-splicing c)
        let splice = inner[2].as_list().unwrap();
        assert_eq!(splice[0].as_atom().unwrap(), "unquote-splicing");
    }

    #[test]
    fn test_parse_all_empty() {
        let exprs = parse_all("").unwrap();
        assert!(exprs.is_empty());
    }

    #[test]
    fn test_parse_all_multiple() {
        let exprs = parse_all("(define x 1) (define y 2) x").unwrap();
        assert_eq!(exprs.len(), 3);
        assert_eq!(exprs[0].as_list().unwrap()[0].as_atom().unwrap(), "define");
        assert_eq!(exprs[2].as_atom().unwrap(), "x");
    }

    #[test]
    fn test_dotted_pair() {
        let expr = parse(r#"("REDIS_HOST" . "redis")"#).unwrap();
        match expr {
            SExpr::DottedList(items, tail) => {
                assert_eq!(items.len(), 1);
                assert_eq!(items[0].as_atom().unwrap(), "REDIS_HOST");
                assert_eq!(tail.as_atom().unwrap(), "redis");
            }
            _ => panic!("expected DottedList"),
        }
    }

    #[test]
    fn test_dotted_pair_multi_head() {
        let expr = parse("(a b . c)").unwrap();
        match expr {
            SExpr::DottedList(items, tail) => {
                assert_eq!(items.len(), 2);
                assert_eq!(items[0].as_atom().unwrap(), "a");
                assert_eq!(items[1].as_atom().unwrap(), "b");
                assert_eq!(tail.as_atom().unwrap(), "c");
            }
            _ => panic!("expected DottedList"),
        }
    }

    #[test]
    fn test_dotted_pair_display_round_trip() {
        let input = r#"("KEY" . "val")"#;
        let expr = parse(input).unwrap();
        let printed = expr.to_string();
        let reparsed = parse(&printed).unwrap();
        assert_eq!(expr, reparsed);
    }

    #[test]
    fn test_dotted_number_is_not_separator() {
        // ".5" should parse as the atom ".5", not trigger dotted pair
        let expr = parse("(.5)").unwrap();
        assert!(matches!(expr, SExpr::List(_)));
        let items = expr.as_list().unwrap();
        assert_eq!(items[0].as_atom().unwrap(), ".5");
    }

    #[test]
    fn test_bare_word_stops_at_reader_macros() {
        // bare words should not swallow ', `, , characters
        let expr = parse("(a 'b)").unwrap();
        let items = expr.as_list().unwrap();
        assert_eq!(items[0].as_atom().unwrap(), "a");
        let quoted = items[1].as_list().unwrap();
        assert_eq!(quoted[0].as_atom().unwrap(), "quote");
        assert_eq!(quoted[1].as_atom().unwrap(), "b");
    }

    #[test]
    fn test_error_line_col() {
        // Error on line 2, column 3 (1-based).
        let input = "(a\n  )x";
        let err = parse(input).unwrap_err();
        // The trailing 'x' is unexpected; confirm the Display uses line:col format.
        let msg = err.to_string();
        assert!(msg.contains(':'), "expected line:col in '{}'", msg);
        assert_eq!(err.line, 2);
        assert_eq!(err.col, 4); // '  )' is 3 chars; 'x' is col 4
    }

    #[test]
    fn test_line_col_helper() {
        let input = "line1\nline2\nline3";
        assert_eq!(line_col(input, 0), (1, 1));
        assert_eq!(line_col(input, 5), (1, 6)); // '\n' itself
        assert_eq!(line_col(input, 6), (2, 1)); // first char of line2
        assert_eq!(line_col(input, 11), (2, 6));
        assert_eq!(line_col(input, 12), (3, 1));
    }
}