Skip to main content

sim_auto/
entrypoint.rs

1//! Loadable library and Bootloader wiring for the auto command.
2
3use std::{ffi::OsString, io::Write, sync::Arc};
4
5use sim_kernel::{
6    AbiVersion, Args, Callable, CodecId, Cx, Error, Export, Expr, Lib, LibManifest, LibTarget,
7    Linker, LoadCx, Object, ObjectCompat, Result, Symbol, Value, Version,
8};
9use sim_run_core::{Bootloader, cli_main_entrypoint_symbol};
10
11use crate::render_auto_command;
12
13/// Bootloader verb served by this package.
14pub const AUTO_VERB: &str = "auto";
15
16/// Host library id registered for the auto verb.
17pub const AUTO_HOST_LIB: &str = "lib/auto";
18
19/// Returns the function symbol exported for the bootloader handoff.
20pub fn auto_entrypoint_symbol() -> Symbol {
21    cli_main_entrypoint_symbol(AUTO_VERB)
22}
23
24/// Builds the Bootloader used by the `sim-auto` binary.
25pub fn auto_bootloader() -> Bootloader {
26    Bootloader::standard()
27        .host_lib("codec/lisp", lisp_boot_codec)
28        .host_verb(AUTO_VERB, AUTO_HOST_LIB, || Box::new(AutoCliLib::new()))
29}
30
31/// Normalizes process args so `sim-auto diag` boots the same `auto` verb.
32pub fn auto_boot_args<I, S>(args: I) -> Vec<OsString>
33where
34    I: IntoIterator<Item = S>,
35    S: Into<OsString>,
36{
37    let mut args = args.into_iter().map(Into::into).collect::<Vec<_>>();
38    match args.get(1).and_then(|arg| arg.to_str()) {
39        Some(AUTO_VERB) => args,
40        Some("--help" | "-h") | None => {
41            args.insert(1, OsString::from(AUTO_VERB));
42            args
43        }
44        Some(_) => {
45            args.insert(1, OsString::from(AUTO_VERB));
46            args
47        }
48    }
49}
50
51fn lisp_boot_codec() -> Box<dyn Lib> {
52    Box::new(sim_codec_lisp::LispCodecLib::new(CodecId(1)).expect("lisp boot codec"))
53}
54
55/// Loadable automotive command library.
56#[derive(Clone, Debug, Default)]
57pub struct AutoCliLib;
58
59impl AutoCliLib {
60    /// Creates an auto command library instance.
61    pub fn new() -> Self {
62        Self
63    }
64}
65
66impl Lib for AutoCliLib {
67    fn manifest(&self) -> LibManifest {
68        LibManifest {
69            id: Symbol::qualified("lib", "auto"),
70            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
71            abi: AbiVersion { major: 0, minor: 1 },
72            target: LibTarget::HostRegistered,
73            requires: Vec::new(),
74            capabilities: Vec::new(),
75            exports: vec![Export::Function {
76                symbol: auto_entrypoint_symbol(),
77                function_id: None,
78            }],
79        }
80    }
81
82    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
83        let entrypoint = cx.factory().opaque(Arc::new(AutoCliEntrypoint))?;
84        linker.function_value(auto_entrypoint_symbol(), entrypoint)?;
85        Ok(())
86    }
87}
88
89#[derive(Clone)]
90struct AutoCliEntrypoint;
91
92impl Object for AutoCliEntrypoint {
93    fn display(&self, _cx: &mut Cx) -> Result<String> {
94        Ok("cli/main/auto".to_owned())
95    }
96
97    fn as_any(&self) -> &dyn std::any::Any {
98        self
99    }
100}
101
102impl ObjectCompat for AutoCliEntrypoint {
103    fn as_callable(&self) -> Option<&dyn Callable> {
104        Some(self)
105    }
106}
107
108impl Callable for AutoCliEntrypoint {
109    fn call(&self, cx: &mut Cx, args: Args) -> Result<Value> {
110        let envelope = match args.values().first() {
111            Some(envelope) => AutoEnvelope::from_value(cx, envelope)?,
112            None => AutoEnvelope::default(),
113        };
114        let output = render_auto_command(&envelope.args)?;
115        writeln!(std::io::stdout(), "{output}")
116            .map_err(|err| Error::Eval(format!("write stdout: {err}")))?;
117        cx.factory().bool(true)
118    }
119}
120
121#[derive(Clone, Debug, Default, PartialEq, Eq)]
122struct AutoEnvelope {
123    args: Vec<String>,
124}
125
126impl AutoEnvelope {
127    fn from_value(cx: &mut Cx, envelope: &Value) -> Result<Self> {
128        Ok(Self {
129            args: envelope_args(cx, envelope)?,
130        })
131    }
132}
133
134fn envelope_args(cx: &mut Cx, envelope: &Value) -> Result<Vec<String>> {
135    let Some(table) = envelope.object().as_table_impl() else {
136        return Err(Error::Eval("CLI envelope is not a table".to_owned()));
137    };
138    let value = table.get(cx, Symbol::new("args"))?;
139    let Expr::List(items) = value.object().as_expr(cx)? else {
140        return Err(Error::TypeMismatch {
141            expected: "argument list",
142            found: "non-list",
143        });
144    };
145    items
146        .into_iter()
147        .map(|item| match item {
148            Expr::String(value) => Ok(value),
149            other => Err(Error::TypeMismatch {
150                expected: "string argument",
151                found: sim_value::kind::expr_kind(&other),
152            }),
153        })
154        .collect()
155}