sim-kernel 0.1.4

Small protocol kernel contracts for the expandable SIM Rust runtime.
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
//! The [`Term`] contract: the checked form that bridges expressions and data.
//!
//! The kernel defines the term representation and its operation keys; it sits
//! on the path from checked forms to objects, and libraries interpret terms.

use crate::{
    datum::Datum,
    error::{Error, Result},
    expr::{Expr, NumberLiteral, QuoteMode},
    id::Symbol,
    ref_id::{ContentId, Coordinate, HandleId, Ref},
};

/// Stable operation identity used by lowered `Term::Op` nodes.
///
/// Lowered `Term::Op` nodes carry only the key value so terms can express
/// explicit op invocations. Operation specs, dispatch, adapters, and
/// capability gates are resolved by the op layer.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OpKey {
    /// The operation's namespace.
    pub namespace: Symbol,
    /// The operation's name within the namespace.
    pub name: Symbol,
    /// The operation's version.
    pub version: u16,
}

impl OpKey {
    /// Builds an op key from a namespace, name, and version.
    pub fn new(namespace: Symbol, name: Symbol, version: u16) -> Self {
        Self {
            namespace,
            name,
            version,
        }
    }
}

/// Lowered executable form.
///
/// Current `Expr` values lower as follows:
///
/// - scalar data -> `Term::Literal`
/// - `Expr::Symbol` -> `Term::Ref(Ref::Symbol)`
/// - `Expr::Local` -> `Term::Local`
/// - data-only list, vector, map, and set -> `Term::Literal`
/// - call -> `Term::Call`
/// - infix, prefix, and postfix -> `Term::Call` with a symbolic target
/// - block -> `Term::Seq`
/// - quote -> `Term::Quote` over pure `Datum`
/// - annotated -> `Term::Annotated` with datum annotations
/// - extension -> `Term::Extension` with a datum payload
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Term {
    /// A constant datum value.
    Literal(Datum),
    /// A reference resolved through the registry or substrate.
    Ref(Ref),
    /// A lexical local binding referenced by name.
    Local(Symbol),
    /// A local binding form: bind `name` to `value` within `body`.
    Let {
        /// The bound name.
        name: Symbol,
        /// The term producing the bound value.
        value: Box<Term>,
        /// The body evaluated with the binding in scope.
        body: Box<Term>,
    },
    /// An explicit operation invocation over one input term.
    Op {
        /// The operation key naming the op.
        op: OpKey,
        /// The input term the op consumes.
        input: Box<Term>,
    },
    /// A call of `target` with positional `args`.
    Call {
        /// The term producing the callable target.
        target: Box<Term>,
        /// The positional argument terms.
        args: Vec<Term>,
    },
    /// A sequence of terms evaluated in order.
    Seq(Vec<Term>),
    /// A quoted datum carried at a given quote mode.
    Quote {
        /// The quote mode (quote, quasiquote, ...).
        mode: QuoteMode,
        /// The quoted datum.
        datum: Datum,
    },
    /// A term carrying datum-valued annotations.
    Annotated {
        /// The annotated inner term.
        term: Box<Term>,
        /// The name/datum annotation pairs.
        annotations: Vec<(Symbol, Datum)>,
    },
    /// An open extension term with a tag and datum payload.
    Extension {
        /// The extension tag.
        tag: Symbol,
        /// The extension payload datum.
        payload: Datum,
    },
}

impl Term {
    /// Lowers a checked [`Expr`] into its executable [`Term`] form.
    ///
    /// This walks the expression graph and produces the lowered representation
    /// described on [`Term`]; it fails when a sub-expression cannot become a
    /// pure [`Datum`].
    pub fn lower(expr: Expr) -> Result<Self> {
        match expr {
            Expr::Nil => Ok(Self::Literal(Datum::Nil)),
            Expr::Bool(value) => Ok(Self::Literal(Datum::Bool(value))),
            Expr::Number(value) => Ok(Self::Literal(Datum::Number(value))),
            Expr::Symbol(symbol) => Ok(Self::Ref(Ref::Symbol(symbol))),
            Expr::Local(symbol) => Ok(Self::Local(symbol)),
            Expr::String(value) => Ok(Self::Literal(Datum::String(value))),
            Expr::Bytes(value) => Ok(Self::Literal(Datum::Bytes(value))),
            Expr::List(items) => data_literal(Expr::List(items)),
            Expr::Vector(items) => data_literal(Expr::Vector(items)),
            Expr::Map(entries) => data_literal(Expr::Map(entries)),
            Expr::Set(items) => data_literal(Expr::Set(items)),
            Expr::Call { operator, args } => Ok(Self::Call {
                target: Box::new(Self::lower(*operator)?),
                args: lower_terms(args)?,
            }),
            Expr::Infix {
                operator,
                left,
                right,
            } => Ok(Self::Call {
                target: Box::new(Self::Ref(Ref::Symbol(operator))),
                args: vec![Self::lower(*left)?, Self::lower(*right)?],
            }),
            Expr::Prefix { operator, arg } | Expr::Postfix { operator, arg } => Ok(Self::Call {
                target: Box::new(Self::Ref(Ref::Symbol(operator))),
                args: vec![Self::lower(*arg)?],
            }),
            Expr::Block(items) => Ok(Self::Seq(lower_terms(items)?)),
            Expr::Quote { mode, expr } => Ok(Self::Quote {
                mode,
                datum: Datum::try_from(*expr)?,
            }),
            Expr::Annotated { expr, annotations } => {
                let annotations = annotations
                    .into_iter()
                    .map(|(name, expr)| Ok((name, Datum::try_from(expr)?)))
                    .collect::<Result<Vec<_>>>()?;
                Ok(Self::Annotated {
                    term: Box::new(Self::lower(*expr)?),
                    annotations,
                })
            }
            Expr::Extension { tag, payload } => Ok(Self::Extension {
                tag,
                payload: Datum::try_from(*payload)?,
            }),
        }
    }

    /// Encodes this lowered executable form as canonical SIM data.
    pub fn to_datum(&self) -> Datum {
        term_datum(self)
    }
}

impl TryFrom<Expr> for Term {
    type Error = Error;

    fn try_from(expr: Expr) -> Result<Self> {
        Self::lower(expr)
    }
}

impl From<Term> for Datum {
    fn from(term: Term) -> Self {
        term.to_datum()
    }
}

impl From<Term> for Expr {
    fn from(term: Term) -> Self {
        match term {
            Term::Literal(datum) => Self::from(datum),
            Term::Ref(reference) => ref_to_expr(reference),
            Term::Local(symbol) => Self::Local(symbol),
            Term::Let { name, value, body } => Self::Extension {
                tag: core_symbol("term-let"),
                payload: Box::new(Self::Map(vec![
                    (Self::Symbol(Symbol::new("name")), Self::Symbol(name)),
                    (Self::Symbol(Symbol::new("value")), Self::from(*value)),
                    (Self::Symbol(Symbol::new("body")), Self::from(*body)),
                ])),
            },
            Term::Op { op, input } => Self::Extension {
                tag: core_symbol("term-op"),
                payload: Box::new(Self::Map(vec![
                    (
                        Self::Symbol(Symbol::new("op")),
                        Self::from(op_key_datum(op)),
                    ),
                    (Self::Symbol(Symbol::new("input")), Self::from(*input)),
                ])),
            },
            Term::Call { target, args } => Self::Call {
                operator: Box::new(Self::from(*target)),
                args: args.into_iter().map(Self::from).collect(),
            },
            Term::Seq(items) => Self::Block(items.into_iter().map(Self::from).collect()),
            Term::Quote { mode, datum } => Self::Quote {
                mode,
                expr: Box::new(Self::from(datum)),
            },
            Term::Annotated { term, annotations } => Self::Annotated {
                expr: Box::new(Self::from(*term)),
                annotations: annotations
                    .into_iter()
                    .map(|(name, datum)| (name, Self::from(datum)))
                    .collect(),
            },
            Term::Extension { tag, payload } => Self::Extension {
                tag,
                payload: Box::new(Self::from(payload)),
            },
        }
    }
}

fn lower_terms(exprs: Vec<Expr>) -> Result<Vec<Term>> {
    exprs.into_iter().map(Term::lower).collect()
}

fn data_literal(expr: Expr) -> Result<Term> {
    Datum::try_from(expr).map(Term::Literal)
}

fn term_datum(term: &Term) -> Datum {
    match term {
        Term::Literal(datum) => term_node("literal", vec![(Symbol::new("datum"), datum.clone())]),
        Term::Ref(reference) => term_node(
            "ref",
            vec![(Symbol::new("ref"), ref_datum(reference.clone()))],
        ),
        Term::Local(symbol) => term_node(
            "local",
            vec![(Symbol::new("symbol"), Datum::Symbol(symbol.clone()))],
        ),
        Term::Let { name, value, body } => term_node(
            "let",
            vec![
                (Symbol::new("name"), Datum::Symbol(name.clone())),
                (Symbol::new("value"), term_datum(value)),
                (Symbol::new("body"), term_datum(body)),
            ],
        ),
        Term::Op { op, input } => term_node(
            "op",
            vec![
                (Symbol::new("op"), op_key_datum(op.clone())),
                (Symbol::new("input"), term_datum(input)),
            ],
        ),
        Term::Call { target, args } => term_node(
            "call",
            vec![
                (Symbol::new("target"), term_datum(target)),
                (Symbol::new("args"), terms_datum(args)),
            ],
        ),
        Term::Seq(items) => term_node("seq", vec![(Symbol::new("items"), terms_datum(items))]),
        Term::Quote { mode, datum } => term_node(
            "quote",
            vec![
                (Symbol::new("mode"), Datum::Symbol(quote_mode_symbol(*mode))),
                (Symbol::new("datum"), datum.clone()),
            ],
        ),
        Term::Annotated { term, annotations } => term_node(
            "annotated",
            vec![
                (Symbol::new("term"), term_datum(term)),
                (
                    Symbol::new("annotations"),
                    Datum::Vector(
                        annotations
                            .iter()
                            .map(|(name, datum)| Datum::Node {
                                tag: core_symbol("term-annotation"),
                                fields: vec![
                                    (Symbol::new("name"), Datum::Symbol(name.clone())),
                                    (Symbol::new("datum"), datum.clone()),
                                ],
                            })
                            .collect(),
                    ),
                ),
            ],
        ),
        Term::Extension { tag, payload } => term_node(
            "extension",
            vec![
                (Symbol::new("tag"), Datum::Symbol(tag.clone())),
                (Symbol::new("payload"), payload.clone()),
            ],
        ),
    }
}

fn term_node(kind: &str, fields: Vec<(Symbol, Datum)>) -> Datum {
    let mut node_fields = vec![(Symbol::new("kind"), Datum::Symbol(core_symbol(kind)))];
    node_fields.extend(fields);
    Datum::Node {
        tag: core_symbol("term"),
        fields: node_fields,
    }
}

fn terms_datum(terms: &[Term]) -> Datum {
    Datum::Vector(terms.iter().map(term_datum).collect())
}

fn quote_mode_symbol(mode: QuoteMode) -> Symbol {
    core_symbol(match mode {
        QuoteMode::Quote => "quote",
        QuoteMode::QuasiQuote => "quasiquote",
        QuoteMode::Unquote => "unquote",
        QuoteMode::Splice => "splice",
        QuoteMode::Syntax => "syntax",
    })
}

fn ref_to_expr(reference: Ref) -> Expr {
    match reference {
        Ref::Symbol(symbol) => Expr::Symbol(symbol),
        other => Expr::from(ref_datum(other)),
    }
}

fn ref_datum(reference: Ref) -> Datum {
    match reference {
        Ref::Symbol(symbol) => Datum::Node {
            tag: core_symbol("ref"),
            fields: vec![
                (Symbol::new("kind"), Datum::Symbol(core_symbol("symbol"))),
                (Symbol::new("symbol"), Datum::Symbol(symbol)),
            ],
        },
        Ref::Content(content) => Datum::Node {
            tag: core_symbol("ref"),
            fields: vec![
                (Symbol::new("kind"), Datum::Symbol(core_symbol("content"))),
                (Symbol::new("content"), content_id_datum(content)),
            ],
        },
        Ref::Handle(handle) => Datum::Node {
            tag: core_symbol("ref"),
            fields: vec![
                (Symbol::new("kind"), Datum::Symbol(core_symbol("handle"))),
                (Symbol::new("id"), handle_id_datum(handle)),
            ],
        },
        Ref::Coord(coordinate) => coordinate_datum(coordinate),
    }
}

fn coordinate_datum(coordinate: Coordinate) -> Datum {
    Datum::Node {
        tag: core_symbol("ref"),
        fields: vec![
            (Symbol::new("kind"), Datum::Symbol(core_symbol("coord"))),
            (Symbol::new("space"), Datum::Symbol(coordinate.space)),
            (Symbol::new("ordinal"), content_id_datum(coordinate.ordinal)),
        ],
    }
}

fn content_id_datum(content: ContentId) -> Datum {
    Datum::Node {
        tag: core_symbol("content-id"),
        fields: vec![
            (Symbol::new("algorithm"), Datum::Symbol(content.algorithm)),
            (Symbol::new("bytes"), Datum::Bytes(content.bytes.to_vec())),
        ],
    }
}

fn handle_id_datum(handle: HandleId) -> Datum {
    Datum::Bytes(handle.0.to_be_bytes().to_vec())
}

fn op_key_datum(op: OpKey) -> Datum {
    Datum::Node {
        tag: core_symbol("op-key"),
        fields: vec![
            (Symbol::new("namespace"), Datum::Symbol(op.namespace)),
            (Symbol::new("name"), Datum::Symbol(op.name)),
            (
                Symbol::new("version"),
                Datum::Number(NumberLiteral {
                    domain: core_symbol("u16"),
                    canonical: op.version.to_string(),
                }),
            ),
        ],
    }
}

fn core_symbol(name: &str) -> Symbol {
    Symbol::qualified("core", name)
}