#![cfg(not(feature = "no_std"))]
#![cfg(any(not(target_family = "wasm"), not(target_os = "unknown")))]
use crate::types::dynamic::Variant;
use crate::{Engine, RhaiResultOf, Scope, AST, ERR};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
fs::File,
io::Read,
path::{Path, PathBuf},
};
impl Engine {
fn read_file(path: impl AsRef<Path>) -> RhaiResultOf<String> {
let path = path.as_ref();
let mut f = File::open(path).map_err(|err| {
ERR::ErrorSystem(
format!("Cannot open script file '{}'", path.to_string_lossy()),
err.into(),
)
})?;
let mut contents = String::new();
f.read_to_string(&mut contents).map_err(|err| {
ERR::ErrorSystem(
format!("Cannot read script file '{}'", path.to_string_lossy()),
err.into(),
)
})?;
if contents.starts_with("#!") {
match contents.find('\n') {
Some(n) => {
contents.drain(0..n).count();
}
None => contents.clear(),
}
}
Ok(contents)
}
#[inline(always)]
pub fn compile_file(&self, path: PathBuf) -> RhaiResultOf<AST> {
self.compile_file_with_scope(&Scope::new(), path)
}
#[inline]
pub fn compile_file_with_scope(&self, scope: &Scope, path: PathBuf) -> RhaiResultOf<AST> {
Self::read_file(&path).and_then(|contents| {
let mut ast = self.compile_with_scope(scope, contents)?;
ast.set_source(path.to_string_lossy().as_ref());
Ok(ast)
})
}
#[inline]
pub fn eval_file<T: Variant + Clone>(&self, path: PathBuf) -> RhaiResultOf<T> {
Self::read_file(path).and_then(|contents| self.eval::<T>(&contents))
}
#[inline]
pub fn eval_file_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope,
path: PathBuf,
) -> RhaiResultOf<T> {
Self::read_file(path).and_then(|contents| self.eval_with_scope(scope, &contents))
}
#[inline]
pub fn run_file(&self, path: PathBuf) -> RhaiResultOf<()> {
Self::read_file(path).and_then(|contents| self.run(&contents))
}
#[inline]
pub fn run_file_with_scope(&self, scope: &mut Scope, path: PathBuf) -> RhaiResultOf<()> {
Self::read_file(path).and_then(|contents| self.run_with_scope(scope, &contents))
}
}
#[inline]
pub fn eval_file<T: Variant + Clone>(path: impl AsRef<Path>) -> RhaiResultOf<T> {
Engine::read_file(path).and_then(|contents| Engine::new().eval::<T>(&contents))
}
#[inline]
pub fn run_file(path: impl AsRef<Path>) -> RhaiResultOf<()> {
Engine::read_file(path).and_then(|contents| Engine::new().run(&contents))
}