Skip to content

Commit

Permalink
Initial stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
WilliamRagstad committed Oct 16, 2023
1 parent 6606b4e commit 8ec16e6
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/engine/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod runtime;
mod test;
mod http;
mod http;
mod stdlib;
4 changes: 3 additions & 1 deletion src/engine/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
use super::{http::{
parse_request_tcp, serialize_response,
Responses::{self, ok_html},
};
}, stdlib};

/// A runtime error.
pub struct WXRuntimeError {
Expand Down Expand Up @@ -165,6 +165,8 @@ impl WXRTHandlerCall {
/// Execute the handler in the given context and return the result.
fn execute(&self, ctx: &WXRTContext, info: &WXRuntimeInfo) -> Result<WXRTValue, WXRuntimeError> {
let args = self.args.iter().map(|arg| eval_literal(arg, &ctx)).collect::<Result<Vec<_>, _>>()?;
// Try to call a native handler.
if let Some(native_res) = stdlib::try_call(&self.name, args, info) { return native_res; }
// TODO: Add support for custom user-defined handlers
Err(WXRuntimeError {
code: 500,
Expand Down
43 changes: 43 additions & 0 deletions src/engine/stdlib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use crate::reporting::error::ERROR_HANDLER_CALL;

use super::runtime::{WXRTValue, WXRuntimeError, WXRuntimeInfo};

/// Serve static content from the filesystem.
///
/// # Arguments
/// - `path`: The path to the file to serve relative to the project root.
fn webx_static(relative_path: &WXRTValue, info: &WXRuntimeInfo) -> Result<WXRTValue, WXRuntimeError> {
// Read the file from the filesystem.
if let WXRTValue::String(path) = relative_path {
let file = std::fs::read(info.project_root.join(path));
if let Ok(file) = file {
return Ok(WXRTValue::String(String::from_utf8(file).unwrap()));
} else {
return Err(WXRuntimeError {
message: format!("static: failed to read file '{}'", path),
code: ERROR_HANDLER_CALL
});
}
}
Err(WXRuntimeError {
message: format!("static: failed to read file '{}'", relative_path.to_js()),
code: ERROR_HANDLER_CALL
})
}

pub fn try_call(name: &str, args: Vec<WXRTValue>, info: &WXRuntimeInfo) -> Option<Result<WXRTValue, WXRuntimeError>> {
let assert_args = |n: usize| {
if args.len() != n {
return Some(Err::<WXRTValue, WXRuntimeError>(WXRuntimeError {
message: format!("{}: expected {} arguments, got {}", name, n, args.len()),
code: ERROR_HANDLER_CALL
}));
}
None
};

match name {
"static" => Some(match assert_args(1) { Some(err) => err, None => webx_static(&args[0], info) }),
_ => None
}
}

0 comments on commit 8ec16e6

Please sign in to comment.