Skip to main content

xur_std/
xur.rs

1//! `std::xur` — information about the runtime environment.
2
3use std::sync::OnceLock;
4
5use xur_runtime::registry::RawSig;
6use xur_runtime::{Registry, RuntimeError, TypeDesc, Value};
7
8static INVOKED_BY: OnceLock<String> = OnceLock::new();
9pub(crate) static ARGV: OnceLock<(Option<Value>, Vec<String>)> = OnceLock::new();
10
11/// Sets how xur was invoked (e.g. "cli", "stub"). Must be called once
12/// before any script runs; later calls are ignored.
13pub fn set_invoked_by(name: &str) {
14    let _ = INVOKED_BY.set(name.to_owned());
15}
16
17/// Sets the program's argument list. `script` is the path to the script
18/// (`None` for stdin); `args` are the trailing arguments.
19///
20/// The script path is stored as `None` internally and wrapped in
21/// `Option` when `std::argv()` is called (which has access to the
22/// runtime's lang items).
23pub fn set_argv(script: Option<String>, args: Vec<String>) {
24    let script_value = script.map(|p| Value::str(&p));
25    let _ = ARGV.set((script_value, args));
26}
27
28pub(crate) fn register(registry: &Registry) {
29    registry.module("std::xur").raw_function_sig(
30        "invoked_by",
31        RawSig::new().returns(TypeDesc::of::<String>()),
32        |_cx, args| {
33            if !args.is_empty() {
34                return Err(RuntimeError::new("`invoked_by` takes no arguments"));
35            }
36            let name = INVOKED_BY.get().map_or("unknown", |s| s.as_str());
37            Ok(Value::str(name))
38        },
39    );
40}