Skip to main content

sim_lib_auto_order/
runtime.rs

1//! Loadable library wiring for modeled work orders.
2
3use std::sync::Arc;
4
5use sim_citizen::registered_citizens;
6use sim_kernel::{
7    AbiVersion, Args, Callable, Cx, Error, Export, Lib, LibManifest, LibTarget, Linker, LoadCx,
8    Object, ObjectCompat, Result, Symbol, Value, Version,
9};
10
11use crate::run_modeled_conformance;
12
13const ORDER_CITIZENS: &[&str] = &[
14    "auto/WorkOrderEvent",
15    "auto/WorkOrderLedger",
16    "auto/LedgerInvoiceEvidence",
17    "auto/LedgerInvoicePosting",
18    "auto/LedgerInvoiceExport",
19    "auto/WorkOrder",
20    "auto/ConformanceReport",
21];
22
23/// Loadable library that contributes modeled work-order exports.
24#[derive(Clone, Copy, Debug, Default)]
25pub struct AutoOrderLib;
26
27impl Lib for AutoOrderLib {
28    fn manifest(&self) -> LibManifest {
29        let mut exports = auto_order_citizen_symbols()
30            .into_iter()
31            .map(|symbol| Export::Class {
32                symbol,
33                class_id: None,
34            })
35            .collect::<Vec<_>>();
36        exports.extend([
37            Export::Function {
38                symbol: auto_order_function_symbol(),
39                function_id: None,
40            },
41            Export::Value {
42                symbol: auto_order_shape_symbol(),
43            },
44        ]);
45        LibManifest {
46            id: Symbol::qualified("auto", "order"),
47            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
48            abi: AbiVersion { major: 0, minor: 1 },
49            target: LibTarget::HostRegistered,
50            requires: Vec::new(),
51            capabilities: Vec::new(),
52            exports,
53        }
54    }
55
56    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
57        install_order_citizens(linker)?;
58        linker.function_value(
59            auto_order_function_symbol(),
60            cx.factory().opaque(Arc::new(AutoWorkOrderFunction))?,
61        )?;
62        linker.value(
63            auto_order_shape_symbol(),
64            cx.factory().string(
65                "auto/work-order: modeled MBTECH work order using diagnostic-read and order parent grants"
66                    .to_owned(),
67            )?,
68        )?;
69        Ok(())
70    }
71}
72
73/// Installs the modeled work-order library into a context once.
74pub fn install_auto_order_lib(cx: &mut Cx) -> Result<()> {
75    if cx
76        .registry()
77        .lib(&Symbol::qualified("auto", "order"))
78        .is_some()
79    {
80        return Ok(());
81    }
82    cx.load_lib(&AutoOrderLib).map(|_| ())
83}
84
85/// Returns the citizen class symbols exported by the work-order library.
86pub fn auto_order_citizen_symbols() -> Vec<Symbol> {
87    ORDER_CITIZENS
88        .iter()
89        .map(|symbol| parse_symbol(symbol))
90        .collect()
91}
92
93/// Symbol for the modeled work-order callable.
94pub fn auto_order_function_symbol() -> Symbol {
95    Symbol::qualified("auto", "work-order")
96}
97
98/// Symbol for the work-order request shape descriptor.
99pub fn auto_order_shape_symbol() -> Symbol {
100    Symbol::qualified("auto", "work-order-shape")
101}
102
103#[derive(Clone)]
104struct AutoWorkOrderFunction;
105
106impl Object for AutoWorkOrderFunction {
107    fn display(&self, _cx: &mut Cx) -> Result<String> {
108        Ok("auto/work-order".to_owned())
109    }
110
111    fn as_any(&self) -> &dyn std::any::Any {
112        self
113    }
114}
115
116impl ObjectCompat for AutoWorkOrderFunction {
117    fn as_callable(&self) -> Option<&dyn Callable> {
118        Some(self)
119    }
120}
121
122impl Callable for AutoWorkOrderFunction {
123    fn call(&self, cx: &mut Cx, args: Args) -> Result<Value> {
124        if !args.values().is_empty() {
125            return Err(Error::Eval(
126                "auto/work-order currently accepts the modeled default story only".to_owned(),
127            ));
128        }
129        let report = run_modeled_conformance(cx)?;
130        cx.factory().expr(report.to_expr())
131    }
132}
133
134fn install_order_citizens(linker: &mut Linker<'_>) -> Result<()> {
135    for expected in ORDER_CITIZENS {
136        let Some(info) = registered_citizens().find(|info| info.symbol == *expected) else {
137            return Err(Error::HostError(format!(
138                "work-order citizen {expected} is not registered"
139            )));
140        };
141        (info.install)(linker)?;
142    }
143    Ok(())
144}
145
146fn parse_symbol(text: &str) -> Symbol {
147    if let Some((namespace, name)) = text.split_once('/') {
148        Symbol::qualified(namespace, name)
149    } else {
150        Symbol::new(text)
151    }
152}