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