sim-kernel 0.1.0-rc.1

SIM workspace package for sim kernel.
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
use std::{collections::BTreeMap, sync::Arc};

use crate::{
    ContentId,
    capability::{CapabilityName, CapabilitySet, read_construct_capability},
    control::{ControlPolicy, ControlPolicyRef, NoopControlPolicy},
    datum_store::BTreeDatumStore,
    effect_ledger::EffectLedger,
    error::{Diagnostic, Error, Result},
    eval::{EvalPolicy, EvalPolicyRef, MacroExpanderRef, Phase},
    expr::{Expr, SourceRegistry},
    fact_store::{BTreeFactStore, FactStore},
    factory::Factory,
    handle_store::BTreeHandleStore,
    id::{LibId, Symbol},
    library::{LoadCx, Registry},
    list::ListRegistry,
    number_domain::PromotionSearchLimits,
    object::Args,
    table::TableRegistry,
    value::Value,
};

use super::{Diagnostics, Env};

/// The capability state of a [`Cx`]; an alias for [`CapabilitySet`].
pub type Capabilities = CapabilitySet;

/// The evaluation context threaded through every checked call.
///
/// `Cx` bundles the registry handle, factory, capability set, eval and control
/// policies, the data substrate (datum/fact/handle stores and ledgers), and the
/// diagnostic sink. The kernel defines this context; libraries supply the
/// behavior reached through it (registered classes, functions, number domains,
/// list/table backends, and so on). See the README sections "Library system"
/// and "Capabilities and trust".
pub struct Cx {
    env: Env,
    diagnostics: Diagnostics,
    capabilities: Capabilities,
    eval_policy: EvalPolicyRef,
    macro_expander: Option<MacroExpanderRef>,
    factory: Arc<dyn Factory>,
    pub(crate) registry: Registry,
    list_registry: ListRegistry,
    table_registry: TableRegistry,
    promotion_search_limits: PromotionSearchLimits,
    sources: SourceRegistry,
    datum_store: BTreeDatumStore,
    handles: BTreeHandleStore,
    facts: BTreeFactStore,
    load_claims: BTreeMap<LibId, Vec<ContentId>>,
    effect_ledger: EffectLedger,
    control_policy: ControlPolicyRef,
}

impl Cx {
    /// Builds a fresh context with the given eval policy and factory.
    ///
    /// The registry, capability set, and stores start empty (boot claims aside);
    /// libraries register behavior into the returned context.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::sync::Arc;
    /// # use sim_kernel::{Cx, DefaultFactory, NoopEvalPolicy};
    /// let cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
    /// assert!(cx.capabilities().iter().next().is_none());
    /// ```
    pub fn new(eval_policy: EvalPolicyRef, factory: Arc<dyn Factory>) -> Self {
        let mut datum_store = BTreeDatumStore::default();
        let mut facts = BTreeFactStore::default();
        facts.insert_boot_claims(&mut datum_store);

        Self {
            env: Env::default(),
            diagnostics: Diagnostics::default(),
            capabilities: Capabilities::default(),
            eval_policy,
            macro_expander: None,
            factory,
            registry: Registry::default(),
            list_registry: ListRegistry::default(),
            table_registry: TableRegistry::default(),
            promotion_search_limits: PromotionSearchLimits::default(),
            sources: SourceRegistry::default(),
            datum_store,
            handles: BTreeHandleStore::default(),
            facts,
            load_claims: BTreeMap::new(),
            effect_ledger: EffectLedger::default(),
            control_policy: Arc::new(NoopControlPolicy),
        }
    }

    /// Returns the active lexical environment.
    pub fn env(&self) -> &Env {
        &self.env
    }

    /// Returns the active lexical environment mutably.
    pub fn env_mut(&mut self) -> &mut Env {
        &mut self.env
    }

    /// Runs `f` with `env` installed as the active environment, then restores it.
    pub fn with_env<T>(&mut self, env: Env, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
        let saved = std::mem::replace(&mut self.env, env);
        let result = f(self);
        self.env = saved;
        result
    }

    /// Returns the active object [`Factory`].
    pub fn factory(&self) -> &dyn Factory {
        self.factory.as_ref()
    }

    /// Returns a shared handle to the active object factory.
    pub fn factory_ref(&self) -> Arc<dyn Factory> {
        self.factory.clone()
    }

    /// Runs `f` with `factory` installed as the active factory, then restores it.
    pub fn with_factory<T>(
        &mut self,
        factory: Arc<dyn Factory>,
        f: impl FnOnce(&mut Self) -> Result<T>,
    ) -> Result<T> {
        let saved = std::mem::replace(&mut self.factory, factory);
        let result = f(self);
        self.factory = saved;
        result
    }

    /// Returns the behavior [`Registry`].
    pub fn registry(&self) -> &Registry {
        &self.registry
    }

    /// Returns the behavior registry mutably, for registering exports.
    pub fn registry_mut(&mut self) -> &mut Registry {
        &mut self.registry
    }

    /// Returns the registered list backend.
    pub fn list_registry(&self) -> &ListRegistry {
        &self.list_registry
    }

    /// Returns the list backend mutably.
    pub fn list_registry_mut(&mut self) -> &mut ListRegistry {
        &mut self.list_registry
    }

    /// Returns the registered table backend.
    pub fn table_registry(&self) -> &TableRegistry {
        &self.table_registry
    }

    /// Returns the table backend mutably.
    pub fn table_registry_mut(&mut self) -> &mut TableRegistry {
        &mut self.table_registry
    }

    /// Runs `f` with `registry` installed as the active registry, then restores it.
    pub fn with_registry<T>(
        &mut self,
        registry: Registry,
        f: impl FnOnce(&mut Self) -> Result<T>,
    ) -> Result<T> {
        let saved = std::mem::replace(&mut self.registry, registry);
        let result = f(self);
        self.registry = saved;
        result
    }

    /// Builds a list value through the registered list backend.
    pub fn new_list(&mut self, items: Vec<Value>) -> Result<Value> {
        let registry = std::mem::take(&mut self.list_registry);
        let result = registry.new_list(self, items);
        self.list_registry = registry;
        result
    }

    /// Builds a cons cell through the registered list backend.
    pub fn new_cons(&mut self, car: Value, cdr: Value) -> Result<Value> {
        let registry = std::mem::take(&mut self.list_registry);
        let result = registry.new_cons(self, car, cdr);
        self.list_registry = registry;
        result
    }

    /// Builds a table value through the registered table backend.
    pub fn new_table(&mut self, entries: Vec<(Symbol, Value)>) -> Result<Value> {
        let registry = std::mem::take(&mut self.table_registry);
        let result = registry.new_table(self, entries);
        self.table_registry = registry;
        result
    }

    /// Returns the source registry.
    pub fn sources(&self) -> &SourceRegistry {
        &self.sources
    }

    /// Returns the source registry mutably.
    pub fn sources_mut(&mut self) -> &mut SourceRegistry {
        &mut self.sources
    }

    /// Returns the datum store.
    pub fn datum_store(&self) -> &BTreeDatumStore {
        &self.datum_store
    }

    /// Returns the datum store mutably.
    pub fn datum_store_mut(&mut self) -> &mut BTreeDatumStore {
        &mut self.datum_store
    }

    /// Returns the handle store.
    pub fn handles(&self) -> &BTreeHandleStore {
        &self.handles
    }

    /// Returns the handle store mutably.
    pub fn handles_mut(&mut self) -> &mut BTreeHandleStore {
        &mut self.handles
    }

    /// Returns the fact store.
    pub fn facts(&self) -> &BTreeFactStore {
        &self.facts
    }

    /// Returns the fact store mutably.
    pub fn facts_mut(&mut self) -> &mut BTreeFactStore {
        &mut self.facts
    }

    /// Returns the effect ledger.
    pub fn effect_ledger(&self) -> &EffectLedger {
        &self.effect_ledger
    }

    /// Returns the effect ledger mutably.
    pub fn effect_ledger_mut(&mut self) -> &mut EffectLedger {
        &mut self.effect_ledger
    }

    /// Returns the active control policy.
    pub fn control_policy(&self) -> &dyn ControlPolicy {
        self.control_policy.as_ref()
    }

    /// Returns a shared handle to the active control policy.
    pub fn control_policy_ref(&self) -> ControlPolicyRef {
        self.control_policy.clone()
    }

    /// Returns the name of the active control policy.
    pub fn control_policy_name(&self) -> &'static str {
        self.control_policy.name()
    }

    /// Replaces the active control policy.
    pub fn set_control_policy(&mut self, control_policy: ControlPolicyRef) {
        self.control_policy = control_policy;
    }

    pub(crate) fn with_effect_ledger<T>(
        &mut self,
        f: impl FnOnce(&mut Self, &mut EffectLedger) -> Result<T>,
    ) -> Result<T> {
        let mut ledger = std::mem::take(&mut self.effect_ledger);
        let result = f(self, &mut ledger);
        self.effect_ledger = ledger;
        result
    }

    /// Inserts a claim into the fact store, subject to capability authorization.
    pub fn insert_fact(&mut self, claim: crate::Claim) -> Result<crate::Ref> {
        self.facts
            .insert_authorized(&self.capabilities, &mut self.datum_store, claim)
    }

    /// Inserts a claim and records it as part of a loaded library's receipt.
    ///
    /// When the claim did not already exist, `unload_lib` retracts it with the
    /// rest of `lib_id`'s recorded load effects. Pre-existing identical claims
    /// are left owned by their original publisher.
    pub fn insert_fact_for_lib(
        &mut self,
        lib_id: LibId,
        claim: crate::Claim,
    ) -> Result<crate::Ref> {
        let (reference, inserted) = self.insert_recorded_fact(claim)?;
        if let Some(inserted) = inserted {
            self.record_load_claims(lib_id, vec![inserted]);
        }
        Ok(reference)
    }

    pub(crate) fn insert_recorded_fact(
        &mut self,
        claim: crate::Claim,
    ) -> Result<(crate::Ref, Option<ContentId>)> {
        let id = claim.content_id(&mut self.datum_store)?;
        let existed = self.facts.get(&id).is_some();
        let inserted = self.insert_fact(claim)?;
        let crate::Ref::Content(inserted_id) = inserted else {
            return Err(Error::Lib(
                "fact insertion returned a non-content reference".to_owned(),
            ));
        };
        debug_assert_eq!(inserted_id, id);
        Ok((
            crate::Ref::Content(inserted_id.clone()),
            (!existed).then_some(inserted_id),
        ))
    }

    /// Queries the fact store for claims matching `pattern`, applying read policy.
    pub fn query_facts(&self, pattern: crate::ClaimPattern) -> Result<Vec<crate::Claim>> {
        self.facts.query_authorized(self, pattern)
    }

    pub(crate) fn record_load_claims(&mut self, lib_id: LibId, claim_ids: Vec<ContentId>) {
        if claim_ids.is_empty() {
            return;
        }
        self.load_claims
            .entry(lib_id)
            .or_default()
            .extend(claim_ids);
    }

    pub(crate) fn remove_load_claims(&mut self, lib_ids: &[LibId]) {
        for lib_id in lib_ids {
            if let Some(claim_ids) = self.load_claims.remove(lib_id) {
                for claim_id in claim_ids {
                    self.facts.remove(&claim_id);
                }
            }
        }
    }

    /// Returns the limits bounding number-domain promotion search.
    pub fn promotion_search_limits(&self) -> PromotionSearchLimits {
        self.promotion_search_limits
    }

    /// Sets the limits bounding number-domain promotion search.
    pub fn set_promotion_search_limits(&mut self, limits: PromotionSearchLimits) {
        self.promotion_search_limits = limits;
    }

    pub(crate) fn load_cx(&self) -> LoadCx {
        LoadCx::new(
            self.capabilities.clone(),
            self.factory.clone(),
            self.registry.clone(),
        )
    }

    /// Returns the active evaluation policy.
    pub fn eval_policy(&self) -> &dyn EvalPolicy {
        self.eval_policy.as_ref()
    }

    /// Returns a shared handle to the active evaluation policy.
    pub fn eval_policy_ref(&self) -> EvalPolicyRef {
        self.eval_policy.clone()
    }

    /// Returns the name of the active evaluation policy.
    pub fn eval_policy_name(&self) -> &'static str {
        self.eval_policy.name()
    }

    /// Replaces the active evaluation policy.
    pub fn set_eval_policy(&mut self, eval_policy: EvalPolicyRef) {
        self.eval_policy = eval_policy;
    }

    /// Installs a macro expander.
    pub fn set_macro_expander(&mut self, macro_expander: MacroExpanderRef) {
        self.macro_expander = Some(macro_expander);
    }

    /// Removes any installed macro expander.
    pub fn clear_macro_expander(&mut self) {
        self.macro_expander = None;
    }

    /// Returns the installed macro expander, if any.
    pub fn macro_expander_ref(&self) -> Option<MacroExpanderRef> {
        self.macro_expander.clone()
    }

    /// Expands macros in `expr` for the given phase, or returns it unchanged.
    pub fn expand_macros(&mut self, phase: Phase, expr: Expr) -> Result<Expr> {
        match self.macro_expander.clone() {
            Some(expander) => expander.expand_expr(self, phase, expr),
            None => Ok(expr),
        }
    }

    /// Returns the accumulated diagnostics.
    pub fn diagnostics(&self) -> &Diagnostics {
        &self.diagnostics
    }

    /// Drains and returns the accumulated diagnostics.
    pub fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
        self.diagnostics.take()
    }

    /// Records an already-built diagnostic.
    pub fn push_diagnostic(&mut self, diagnostic: Diagnostic) {
        self.diagnostics.push_diagnostic(diagnostic);
    }

    /// Records an info-level diagnostic from a message.
    pub fn push_info(&mut self, message: impl Into<String>) {
        self.diagnostics.push_info(message);
    }

    /// Grants a capability to this context.
    pub fn grant(&mut self, capability: CapabilityName) {
        self.capabilities.insert(capability);
    }

    /// Grants a capability named by a static string.
    pub fn grant_named(&mut self, capability: &'static str) {
        self.capabilities.insert(CapabilityName::new(capability));
    }

    /// Returns the granted capability set.
    pub fn capabilities(&self) -> &Capabilities {
        &self.capabilities
    }

    /// Runs `f` with `capabilities` installed, then restores the prior set.
    pub fn with_capabilities<T>(
        &mut self,
        capabilities: Capabilities,
        f: impl FnOnce(&mut Self) -> Result<T>,
    ) -> Result<T> {
        let saved = std::mem::replace(&mut self.capabilities, capabilities);
        let result = f(self);
        self.capabilities = saved;
        result
    }

    /// Resolves a registered class by symbol.
    pub fn resolve_class(&self, symbol: &Symbol) -> Result<Value> {
        self.registry()
            .class_by_symbol(symbol)
            .cloned()
            .ok_or_else(|| Error::UnknownClass {
                class: symbol.clone(),
            })
    }

    /// Resolves a registered function by symbol.
    pub fn resolve_function(&self, symbol: &Symbol) -> Result<Value> {
        self.registry()
            .function_by_symbol(symbol)
            .cloned()
            .ok_or_else(|| Error::UnknownFunction {
                function: symbol.clone(),
            })
    }

    /// Resolves a registered macro by symbol.
    pub fn resolve_macro(&self, symbol: &Symbol) -> Result<Value> {
        self.registry()
            .macro_by_symbol(symbol)
            .cloned()
            .ok_or_else(|| Error::UnknownSymbol {
                symbol: symbol.clone(),
            })
    }

    /// Resolves a registered shape by symbol.
    pub fn resolve_shape(&self, symbol: &Symbol) -> Result<Value> {
        self.registry()
            .shape_by_symbol(symbol)
            .cloned()
            .ok_or_else(|| Error::UnknownSymbol {
                symbol: symbol.clone(),
            })
    }

    /// Resolves a registered codec by symbol.
    pub fn resolve_codec(&self, symbol: &Symbol) -> Result<Value> {
        self.registry()
            .codec_by_symbol(symbol)
            .cloned()
            .ok_or_else(|| Error::UnknownSymbol {
                symbol: symbol.clone(),
            })
    }

    /// Resolves a registered number domain by symbol.
    pub fn resolve_number_domain(&self, symbol: &Symbol) -> Result<Value> {
        self.registry()
            .number_domain_by_symbol(symbol)
            .cloned()
            .ok_or_else(|| Error::UnknownSymbol {
                symbol: symbol.clone(),
            })
    }

    /// Resolves a registered value binding by symbol.
    pub fn resolve_value(&self, symbol: &Symbol) -> Result<Value> {
        self.registry()
            .value_by_symbol(symbol)
            .cloned()
            .ok_or_else(|| Error::UnknownSymbol {
                symbol: symbol.clone(),
            })
    }

    /// Calls a callable value with already-evaluated arguments.
    pub fn call_value(&mut self, value: Value, args: Args) -> Result<Value> {
        let Some(callable) = value.object().as_callable() else {
            return Err(Error::TypeMismatch {
                expected: "callable",
                found: "non-callable",
            });
        };
        callable.call(self, args)
    }

    /// Calls a callable value with raw, unevaluated argument expressions.
    pub fn call_exprs(&mut self, value: Value, args: Vec<crate::expr::Expr>) -> Result<Value> {
        let Some(callable) = value.object().as_callable() else {
            return Err(Error::TypeMismatch {
                expected: "callable",
                found: "non-callable",
            });
        };
        callable.call_exprs(self, crate::object::RawArgs::new(args))
    }

    /// Resolves a function by symbol and calls it.
    pub fn call_function(&mut self, symbol: &Symbol, args: Args) -> Result<Value> {
        let function = self.resolve_function(symbol)?;
        self.call_value(function, args)
    }

    /// Resolves a class by symbol and calls its constructor.
    pub fn call_class(&mut self, symbol: &Symbol, args: Args) -> Result<Value> {
        let class = self.resolve_class(symbol)?;
        self.call_value(class, args)
    }

    /// Constructs an instance of `class` from read-time arguments.
    ///
    /// Requires the [`read_construct_capability`](crate::capability::read_construct_capability).
    pub fn read_construct(&mut self, class: &Symbol, args: Vec<Value>) -> Result<Value> {
        self.require(&read_construct_capability())?;

        let class_value = self.resolve_class(class)?;
        let Some(class_impl) = class_value.object().as_class() else {
            return Err(Error::TypeMismatch {
                expected: "class",
                found: "non-class",
            });
        };
        let Some(read_constructor) = class_impl.read_constructor(self)? else {
            return Err(Error::Eval(format!(
                "class {} has no read constructor",
                class
            )));
        };
        let Some(read_impl) = read_constructor.object().as_read_constructor() else {
            return Err(Error::TypeMismatch {
                expected: "read-constructor",
                found: "non-read-constructor",
            });
        };
        read_impl.construct_read(self, args)
    }

    /// Forces a value to the requested demand through the active eval policy.
    pub fn force(&mut self, value: Value, demand: crate::eval::Demand) -> Result<Value> {
        let eval_policy = self.eval_policy.clone();
        eval_policy.force(self, value, demand)
    }

    /// Evaluates an expression through the active eval policy.
    pub fn eval_expr(&mut self, expr: crate::expr::Expr) -> Result<Value> {
        let eval_policy = self.eval_policy.clone();
        eval_policy.eval_expr(self, expr)
    }

    /// Returns true when `name` resolves across environment or registry layers.
    pub fn symbol_is_bound(&mut self, name: &Symbol) -> bool {
        self.env().get(name).is_some()
            || self.resolve_function(name).is_ok()
            || self.resolve_class(name).is_ok()
            || self.resolve_shape(name).is_ok()
            || self.resolve_value(name).is_ok()
    }

    /// Resolves an unbound value-position symbol through the active eval policy.
    pub fn resolve_unbound_symbol(&mut self, symbol: Symbol) -> Result<Value> {
        let eval_policy = self.eval_policy_ref();
        eval_policy.resolve_unbound_symbol(self, symbol)
    }

    /// Resolves an unbound call through the active eval policy.
    pub fn resolve_unbound_call(
        &mut self,
        operator: Symbol,
        args: Vec<crate::expr::Expr>,
    ) -> Result<Value> {
        let eval_policy = self.eval_policy_ref();
        eval_policy.resolve_unbound_call(self, operator, args)
    }

    /// Demands a capability, returning [`Error::CapabilityDenied`] when absent.
    pub fn require(&self, capability: &CapabilityName) -> Result<()> {
        if self.capabilities.contains(capability) {
            Ok(())
        } else {
            Err(Error::CapabilityDenied {
                capability: capability.clone(),
            })
        }
    }

    /// Demands every capability in turn, failing on the first absent one.
    pub fn require_all(&self, capabilities: &[CapabilityName]) -> Result<()> {
        for capability in capabilities {
            self.require(capability)?;
        }
        Ok(())
    }
}