rpc/script.rs
1//! Script compile entry: automation source to the stored bytecode.
2//!
3//! [`compile_script`] is the one script compiler. It compiles in Script mode
4//! against the entity-script surface the trigger runner links, and backs `nms --compile` and the save paths [`create_script`] and
5//! [`update_script_source`]. `rpc` owns the compile-then-store step because
6//! `server` cannot depend on it; the server functions take source and bytecode
7//! together.
8
9use nomiscript::{Compiler, Reader, SymbolTable};
10use server::error::ServerError;
11use server::user::User;
12use thiserror::Error;
13use uuid::Uuid;
14
15#[derive(Debug, Error)]
16pub enum ScriptError {
17 /// The source failed to parse or compile; shown at the `source` field.
18 #[error("script compile error: {0}")]
19 Compile(String),
20 #[error(transparent)]
21 Server(#[from] ServerError),
22}
23
24/// Compiles `source` as an automation script, returning the wasm bytes.
25///
26/// No rpc host natives are registered: the compiler declares every registered
27/// native as a wasm import, and the trigger runner links none of them, so a
28/// module built with them would not load.
29///
30/// # Errors
31/// [`ScriptError::Compile`] with the reader or compiler message, which carries
32/// the source position where the compiler gives one.
33pub fn compile_script(source: &str) -> Result<Vec<u8>, ScriptError> {
34 if source.trim().is_empty() {
35 return Err(ScriptError::Compile(
36 "the script source is empty".to_string(),
37 ));
38 }
39 let mut symbols = SymbolTable::with_builtins();
40 let program = Reader::parse(source).map_err(|err| ScriptError::Compile(err.to_string()))?;
41 Compiler::new()
42 .compile(&program, &mut symbols)
43 .map_err(|err| ScriptError::Compile(err.to_string()))
44}
45
46/// Compiles `source` and stores it with its bytecode as a new script.
47///
48/// # Errors
49/// A compile failure stores nothing; otherwise the server failure.
50pub async fn create_script(
51 user: &User,
52 source: String,
53 name: Option<String>,
54) -> Result<Uuid, ScriptError> {
55 let bytecode = compile_script(&source)?;
56 Ok(user
57 .create_script_from_source(source, bytecode, name, true)
58 .await?)
59}
60
61/// Recompiles `source` and replaces the script's source and bytecode together.
62///
63/// # Errors
64/// A compile failure leaves the script as it was; otherwise the server failure.
65pub async fn update_script_source(
66 user: &User,
67 id: Uuid,
68 source: String,
69) -> Result<(), ScriptError> {
70 let bytecode = compile_script(&source)?;
71 Ok(user.update_script_source(id, source, bytecode).await?)
72}