Skip to main content

ruso_script/
lib.rs

1//! Parse Ruso Scripting Language (RSL) source into an AST and compile to
2//! `ruso-runtime` bytecode.
3//!
4//! # Developer documentation
5//!
6//! - [Language reference](https://docs.ruso.hopeless-labs.com/rsl/reference.html)
7//! - [Compiler](https://docs.ruso.hopeless-labs.com/internals/compiler.html)
8//! - [Examples](https://docs.ruso.hopeless-labs.com/rsl/examples.html)
9
10// `ParseError::Pest` wraps `pest::error::Error`, which carries spans + rule
11// chain for useful diagnostics and is naturally large. Boxing it would obscure
12// the public error type at call sites; the size lint is noise here.
13#![allow(clippy::result_large_err)]
14// Every public item carries rustdoc: the book's /api section is generated from
15// it, so a missing doc comment is a gap in user-facing documentation. CI builds
16// with `-D warnings`, which turns this into a hard failure.
17#![warn(missing_docs)]
18
19mod compile;
20pub mod script;
21mod spec_build;
22
23pub use compile::{CompileError, compile};
24pub use ruso_runtime::{
25    BytecodeProgram, EvidenceKind, ExtractSource, QualifiedMatch, Severity, encode_bytecode,
26};
27pub use script::ast::{self, Program, Stmt};
28pub use script::{ParseError, parse};
29
30use std::path::Path;
31
32/// Error from [`load_program`]: reading the file failed, or its contents did
33/// not parse.
34#[derive(Debug, thiserror::Error)]
35pub enum LoadError {
36    /// The source file could not be read.
37    #[error("failed to read {}: {source}", path.display())]
38    Io {
39        /// The path that failed to read.
40        path: std::path::PathBuf,
41        /// The underlying I/O error.
42        source: std::io::Error,
43    },
44    /// The source file was read but did not parse as RSL.
45    #[error("failed to parse {}: {source}", path.display())]
46    Parse {
47        /// The path that failed to parse.
48        path: std::path::PathBuf,
49        /// The underlying parse error.
50        source: ParseError,
51    },
52}
53
54/// Read and parse an `.rsl` file into a [`Program`] AST.
55pub fn load_program(path: &Path) -> Result<Program, LoadError> {
56    let source = std::fs::read_to_string(path).map_err(|err| LoadError::Io {
57        path: path.to_path_buf(),
58        source: err,
59    })?;
60    parse(&source).map_err(|err| LoadError::Parse {
61        path: path.to_path_buf(),
62        source: err,
63    })
64}
65
66/// Compile a parsed [`Program`] into a [`BytecodeProgram`].
67pub fn compile_program(program: &Program) -> Result<BytecodeProgram, CompileError> {
68    compile(program)
69}
70
71/// Compile a [`Program`] and serialize it to a raw `.rbc` byte buffer.
72pub fn compile_to_bytes(program: &Program) -> Result<Vec<u8>, CompileError> {
73    Ok(encode_bytecode(&compile_program(program)?))
74}
75
76/// Compile a [`Program`] and run it against a single target in one step.
77pub async fn run(
78    program: &Program,
79    config: ruso_runtime::ExecutorConfig,
80) -> Result<ruso_runtime::ExecutionResult, ruso_runtime::RuntimeError> {
81    let bytecode =
82        compile_program(program).map_err(|e| ruso_runtime::RuntimeError::Other(e.to_string()))?;
83    ruso_runtime::Executor::from_bytecode(config, bytecode)?
84        .run()
85        .await
86}
87
88/// Run an already-compiled [`BytecodeProgram`] against a single target.
89pub async fn run_bytecode(
90    bytecode: &BytecodeProgram,
91    config: ruso_runtime::ExecutorConfig,
92) -> Result<ruso_runtime::ExecutionResult, ruso_runtime::RuntimeError> {
93    ruso_runtime::Executor::from_bytecode(config, bytecode.clone())?
94        .run()
95        .await
96}
97
98/// Run a pre-shared `Arc<BytecodeProgram>` against a single target.
99///
100/// Prefer this over [`run_bytecode`] when running the same compiled script
101/// against many targets — the program is cloned via `Arc::clone` (a
102/// reference-count bump) instead of being deep-copied for each run.
103pub async fn run_program(
104    bytecode: std::sync::Arc<BytecodeProgram>,
105    config: ruso_runtime::ExecutorConfig,
106) -> Result<ruso_runtime::ExecutionResult, ruso_runtime::RuntimeError> {
107    ruso_runtime::Executor::from_program(config, bytecode)?
108        .run()
109        .await
110}
111
112/// Decode a raw `.rbc` byte buffer and run it against a single target.
113pub async fn run_bytes(
114    bytes: &[u8],
115    config: ruso_runtime::ExecutorConfig,
116) -> Result<ruso_runtime::ExecutionResult, ruso_runtime::RuntimeError> {
117    ruso_runtime::Executor::from_bytes(config, bytes)?
118        .run()
119        .await
120}
121
122#[cfg(test)]
123mod tests {
124    use std::path::PathBuf;
125
126    use ruso_runtime::{bytes_to_hex, decode_bytecode, hex_to_bytes};
127
128    use super::*;
129    use crate::script::ast::Stmt;
130
131    #[test]
132    fn load_program_valid_example() {
133        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/http_status_ok.rsl");
134        let program = load_program(&path).expect("example script should parse");
135        assert!(!program.statements.is_empty());
136    }
137
138    #[test]
139    fn bytecode_roundtrip_http_example() {
140        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/http_status_ok.rsl");
141        let program = load_program(&path).unwrap();
142        let original = compile_program(&program).unwrap();
143        let bytes = encode_bytecode(&original);
144        let restored = decode_bytecode(&bytes).unwrap();
145        assert_eq!(original.code, restored.code);
146        assert_eq!(original.strings, restored.strings);
147        assert_eq!(original.matchers, restored.matchers);
148    }
149
150    #[test]
151    fn hex_bytes_roundtrip() {
152        let program = Program {
153            statements: vec![Stmt::Name("Hex test".into()), Stmt::Severity(Severity::Low)],
154        };
155        let bytes = compile_to_bytes(&program).unwrap();
156        let hex = bytes_to_hex(&bytes);
157        let restored = hex_to_bytes(&hex).expect("hex decode");
158        let decoded = decode_bytecode(&restored).expect("bytecode decode");
159        assert_eq!(decoded.spec.metadata.name.as_deref(), Some("Hex test"));
160    }
161}