use crate::machine::{Deferred, Expr, Program};
use crate::refusal::{CompileReason, Reason, Refusal};
use crate::xml::Location;
use predicator_rs::{Context, OnUnbound, Options, Value};
pub(super) fn compile(source: &str, location: Location) -> Result<Expr, Refusal> {
match predicator_rs::compile(source) {
Ok(instructions) => Ok(Expr::Compiled {
instructions,
source: source.to_owned(),
}),
Err(error) => Err(refusal(source, &error, location)),
}
}
pub(super) fn deferred(source: &str, location: Location) -> Deferred<Expr> {
match compile(source, location) {
Ok(expr) => Deferred::Ready(expr),
Err(refusal) => Deferred::Invalid(Box::new(refusal)),
}
}
pub(super) fn program(source: &str, location: Location) -> Deferred<Program> {
match predicator_rs::compile_program(source) {
Ok(instructions) => Deferred::Ready(Program {
instructions,
source: source.to_owned(),
}),
Err(error) => Deferred::Invalid(Box::new(refusal(source, &error, location))),
}
}
pub(super) fn literal(value: impl Into<Value>) -> Expr {
Expr::Static(value.into())
}
pub(super) fn inline_value(text: &str) -> Expr {
let trimmed = text.trim();
let options = Options::new().on_unbound(OnUnbound::Error);
match predicator_rs::compile(trimmed)
.and_then(|instructions| predicator_rs::evaluate(&instructions, &Context::new(), &options))
{
Ok(value) => Expr::Static(value),
Err(_) => literal(trimmed),
}
}
fn refusal(source: &str, error: &predicator_rs::Error, location: Location) -> Refusal {
let position = error
.position()
.map(|position| (position.line, position.column));
let at = position.map_or_else(String::new, |(line, column)| {
format!(" (predicator line {line}, column {column})")
});
Refusal::new(
Reason::Compile(CompileReason::ExpressionCompileError {
source: source.to_owned(),
cause: error.reason().to_owned(),
position,
}),
format!(
"failed to compile expression {source:?}: {}{at}",
error.message()
),
location,
)
}