Skip to main content

sim_lib_platform/
runtime.rs

1// conformance: product runtime composition keeps the platform membrane explicit.
2
3use std::{sync::Arc, time::Duration};
4
5use sim_kernel::{
6    AbiVersion, Args, Callable, CapabilityName, Consistency, Cx, Error, EvalMode, EvalRequest,
7    Export, Expr, Lib, LibManifest, LibTarget, Linker, LoadCx, Object, ObjectCompat, Result,
8    Symbol, Value, Version,
9};
10
11/// The lexical binding holding the platform site for the current realization.
12///
13/// The binding is deliberately neither a registry singleton nor a target lookup:
14/// child realizations can replace it without changing the loaded API.
15pub const ACTIVE_PLATFORM_SITE: &str = "active-site";
16
17/// The thirteen operations in the Small SIM API. This enum is intentionally closed.
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub enum PlatformFunctionKind {
20    Card,
21    Require,
22    Mounts,
23    Open,
24    Share,
25    Notify,
26    ClipboardRead,
27    ClipboardWrite,
28    PermissionStatus,
29    PermissionRequest,
30    KeepAwake,
31    Lifecycle,
32    Activations,
33}
34
35impl PlatformFunctionKind {
36    /// Every platform API operation, in the public contract order.
37    pub const ALL: [Self; 13] = [
38        Self::Card,
39        Self::Require,
40        Self::Mounts,
41        Self::Open,
42        Self::Share,
43        Self::Notify,
44        Self::ClipboardRead,
45        Self::ClipboardWrite,
46        Self::PermissionStatus,
47        Self::PermissionRequest,
48        Self::KeepAwake,
49        Self::Lifecycle,
50        Self::Activations,
51    ];
52
53    #[must_use]
54    pub fn symbol(self) -> Symbol {
55        Symbol::qualified(
56            "platform",
57            match self {
58                Self::Card => "card",
59                Self::Require => "require",
60                Self::Mounts => "mounts",
61                Self::Open => "open",
62                Self::Share => "share",
63                Self::Notify => "notify",
64                Self::ClipboardRead => "clipboard-read",
65                Self::ClipboardWrite => "clipboard-write",
66                Self::PermissionStatus => "permission-status",
67                Self::PermissionRequest => "permission-request",
68                Self::KeepAwake => "keep-awake",
69                Self::Lifecycle => "lifecycle",
70                Self::Activations => "activations",
71            },
72        )
73    }
74
75    fn arity(self) -> usize {
76        match self {
77            Self::Card | Self::Mounts | Self::Lifecycle | Self::Activations => 0,
78            Self::Require
79            | Self::Open
80            | Self::Share
81            | Self::Notify
82            | Self::ClipboardRead
83            | Self::ClipboardWrite
84            | Self::PermissionStatus
85            | Self::PermissionRequest
86            | Self::KeepAwake => 1,
87        }
88    }
89
90    fn capability(self, args: &[Expr]) -> Result<Option<CapabilityName>> {
91        let fixed = match self {
92            Self::Open => Some("platform.open"),
93            Self::Share => Some("platform.share"),
94            Self::Notify => Some("platform.notify"),
95            Self::ClipboardRead => Some("platform.clipboard.read"),
96            Self::ClipboardWrite => Some("platform.clipboard.write"),
97            Self::KeepAwake => Some("platform.power.keep-awake"),
98            _ => None,
99        };
100        if let Some(name) = fixed {
101            return Ok(Some(CapabilityName::new(name)));
102        }
103        if self == Self::PermissionRequest {
104            let Expr::Symbol(service) = &args[0] else {
105                return Err(Error::Eval(
106                    "platform/permission-request expects a service symbol".to_owned(),
107                ));
108            };
109            let name = service.to_string().replace(['/', '-'], ".");
110            return Ok(Some(CapabilityName::new(name)));
111        }
112        Ok(None)
113    }
114}
115
116/// Returns the exact public function symbols; useful to loaders and conformance tests.
117#[must_use]
118pub fn platform_function_symbols() -> Vec<Symbol> {
119    PlatformFunctionKind::ALL
120        .iter()
121        .map(|kind| kind.symbol())
122        .collect()
123}
124
125/// Loadable Small SIM API library.
126pub struct PlatformLib;
127
128impl Lib for PlatformLib {
129    fn manifest(&self) -> LibManifest {
130        LibManifest {
131            id: Symbol::qualified("sim", "platform"),
132            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
133            abi: AbiVersion { major: 0, minor: 1 },
134            target: LibTarget::HostRegistered,
135            requires: Vec::new(),
136            capabilities: Vec::new(),
137            exports: platform_function_symbols()
138                .into_iter()
139                .map(|symbol| Export::Function {
140                    symbol,
141                    function_id: None,
142                })
143                .collect(),
144        }
145    }
146
147    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
148        for kind in PlatformFunctionKind::ALL {
149            linker.function_value(
150                kind.symbol(),
151                cx.factory().opaque(Arc::new(PlatformFunction(kind)))?,
152            )?;
153        }
154        Ok(())
155    }
156}
157
158/// Install the platform facade once in a context.
159///
160/// # Errors
161/// Returns a kernel load error when the manifest or one of its function exports
162/// cannot be registered atomically.
163pub fn install_platform_lib(cx: &mut Cx) -> Result<()> {
164    if cx
165        .registry()
166        .lib(&Symbol::qualified("sim", "platform"))
167        .is_none()
168    {
169        cx.load_lib(&PlatformLib)?;
170    }
171    Ok(())
172}
173
174/// One callable from the closed platform surface.
175#[derive(Clone, Copy, Debug)]
176pub struct PlatformFunction(pub PlatformFunctionKind);
177
178impl Object for PlatformFunction {
179    fn display(&self, _cx: &mut Cx) -> Result<String> {
180        Ok(format!("#<function {}>", self.0.symbol()))
181    }
182    fn as_any(&self) -> &dyn std::any::Any {
183        self
184    }
185}
186
187impl ObjectCompat for PlatformFunction {
188    fn as_callable(&self) -> Option<&dyn Callable> {
189        Some(self)
190    }
191}
192
193impl Callable for PlatformFunction {
194    fn call(&self, cx: &mut Cx, args: Args) -> Result<Value> {
195        let values = args.into_vec();
196        if values.len() != self.0.arity() {
197            return Err(Error::Eval(format!(
198                "{} expects {} argument(s), found {}",
199                self.0.symbol(),
200                self.0.arity(),
201                values.len()
202            )));
203        }
204        let exprs = values
205            .into_iter()
206            .map(|value| value.object().as_expr(cx))
207            .collect::<Result<Vec<_>>>()?;
208        // Capability precedes provider permission handling, so an unprivileged
209        // caller cannot use the OS prompt as a capability oracle.
210        if let Some(capability) = self.0.capability(&exprs)? {
211            cx.require(&capability)?;
212        }
213        let site = cx
214            .env()
215            .get(&Symbol::qualified("platform", ACTIVE_PLATFORM_SITE))
216            .ok_or_else(|| {
217                Error::Eval(
218                    "no PlatformSite is bound in the current realization environment".to_owned(),
219                )
220            })?;
221        let fabric = site.object().as_eval_fabric().ok_or(Error::TypeMismatch {
222            expected: "platform-site EvalFabric",
223            found: "non-eval-fabric",
224        })?;
225        let required_capabilities = self.0.capability(&exprs)?.into_iter().collect();
226        let reply = fabric.realize(
227            cx,
228            EvalRequest {
229                expr: Expr::Call {
230                    operator: Box::new(Expr::Symbol(self.0.symbol())),
231                    args: exprs,
232                },
233                result_shape: None,
234                required_capabilities,
235                deadline: Some(Duration::from_secs(30)),
236                consistency: Consistency::LocalOnly,
237                mode: EvalMode::Eval,
238                answer_limit: Some(1),
239                stream_buffer: None,
240                stream: false,
241                trace: true,
242            },
243        )?;
244        Ok(reply.value)
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use sim_kernel::{EvalFabric, EvalReply};
252    use std::sync::Mutex;
253
254    struct RecordingSite(Mutex<Vec<Expr>>);
255    impl Object for RecordingSite {
256        fn display(&self, _: &mut Cx) -> Result<String> {
257            Ok("#<recording-platform-site>".into())
258        }
259        fn as_any(&self) -> &dyn std::any::Any {
260            self
261        }
262    }
263    impl ObjectCompat for RecordingSite {
264        fn as_eval_fabric(&self) -> Option<&dyn EvalFabric> {
265            Some(self)
266        }
267    }
268    impl EvalFabric for RecordingSite {
269        fn realize(&self, cx: &mut Cx, request: EvalRequest) -> Result<EvalReply> {
270            self.0.lock().unwrap().push(request.expr.clone());
271            Ok(EvalReply {
272                value: cx.factory().expr(request.expr)?,
273                diagnostics: Vec::new(),
274                trace: None,
275            })
276        }
277    }
278
279    fn cx_with(site: Arc<RecordingSite>) -> Cx {
280        let mut cx = sim_kernel::testing::bare_cx();
281        let value = cx.factory().opaque(site).unwrap();
282        cx.env_mut()
283            .define(Symbol::qualified("platform", ACTIVE_PLATFORM_SITE), value);
284        cx
285    }
286
287    #[test]
288    fn manifest_is_the_closed_thirteen_function_surface() {
289        let symbols = platform_function_symbols();
290        assert_eq!(symbols.len(), 13);
291        assert_eq!(
292            symbols.iter().map(ToString::to_string).collect::<Vec<_>>(),
293            vec![
294                "platform/card",
295                "platform/require",
296                "platform/mounts",
297                "platform/open",
298                "platform/share",
299                "platform/notify",
300                "platform/clipboard-read",
301                "platform/clipboard-write",
302                "platform/permission-status",
303                "platform/permission-request",
304                "platform/keep-awake",
305                "platform/lifecycle",
306                "platform/activations",
307            ]
308        );
309    }
310
311    #[test]
312    fn dispatch_uses_only_the_current_environment_site() {
313        let outer = Arc::new(RecordingSite(Mutex::new(Vec::new())));
314        let inner = Arc::new(RecordingSite(Mutex::new(Vec::new())));
315        let mut cx = cx_with(outer.clone());
316        let mut child = sim_kernel::Env::child(Arc::new(cx.env().clone()));
317        child.define(
318            Symbol::qualified("platform", ACTIVE_PLATFORM_SITE),
319            cx.factory().opaque(inner.clone()).unwrap(),
320        );
321        cx.with_env(child, |cx| {
322            PlatformFunction(PlatformFunctionKind::Card).call(cx, Args::default())
323        })
324        .unwrap();
325        assert!(outer.0.lock().unwrap().is_empty());
326        assert_eq!(inner.0.lock().unwrap().len(), 1);
327    }
328
329    #[test]
330    fn capability_is_checked_before_provider_permission_dispatch() {
331        let site = Arc::new(RecordingSite(Mutex::new(Vec::new())));
332        let mut cx = cx_with(site.clone());
333        let arg = cx
334            .factory()
335            .symbol(Symbol::qualified("platform", "clipboard-read"))
336            .unwrap();
337        let error = PlatformFunction(PlatformFunctionKind::PermissionRequest)
338            .call(&mut cx, Args::new(vec![arg]))
339            .unwrap_err();
340        assert!(matches!(error, Error::CapabilityDenied { .. }));
341        assert!(site.0.lock().unwrap().is_empty());
342        cx.grant_named("platform.clipboard.read");
343        let arg = cx
344            .factory()
345            .symbol(Symbol::qualified("platform", "clipboard-read"))
346            .unwrap();
347        PlatformFunction(PlatformFunctionKind::PermissionRequest)
348            .call(&mut cx, Args::new(vec![arg]))
349            .unwrap();
350        assert_eq!(site.0.lock().unwrap().len(), 1);
351    }
352}