use anyhow::{Result, bail};
use oxdock_fs::EntryKind;
use oxdock_fs::env as oxdock_env;
use oxdock_fs::to_forward_slashes;
use oxdock_parser::{Arg, ArgPart, ArithOp, CompareOp, Expr, LogicalOp, MathOp, TypeTag, Value};
use oxdock_pipe::{SharedInput, SharedOutput, SpillBuffer};
use oxdock_process::{ProcessManager, format_value_for_string};
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use super::state::ExecState;
use super::steps::StepCtx;
pub(crate) fn type_mismatch(ctx: &str, expected: &TypeTag, value: &Value) -> anyhow::Error {
anyhow::anyhow!(
"{ctx}: TypeMismatch: expected {}, got {}",
oxdock_parser::render_structural(expected),
value.type_name()
)
}
pub(crate) fn parse_bool_str(s: &str) -> Option<bool> {
let t = s.trim();
if t.is_empty() {
return None;
}
if t.eq_ignore_ascii_case("true")
|| t.eq_ignore_ascii_case("yes")
|| t.eq_ignore_ascii_case("on")
|| t == "1"
{
Some(true)
} else if t.eq_ignore_ascii_case("false")
|| t.eq_ignore_ascii_case("no")
|| t.eq_ignore_ascii_case("off")
|| t == "0"
{
Some(false)
} else {
None
}
}
pub(crate) fn check_host_return_value(
ctx: &str,
returns: &Option<TypeTag>,
value: &Value,
) -> Result<()> {
let Some(slot) = returns else {
return Ok(());
};
let filled = fill_record_defaults(slot, value);
oxdock_parser::check_value_at(slot, &filled, ctx)
}
pub(crate) fn string_or_path_text(value: &Value) -> Result<String> {
if let Some(s) = value.as_str() {
return Ok(s.to_string());
}
if let Some(p) = value.as_path() {
return Ok(p.to_string_lossy().to_string());
}
Err(type_mismatch(
"string-or-path position",
&oxdock_parser::union_tag!(String, Path),
value,
))
}
fn fill_record_defaults(expected: &TypeTag, value: &Value) -> Value {
fill_record(expected, value).unwrap_or_else(|| value.clone())
}
fn fill_record(expected: &TypeTag, value: &Value) -> Option<Value> {
match expected {
TypeTag::Record(fields) => {
let map = value.as_map()?;
let mut out: Option<BTreeMap<String, Value>> = None;
for field in fields.iter() {
match map.get(field.name.as_str()) {
Some(item) => {
if let Some(filled) = fill_record(&field.ty, item) {
out.get_or_insert_with(|| map.clone())
.insert(field.name.clone(), filled);
}
}
None => {
if let Some(default) = field.default.as_ref() {
out.get_or_insert_with(|| map.clone())
.insert(field.name.clone(), default.clone());
}
}
}
}
out.map(Value::map)
}
TypeTag::ListOf(inner) => {
let items = value.as_list()?;
let mut out: Option<Vec<Value>> = None;
for (idx, item) in items.iter().enumerate() {
if let Some(filled) = fill_record(inner, item) {
out.get_or_insert_with(|| items.clone())[idx] = filled;
}
}
out.map(Value::list)
}
TypeTag::MapOf(inner) => {
let map = value.as_map()?;
let mut out: Option<BTreeMap<String, Value>> = None;
for (key, item) in map.iter() {
if let Some(filled) = fill_record(inner, item) {
out.get_or_insert_with(|| map.clone())
.insert(key.clone(), filled);
}
}
out.map(Value::map)
}
TypeTag::Union(_, members) => {
for member in members.iter() {
let filled = fill_record(member, value).unwrap_or_else(|| value.clone());
if oxdock_parser::check_value(member, &filled).is_ok() {
return (filled != *value).then_some(filled);
}
}
None
}
_ => None,
}
}
pub(crate) fn coerce_value(value: Value, expected: &TypeTag) -> Result<Value> {
if matches!(expected, TypeTag::Any) {
return Ok(value);
}
let value = fill_record_defaults(expected, &value);
if let Err(err) = oxdock_parser::check_value(expected, &value) {
if matches!(expected, TypeTag::ListOf(_) | TypeTag::Record(_)) {
return Err(err);
}
} else {
return Ok(value);
}
if let TypeTag::Union(_, members) = expected {
for member in members.iter() {
if let Ok(coerced) = coerce_value(value.clone(), member) {
return Ok(coerced);
}
}
}
if let Some(s) = value.as_str() {
let name = expected.name();
return match expected {
TypeTag::Bool => match parse_bool_str(s) {
Some(b) => Ok(Value::bool(b)),
None => Err(type_mismatch("coercion", expected, &value)),
},
TypeTag::Pipe => {
Err(anyhow::anyhow!(
"TypeMismatch: expected {name}, got STRING ({s:?}); declare LET $x: PIPE and pass $x"
))
}
TypeTag::Duration => oxdock_parser::command::parse_duration(s.trim())
.map(Value::duration)
.map_err(|_| type_mismatch("coercion", expected, &value)),
TypeTag::Path => {
#[allow(clippy::disallowed_types)]
let path = std::path::PathBuf::from(s.trim());
Ok(Value::path(path))
}
TypeTag::String
| TypeTag::Int
| TypeTag::Float
| TypeTag::List
| TypeTag::Map
| TypeTag::Handle
| TypeTag::HandleOf(_)
| TypeTag::Void
| TypeTag::Semaphore
| TypeTag::Permit
| TypeTag::Any
| TypeTag::Custom(_)
| TypeTag::ListOf(_)
| TypeTag::Record(_)
| TypeTag::MapOf(_)
| TypeTag::Union(..) => Err(type_mismatch("coercion", expected, &value)),
};
}
coerce_scalar(&value, expected)
}
fn coerce_scalar(value: &Value, expected: &TypeTag) -> Result<Value> {
if let Some(n) = value.as_i64() {
if matches!(expected, TypeTag::String) {
return Ok(Value::string(n.to_string()));
}
if matches!(expected, TypeTag::Float) {
return Ok(Value::float(n as f64));
}
if matches!(expected, TypeTag::Bool) {
match n {
1 => return Ok(Value::bool(true)),
0 => return Ok(Value::bool(false)),
_ => return Err(mismatch(expected, value)),
}
}
return Err(mismatch(expected, value));
}
if let Some(f) = value.as_f64() {
if matches!(expected, TypeTag::String) {
return Ok(Value::string(f.to_string()));
}
return Err(mismatch(expected, value));
}
if let Some(b) = value.as_bool() {
if matches!(expected, TypeTag::String) {
return Ok(Value::string(b.to_string()));
}
return Err(mismatch(expected, value));
}
if let Some(d) = value.as_duration() {
if matches!(expected, TypeTag::String) {
return Ok(Value::string(oxdock_parser::command::format_duration(&d)));
}
return Err(mismatch(expected, value));
}
if let Some(p) = value.as_path() {
if matches!(expected, TypeTag::String) {
return Ok(Value::string(p.to_string_lossy().to_string()));
}
return Err(mismatch(expected, value));
}
if value.as_pipe_handle().is_some() {
if matches!(expected, TypeTag::String) {
anyhow::bail!(
"coercion: TypeMismatch: expected STRING, got PIPE: pipes carry streams between steps, not text. Capture the producing step's output with LET $var: STRING = ... instead."
);
}
return Err(mismatch(expected, value));
}
Err(mismatch(expected, value))
}
fn mismatch(expected: &TypeTag, value: &Value) -> anyhow::Error {
type_mismatch("coercion", expected, value)
}
pub(crate) fn resolve_arg_state<P: ProcessManager>(
arg: &Arg,
state: &ExecState<P>,
) -> Result<String> {
match arg {
Arg::String(s, _) => Ok(expand_string(s, &state.envs, state)?),
Arg::Expr(e) => bail!("Arg::Expr cannot be resolved without StepCtx: {:?}", e),
Arg::Parts(parts) => {
let mut out = String::new();
for part in parts {
match part {
ArgPart::Text(s, _) => {
out.push_str(&expand_string(s, &state.envs, state)?);
}
ArgPart::Expr(e) => {
bail!("Arg::Expr cannot be resolved without StepCtx: {:?}", e)
}
}
}
Ok(out)
}
}
}
pub(crate) fn resolve_arg<P: ProcessManager>(arg: &Arg, cx: &mut StepCtx<'_, P>) -> Result<String> {
match arg {
Arg::String(s, _) => Ok(expand_string(s, &cx.state.envs, cx.state)?),
Arg::Expr(e) => {
let val = evaluate_expr(e, cx)?;
format_value_for_string(&val)
}
Arg::Parts(parts) => {
let mut out = String::new();
for part in parts {
match part {
ArgPart::Text(s, _) => {
out.push_str(&expand_string(s, &cx.state.envs, cx.state)?);
}
ArgPart::Expr(e) => {
let val = evaluate_expr(e, cx)?;
out.push_str(&format_value_for_string(&val)?);
}
}
}
Ok(out)
}
}
}
pub(crate) fn resolve_arg_opt<P: ProcessManager>(
arg: &Option<Arg>,
cx: &mut StepCtx<'_, P>,
) -> Result<Option<String>> {
match arg {
Some(a) => resolve_arg(a, cx).map(Some),
None => Ok(None),
}
}
pub(crate) fn evaluate_assert_operand<P: ProcessManager>(
arg: &Arg,
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
match arg {
Arg::Expr(expr) => evaluate_expr(expr, cx),
_ => Ok(Value::string(resolve_arg(arg, cx)?)),
}
}
pub(crate) fn resolve_overrides<P: ProcessManager>(
overrides: &[(String, Arg)],
cx: &mut StepCtx<'_, P>,
) -> Result<Vec<(String, String)>> {
overrides
.iter()
.map(|(k, v)| resolve_arg(v, cx).map(|val| (k.clone(), val)))
.collect()
}
pub(crate) fn resolve_arg_as_int<P: ProcessManager>(
arg: &Arg,
cx: &mut StepCtx<'_, P>,
) -> Result<i64> {
let resolved = resolve_arg(arg, cx)?;
oxdock_parser::command::strip_digit_separators(&resolved)
.parse::<i64>()
.map_err(|_| anyhow::anyhow!("expected int, got {resolved:?}"))
}
pub(crate) fn resolve_arg_as_duration<P: ProcessManager>(
arg: &Arg,
cx: &mut StepCtx<'_, P>,
) -> Result<std::time::Duration> {
let resolved = resolve_arg(arg, cx)?;
oxdock_parser::command::parse_duration(&resolved)
}
pub(crate) fn load_var_binding<P: ProcessManager>(
state: &ExecState<P>,
name: &str,
) -> Result<Value> {
state
.get_var(name)
.ok_or_else(|| anyhow::anyhow!("undefined variable ${name}"))
}
pub(crate) fn evaluate_expr<P: ProcessManager>(
expr: &Expr,
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
match expr {
Expr::Literal(v) => {
if let Some(s) = v.as_str() {
return Ok(Value::string(expand_string(s, &cx.state.envs, cx.state)?));
}
Ok(v.clone())
}
Expr::Var { name } => load_var_binding(cx.state, name),
Expr::ConstRef { alias, name } => super::import::resolve_const_ref(cx.state, alias, name),
Expr::Env(key) => match cx.state.get_env(key) {
Some(v) => Ok(Value::string(v.to_string())),
None => Ok(Value::string(String::new())),
},
Expr::KeyPath { base, keys } => {
let base_value = load_var_binding(cx.state, base)?;
descend_value(base_value, keys)
}
Expr::List(items) => {
let mut result = Vec::new();
for item in items {
result.push(evaluate_expr(item, cx)?);
}
Ok(Value::list(result))
}
Expr::Map(entries) => {
let mut result = std::collections::BTreeMap::new();
for (key, val_expr) in entries {
let val = evaluate_expr(val_expr, cx)?;
result.insert(key.clone(), val);
}
Ok(Value::map(result))
}
Expr::Block(body) => super::handlers::block_value(cx, body),
Expr::Call { name, args } => super::handlers::call_func_value(cx, name, args),
Expr::Inspect { name } => {
let _ = load_var_binding(cx.state, name)?;
evaluate_inspect_var(name, cx)
}
Expr::FreshPipe => Ok(Value::pipe_fresh_in_task(cx.state.task_id)),
Expr::Arithmetic { op, left, right } => {
let left_val = evaluate_expr(left, cx)?;
let right_val = evaluate_expr(right, cx)?;
apply_arith(*op, left_val, right_val)
}
Expr::CompiledMath(ops) => evaluate_compiled_math(ops, cx),
Expr::UnsignedIntBoundary(n) => {
bail!("internal error: unstaged integer boundary {n}")
}
Expr::Compare { op, left, right } => {
let lv = evaluate_expr(left, cx)?;
let rv = evaluate_expr(right, cx)?;
apply_compare(*op, &lv, &rv)
}
Expr::Logical { op, left, right } => {
let left_val = evaluate_expr(left, cx)?;
let left_truthy = is_truthy(&left_val)?;
match op {
LogicalOp::Or => {
if left_truthy {
Ok(Value::bool(true))
} else {
Ok(Value::bool(is_truthy(&evaluate_expr(right, cx)?)?))
}
}
LogicalOp::And => {
if !left_truthy {
Ok(Value::bool(false))
} else {
Ok(Value::bool(is_truthy(&evaluate_expr(right, cx)?)?))
}
}
}
}
Expr::Not(inner) => Ok(Value::bool(!is_truthy(&evaluate_expr(inner, cx)?)?)),
}
}
pub(crate) fn is_truthy(val: &Value) -> Result<bool> {
match val.as_bool() {
Some(b) => Ok(b),
None => bail!("Type Error: condition must be a Bool, found {:?}", val),
}
}
fn evaluate_inspect_var<P: ProcessManager>(var: &str, cx: &mut StepCtx<'_, P>) -> Result<Value> {
super::handlers::inspect_var_map(cx, var).map(Value::map)
}
pub(crate) fn path_type_from_value<P: ProcessManager>(
args: &[Value],
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
let path_val = args
.first()
.ok_or_else(|| anyhow::anyhow!("PATH_TYPE requires a path argument"))?;
let path_str = match path_val.as_str() {
Some(s) => s.to_string(),
None => bail!("PATH_TYPE path argument must evaluate to a string"),
};
let target = cx
.state
.fs
.resolve_write(&cx.state.cwd, &path_str)
.map_err(|e| anyhow::anyhow!("failed to resolve path '{}': {}", path_str, e))?;
let kind = match cx.state.fs.entry_kind_no_follow(&target) {
Ok(EntryKind::Symlink) => "symlink",
Ok(EntryKind::File) => "file",
Ok(EntryKind::Dir) => "dir",
Err(_) => "absent",
};
Ok(Value::string(kind.to_string()))
}
fn path_entry_kind<P: ProcessManager>(cx: &StepCtx<'_, P>, path: &str) -> Option<EntryKind> {
let target = cx.state.fs.resolve_write(&cx.state.cwd, path).ok()?;
cx.state.fs.entry_kind_no_follow(&target).ok()
}
pub(crate) fn path_is_file<P: ProcessManager>(cx: &StepCtx<'_, P>, path: &str) -> bool {
matches!(path_entry_kind(cx, path), Some(EntryKind::File))
}
pub(crate) fn path_is_dir<P: ProcessManager>(cx: &StepCtx<'_, P>, path: &str) -> bool {
matches!(path_entry_kind(cx, path), Some(EntryKind::Dir))
}
pub(crate) fn path_exists<P: ProcessManager>(cx: &StepCtx<'_, P>, path: &str) -> bool {
path_entry_kind(cx, path).is_some()
}
pub(crate) fn is_exec_from_value<P: ProcessManager>(
args: &[Value],
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
let name_val = args
.first()
.ok_or_else(|| anyhow::anyhow!("IS_EXEC requires a name argument"))?;
let name = match name_val.as_str() {
Some(s) => s.to_string(),
None => bail!("IS_EXEC name argument must evaluate to a string"),
};
if name.is_empty() {
return Ok(Value::bool(false));
}
Ok(Value::bool(is_exec_name(cx, &name)))
}
fn is_exec_name<P: ProcessManager>(cx: &StepCtx<'_, P>, name: &str) -> bool {
let exts = platform_exts(cx);
if name.contains('/') || name.contains('\\') {
return exe_candidates(name, &exts)
.iter()
.any(|candidate| is_executable_candidate(cx, candidate, &exts));
}
let path_var = cx.state.get_env(oxdock_env::os::PATH).unwrap_or_default();
for dir in std::env::split_paths(&path_var) {
let dir = dir.to_string_lossy();
let base = dir.trim_end_matches(['/', '\\']);
if base.is_empty() {
continue;
}
for candidate in exe_candidates(name, &exts) {
if is_executable_candidate(cx, &format!("{base}/{candidate}"), &exts) {
return true;
}
}
}
false
}
#[cfg(windows)]
pub(crate) fn parse_pathext(raw: Option<&str>) -> Vec<String> {
let mut exts = Vec::new();
for piece in raw.unwrap_or_default().split(';') {
let stem = piece.trim().trim_start_matches('.');
if stem.is_empty() {
continue;
}
let dotted = format!(".{stem}");
if !exts
.iter()
.any(|seen: &String| seen.eq_ignore_ascii_case(&dotted))
{
exts.push(dotted);
}
}
exts
}
#[cfg(windows)]
fn platform_exts<P: ProcessManager>(cx: &StepCtx<'_, P>) -> Vec<String> {
parse_pathext(cx.state.get_env(oxdock_env::os::windows::PATHEXT))
}
#[cfg(not(windows))]
fn platform_exts<P: ProcessManager>(cx: &StepCtx<'_, P>) -> Vec<String> {
let _ = cx;
Vec::new()
}
fn exe_candidates(name: &str, exts: &[String]) -> Vec<String> {
#[cfg(windows)]
{
let lower = name.to_ascii_lowercase();
if exts
.iter()
.any(|ext| lower.ends_with(&ext.to_ascii_lowercase()))
{
vec![name.to_string()]
} else {
let mut out = vec![name.to_string()];
out.extend(exts.iter().map(|ext| format!("{name}{ext}")));
out
}
}
#[cfg(not(windows))]
{
let _ = exts;
vec![name.to_string()]
}
}
fn is_executable_candidate<P: ProcessManager>(
cx: &StepCtx<'_, P>,
candidate: &str,
exts: &[String],
) -> bool {
let Ok(guard) = cx.state.fs.resolve_read(&cx.state.cwd, candidate) else {
return false;
};
if !matches!(
cx.state.fs.entry_kind(&guard),
Ok(oxdock_fs::EntryKind::File)
) {
return false;
}
#[cfg(unix)]
{
let _ = exts;
use std::os::unix::fs::PermissionsExt;
cx.state
.fs
.metadata(&guard)
.map(|meta| meta.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
#[cfg(windows)]
{
let lower = candidate.to_ascii_lowercase();
exts.iter()
.any(|ext| lower.ends_with(&ext.to_ascii_lowercase()))
}
#[cfg(not(any(unix, windows)))]
{
let _ = (candidate, &guard, exts);
return false;
}
}
pub(crate) fn path_writable_from_value<P: ProcessManager>(
args: &[Value],
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
let path_val = args
.first()
.ok_or_else(|| anyhow::anyhow!("PATH_WRITABLE requires a path argument"))?;
let path_str = match path_val.as_str() {
Some(s) => s.to_string(),
None => bail!("PATH_WRITABLE path argument must evaluate to a string"),
};
if path_str.is_empty() {
return Ok(Value::bool(false));
}
let target = cx
.state
.fs
.resolve_write(&cx.state.cwd, &path_str)
.map_err(|e| anyhow::anyhow!("failed to resolve path '{}': {}", path_str, e))?;
let mut current = target;
loop {
match cx.state.fs.entry_kind_no_follow(¤t) {
Ok(EntryKind::Dir) => {
return Ok(Value::bool(probe_dir_writable(cx, ¤t)));
}
Ok(EntryKind::File) | Ok(EntryKind::Symlink) => {
return Ok(Value::bool(false));
}
Err(_) => {
let Some(parent) = current.parent() else {
return Ok(Value::bool(false));
};
if parent.as_path().as_os_str().is_empty() {
let cwd = cx.state.cwd.clone();
let anchor =
cx.state.fs.resolve_write(&cwd, ".").map_err(|e| {
anyhow::anyhow!("failed to resolve working directory: {e}")
})?;
return Ok(Value::bool(probe_dir_writable(cx, &anchor)));
}
current = parent;
}
}
}
}
fn probe_dir_writable<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
dir: &oxdock_fs::GuardedPath,
) -> bool {
use std::sync::atomic::{AtomicU64, Ordering};
static PROBE_COUNTER: AtomicU64 = AtomicU64::new(0);
let id = PROBE_COUNTER.fetch_add(1, Ordering::Relaxed);
let name = format!(".oxdock_probe_{id:x}");
let Ok(probe) = dir.join(&name) else {
return false;
};
if cx.state.fs.write_file(&probe, b"").is_err() {
return false;
}
let _guard = ProbeGuard {
fs: cx.state.fs.clone_box(),
path: probe,
};
true
}
struct ProbeGuard {
fs: Box<dyn oxdock_fs::WorkspaceFs>,
path: oxdock_fs::GuardedPath,
}
impl Drop for ProbeGuard {
fn drop(&mut self) {
let _ = self.fs.remove_file(&self.path);
}
}
fn pop_stack(stack: &mut Vec<Value>) -> Result<Value> {
stack
.pop()
.ok_or_else(|| anyhow::anyhow!("compiled math stack underflow"))
}
fn as_f64_value(val: &Value) -> Option<f64> {
if let Some(n) = val.as_i64() {
return Some(n as f64);
}
match val.as_f64() {
Some(f) if f.is_finite() => Some(f),
_ => None,
}
}
fn apply_arith(op: ArithOp, left: Value, right: Value) -> Result<Value> {
if let (Some(a), Some(b)) = (left.as_i64(), right.as_i64()) {
let v = match op {
ArithOp::Add => a.checked_add(b),
ArithOp::Sub => a.checked_sub(b),
ArithOp::Mul => a.checked_mul(b),
ArithOp::Div => a.checked_div(b),
};
return v.map(Value::int).ok_or_else(|| {
anyhow::anyhow!("arithmetic error: integer overflow or division by zero")
});
}
{
let (Some(a), Some(b)) = (as_f64_value(&left), as_f64_value(&right)) else {
bail!("Type Error: arithmetic requires Int or Float, found {left:?} and {right:?}");
};
if matches!(op, ArithOp::Div) && b == 0.0 {
bail!("arithmetic error: float division by zero");
}
let v = match op {
ArithOp::Add => a + b,
ArithOp::Sub => a - b,
ArithOp::Mul => a * b,
ArithOp::Div => a / b,
};
if v.is_finite() {
Ok(Value::float(v))
} else {
bail!("arithmetic error: non-finite float result")
}
}
}
fn apply_neg(val: Value) -> Result<Value> {
if let Some(n) = val.as_i64() {
return n
.checked_neg()
.map(Value::int)
.ok_or_else(|| anyhow::anyhow!("arithmetic error: integer overflow"));
}
if let Some(f) = val.as_f64() {
if f.is_finite() {
return Ok(Value::float(-f));
}
bail!("arithmetic error: non-finite float result");
}
bail!("Type Error: unary '-' requires Int or Float, found {val:?}")
}
pub(crate) fn values_equal(left: &Value, right: &Value) -> bool {
if let (Some(a), Some(b)) = (as_f64_value(left), as_f64_value(right)) {
return a == b;
}
left == right
}
fn apply_compare(op: CompareOp, left: &Value, right: &Value) -> Result<Value> {
if let (Some(a), Some(b)) = (as_f64_value(left), as_f64_value(right)) {
if left.as_i64().is_some() && right.as_i64().is_some() {
let (a, b) = (left.as_i64().unwrap_or(0), right.as_i64().unwrap_or(0));
let result = match op {
CompareOp::Eq => a == b,
CompareOp::Ne => a != b,
CompareOp::Lt => a < b,
CompareOp::Le => a <= b,
CompareOp::Gt => a > b,
CompareOp::Ge => a >= b,
};
return Ok(Value::bool(result));
}
let result = match op {
CompareOp::Eq => a == b,
CompareOp::Ne => a != b,
CompareOp::Lt => a < b,
CompareOp::Le => a <= b,
CompareOp::Gt => a > b,
CompareOp::Ge => a >= b,
};
return Ok(Value::bool(result));
}
match op {
CompareOp::Eq | CompareOp::Ne => {
let equal = left == right;
let result = match op {
CompareOp::Eq => equal,
CompareOp::Ne => !equal,
_ => bail!("internal error: equality shape"),
};
Ok(Value::bool(result))
}
CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => {
bail!(
"Type Error: ordering comparison requires Int or Float, found {left:?} and {right:?}"
);
}
}
}
fn trim_ascii(s: &str) -> &str {
s.trim_matches(|c: char| c.is_ascii_whitespace())
}
pub(crate) fn int_from_value(val: Value) -> Result<Value> {
if val.as_i64().is_some() {
return Ok(val);
}
if let Some(f) = val.as_f64() {
if f.is_finite() && f.fract() == 0.0 && f >= i64::MIN as f64 && f <= i64::MAX as f64 {
return Ok(Value::int(f as i64));
}
bail!("INT() requires an integer value, found FLOAT ({f:?})");
}
if let Some(b) = val.as_bool() {
return Ok(Value::int(i64::from(b)));
}
if let Some(s) = val.as_str() {
let trimmed = trim_ascii(s);
let clean = oxdock_parser::command::strip_digit_separators(trimmed);
return clean
.parse::<i64>()
.map(Value::int)
.map_err(|_| anyhow::anyhow!("INT() requires an integer string, found {s:?}"));
}
bail!("INT() requires an Int, Float, Bool, or String, found {val:?}")
}
pub(crate) fn float_from_value(val: Value) -> Result<Value> {
if let Some(f) = val.as_f64() {
if f.is_finite() {
return Ok(Value::float(f));
}
bail!("FLOAT() requires a finite value, found FLOAT ({f:?})");
}
if let Some(n) = val.as_i64() {
return Ok(Value::float(n as f64));
}
if let Some(s) = val.as_str() {
let trimmed = trim_ascii(s);
let parsed: f64 = trimmed
.parse()
.map_err(|_| anyhow::anyhow!("FLOAT() requires a numeric string, found {s:?}"))?;
if parsed.is_finite() {
return Ok(Value::float(parsed));
}
bail!("FLOAT() requires a finite value, found {s:?}");
}
bail!("FLOAT() requires an Int, Float, or String, found {val:?}")
}
pub(crate) fn has_key_from_value(map: Value, key: &str) -> Result<Value> {
let entries = map.as_map().ok_or_else(|| {
anyhow::anyhow!(
"HAS_KEY expects a MAP as its first argument, got {}",
map.type_name()
)
})?;
Ok(Value::bool(entries.contains_key(key)))
}
pub(crate) fn map_set_from_value(map: Value, key: String, value: Value) -> Result<Value> {
let entries = map.as_map().ok_or_else(|| {
anyhow::anyhow!(
"MAP_SET expects a MAP as its first argument, got {}",
map.type_name()
)
})?;
if entries.contains_key(&key) {
bail!("MAP_SET duplicate key '{key}'");
}
let mut next = entries.clone();
next.insert(key, value);
Ok(Value::map(next))
}
pub(crate) fn merge_maps_from_value(maps: Value, policy: String) -> Result<Value> {
let items = maps.as_list().ok_or_else(|| {
anyhow::anyhow!(
"MERGE_MAPS expects a LIST of MAPs, got {}",
maps.type_name()
)
})?;
let mut merged = std::collections::BTreeMap::new();
for (index, item) in items.iter().enumerate() {
let entries = item.as_map().ok_or_else(|| {
anyhow::anyhow!(
"MERGE_MAPS element {index} is {}, not MAP",
item.type_name()
)
})?;
for (key, value) in entries {
if merged.contains_key(key) && policy == "fail_on_duplicate" {
bail!(
"duplicate values key '{key}'; later files must not repeat it under fail_on_duplicate"
);
}
merged.insert(key.clone(), value.clone());
}
}
Ok(Value::map(merged))
}
pub(crate) fn type_of_from_value(value: Value) -> Result<Value> {
Ok(Value::string(value.type_name().to_string()))
}
pub(crate) fn rand_float_from_value(seed: Option<i64>) -> Result<Value> {
use rand::{RngExt, SeedableRng};
let draw = match seed {
Some(n) => rand::rngs::StdRng::seed_from_u64(n as u64).random_range(0.0..1.0),
None => rand::random::<f64>(),
};
Ok(Value::float(draw))
}
pub(crate) fn base64_encode_from_value(text: Value) -> Result<Value> {
use base64::Engine as _;
let input = text.as_str().ok_or_else(|| {
anyhow::anyhow!("BASE64_ENCODE expects a STRING, got {}", text.type_name())
})?;
Ok(Value::string(
base64::engine::general_purpose::STANDARD.encode(input.as_bytes()),
))
}
pub(crate) fn base64_decode_from_value(text: Value) -> Result<Value> {
use base64::Engine as _;
let input = text.as_str().ok_or_else(|| {
anyhow::anyhow!("BASE64_DECODE expects a STRING, got {}", text.type_name())
})?;
let bytes = base64::engine::general_purpose::STANDARD
.decode(input)
.map_err(|e| anyhow::anyhow!("BASE64_DECODE cannot decode {input:?}: {e}"))?;
let decoded = String::from_utf8(bytes)
.map_err(|_| anyhow::anyhow!("BASE64_DECODE decoded bytes are not UTF-8"))?;
Ok(Value::string(decoded))
}
pub(crate) fn to_json_from_value(value: Value) -> Result<Value> {
let json = value_to_json(&value)?;
let mut out = serde_json::to_string(&json).map_err(|e| anyhow::anyhow!("encode JSON: {e}"))?;
out.push('\n');
Ok(Value::string(out))
}
pub fn value_to_json(value: &Value) -> Result<serde_json::Value> {
if let Some(id) = value.as_handle() {
let mut map = serde_json::Map::new();
map.insert(
"task_id".to_string(),
serde_json::Value::Number(serde_json::Number::from(id)),
);
return Ok(serde_json::Value::Object(map));
}
if let Some(map) = value.as_map() {
return map
.iter()
.map(|(key, item)| value_to_json(item).map(|v| (key.clone(), v)))
.collect::<Result<serde_json::Map<_, _>>>()
.map(serde_json::Value::Object);
}
if let Some(list) = value.as_list() {
return list
.iter()
.map(value_to_json)
.collect::<Result<Vec<_>>>()
.map(serde_json::Value::Array);
}
if let Some(s) = value.as_str() {
return Ok(serde_json::Value::String(s.to_string()));
}
if let Some(i) = value.as_i64() {
return Ok(serde_json::Value::Number(serde_json::Number::from(i)));
}
if let Some(f) = value.as_f64() {
let number = serde_json::Number::from_f64(f)
.ok_or_else(|| anyhow::anyhow!("TO_JSON cannot encode non-finite float {f}"))?;
return Ok(serde_json::Value::Number(number));
}
if let Some(b) = value.as_bool() {
return Ok(serde_json::Value::Bool(b));
}
bail!(
"TO_JSON cannot encode {} values; use STRING, INT, FLOAT, BOOL, LIST, or MAP",
value.type_name()
)
}
fn resolve_const_call_arg<P: ProcessManager>(
state: &ExecState<P>,
src: &str,
) -> Result<Option<Value>> {
use oxdock_parser::template::{
TemplateArg, bare_sigil_error, classify_template_arg, qualified_keypath_error,
};
match classify_template_arg(src) {
TemplateArg::DollarQualified { alias, name, keys } => {
if keys.is_empty() {
super::import::resolve_const_ref(state, alias, name).map(Some)
} else {
Err(anyhow::anyhow!(qualified_keypath_error()))
}
}
TemplateArg::Dollar(_) => Ok(None),
TemplateArg::ConstRef { .. } | TemplateArg::KeyPath { .. } | TemplateArg::Var(_) => {
Err(anyhow::anyhow!(bare_sigil_error(src.trim())))
}
_ => Ok(None),
}
}
fn descend_value(current: Value, keys: &[String]) -> Result<Value> {
let mut current = current;
for key in keys {
if let Some(map) = current.as_map() {
current = map
.get(key)
.cloned()
.ok_or_else(|| anyhow::anyhow!("Key '{}' not found in map", key))?;
} else if let Some(list) = current.as_list() {
let idx: usize = key
.parse()
.map_err(|_| anyhow::anyhow!("Invalid array index '{}'", key))?;
current = list
.get(idx)
.cloned()
.ok_or_else(|| anyhow::anyhow!("Index {} out of bounds", idx))?;
} else {
bail!("Cannot traverse into scalar value at key '{}'", key);
}
}
Ok(current)
}
fn evaluate_compiled_math<P: ProcessManager>(
ops: &[MathOp],
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
let mut stack: Vec<Value> = Vec::with_capacity(8);
for op in ops {
match op {
MathOp::PushConst(v) => {
if let Some(s) = v.as_str() {
stack.push(Value::string(expand_string(s, &cx.state.envs, cx.state)?));
} else {
stack.push(v.clone());
}
}
MathOp::Load { name } => {
stack.push(load_var_binding(cx.state, name)?);
}
MathOp::LoadConstRef { alias, name } => {
stack.push(super::import::resolve_const_ref(cx.state, alias, name)?);
}
MathOp::LoadEnv(key) => match cx.state.get_env(key) {
Some(v) => stack.push(Value::string(v.to_string())),
None => stack.push(Value::string(String::new())),
},
MathOp::LoadKeyPath { base, keys } => {
let base_value = load_var_binding(cx.state, base)?;
stack.push(descend_value(base_value, keys)?);
}
MathOp::Call { name, arity } => {
let mut args = Vec::with_capacity(*arity);
for _ in 0..*arity {
args.push(pop_stack(&mut stack)?);
}
args.reverse();
let entry = super::handlers::resolve_call_entry(cx, name.as_str())?;
super::handlers::gate_call(cx, name.as_str(), &entry, args.len())?;
let val =
super::handlers::execute_call_entry(cx, name.as_str(), entry, args, true)?;
stack.push(val);
}
MathOp::Inspect { name } => {
let _ = load_var_binding(cx.state, name)?;
stack.push(Value::map(super::handlers::inspect_var_map(cx, name)?));
}
MathOp::Neg => {
let val = pop_stack(&mut stack)?;
stack.push(apply_neg(val)?);
}
MathOp::Add => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_arith(ArithOp::Add, left, right)?);
}
MathOp::Sub => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_arith(ArithOp::Sub, left, right)?);
}
MathOp::Mul => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_arith(ArithOp::Mul, left, right)?);
}
MathOp::Div => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_arith(ArithOp::Div, left, right)?);
}
MathOp::Lt => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_compare(CompareOp::Lt, &left, &right)?);
}
MathOp::Le => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_compare(CompareOp::Le, &left, &right)?);
}
MathOp::Gt => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_compare(CompareOp::Gt, &left, &right)?);
}
MathOp::Ge => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_compare(CompareOp::Ge, &left, &right)?);
}
MathOp::Eq => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_compare(CompareOp::Eq, &left, &right)?);
}
MathOp::Ne => {
let right = pop_stack(&mut stack)?;
let left = pop_stack(&mut stack)?;
stack.push(apply_compare(CompareOp::Ne, &left, &right)?);
}
}
}
if stack.len() != 1 {
bail!("compiled math left {} values on the stack", stack.len());
}
pop_stack(&mut stack)
}
pub(crate) fn glob_from_value<P: ProcessManager>(
args: &[Value],
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
let pattern_val = args
.first()
.ok_or_else(|| anyhow::anyhow!("GLOB requires a pattern argument"))?;
let Some(raw_pattern) = pattern_val.as_str() else {
bail!("GLOB pattern argument must evaluate to a string");
};
let raw_pattern = raw_pattern.to_string();
if to_forward_slashes(&raw_pattern)
.split('/')
.any(|seg| seg == "..")
{
return Ok(Value::list(Vec::new()));
}
let _ = cx.state.fs.resolve_read(&cx.state.cwd, ".")?;
let root = cx.state.fs.root().clone();
let root_path = root.as_path().to_path_buf();
let mut entries: Vec<Value> = root
.glob_paths(&raw_pattern)?
.into_iter()
.filter_map(|p| {
p.strip_prefix(&root_path)
.ok()
.map(|rel| Value::string(to_forward_slashes(&rel.to_string_lossy())))
})
.collect();
entries.sort_by(|a, b| format!("{}", a).cmp(&format!("{}", b)));
Ok(Value::list(entries))
}
pub(crate) fn load_toml_from_value<P: ProcessManager>(
args: &[Value],
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
let path_val = args
.first()
.ok_or_else(|| anyhow::anyhow!("LOAD_TOML requires a path argument"))?;
let Some(path_str) = path_val.as_str() else {
bail!("LOAD_TOML path argument must evaluate to a string");
};
let path_str = path_str.to_string();
let target = cx
.state
.fs
.resolve_read(&cx.state.cwd, &path_str)
.map_err(|e| anyhow::anyhow!("failed to resolve TOML path '{}': {}", path_str, e))?;
let content = cx
.state
.fs
.read_file(&target)
.map_err(|e| anyhow::anyhow!("failed to read TOML file '{}': {}", path_str, e))?;
let content_str = std::str::from_utf8(&content)
.map_err(|e| anyhow::anyhow!("invalid UTF-8 in TOML file '{}': {}", path_str, e))?;
load_toml_value(content_str)
}
pub(crate) fn load_json_from_value<P: ProcessManager>(
args: &[Value],
cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
let path_val = args
.first()
.ok_or_else(|| anyhow::anyhow!("LOAD_JSON requires a path argument"))?;
let Some(path_str) = path_val.as_str() else {
bail!("LOAD_JSON path argument must evaluate to a string");
};
let path_str = path_str.to_string();
let target = cx
.state
.fs
.resolve_read(&cx.state.cwd, &path_str)
.map_err(|e| anyhow::anyhow!("failed to resolve JSON path '{}': {}", path_str, e))?;
let content = cx
.state
.fs
.read_file(&target)
.map_err(|e| anyhow::anyhow!("failed to read JSON file '{}': {}", path_str, e))?;
let content_str = std::str::from_utf8(&content)
.map_err(|e| anyhow::anyhow!("invalid UTF-8 in JSON file '{}': {}", path_str, e))?;
load_json_value(content_str)
}
pub fn load_toml_value(content: &str) -> Result<Value> {
let json_val: serde_json::Value =
toml::from_str(content).map_err(|e| anyhow::anyhow!("TOML parse error: {}", e))?;
Ok(json_to_value(json_val))
}
pub(crate) fn parse_toml_from_value(value: Value) -> Result<Value> {
let Some(text) = value.as_str() else {
bail!("PARSE_TOML expects a STRING, got {}", value.type_name());
};
load_toml_value(text)
}
pub fn load_json_value(content: &str) -> Result<Value> {
let stripped = strip_json_comments(content);
let json_val: serde_json::Value =
serde_json::from_str(&stripped).map_err(|e| anyhow::anyhow!("JSON parse error: {}", e))?;
Ok(json_to_value(json_val))
}
pub fn strip_json_comments(content: &str) -> String {
let mut out = String::with_capacity(content.len());
let mut chars = content.chars().peekable();
let mut in_string = false;
let mut escaped = false;
while let Some(c) = chars.next() {
if in_string {
out.push(c);
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == '"' {
in_string = false;
}
continue;
}
if c == '"' {
in_string = true;
out.push(c);
continue;
}
if c == '/' {
match chars.peek() {
Some('/') => {
chars.next();
out.push(' ');
out.push(' ');
for c2 in chars.by_ref() {
if c2 == '\n' {
out.push('\n');
break;
}
out.push(' ');
}
continue;
}
Some('*') => {
chars.next();
out.push(' ');
out.push(' ');
let mut prev_star = false;
for c2 in chars.by_ref() {
if c2 == '\n' {
out.push('\n');
} else {
out.push(' ');
}
if prev_star && c2 == '/' {
break;
}
prev_star = c2 == '*';
}
continue;
}
_ => {
out.push(c);
continue;
}
}
}
out.push(c);
}
out
}
pub(crate) fn parse_json_from_value(value: Value) -> Result<Value> {
let Some(text) = value.as_str() else {
bail!("PARSE_JSON expects a STRING, got {}", value.type_name());
};
load_json_value(text)
}
pub fn json_to_value_typed(tag: Option<&TypeTag>, v: serde_json::Value) -> Result<Value> {
if !matches!(tag, Some(TypeTag::Handle)) {
return Ok(json_to_value(v));
}
let map = match v {
serde_json::Value::Object(map) => map,
other => bail!("HANDLE argument must be an object like {{\"task_id\": 7}}, got {other}"),
};
if map.len() != 1 || !map.contains_key("task_id") {
bail!("HANDLE argument must be exactly {{\"task_id\": N}} with no other keys");
}
let id = match map["task_id"] {
serde_json::Value::Number(ref n) => n.as_u64().filter(|id| *id >= 1),
_ => None,
}
.ok_or_else(|| anyhow::anyhow!("HANDLE argument `task_id` must be a positive integer"))?;
Ok(Value::handle(id))
}
pub fn value_to_json_typed(tag: Option<&TypeTag>, value: &Value) -> Result<serde_json::Value> {
if !matches!(tag, Some(TypeTag::Handle)) {
return value_to_json(value);
}
match value.as_handle() {
Some(id) => {
let mut map = serde_json::Map::new();
map.insert(
"task_id".to_string(),
serde_json::Value::Number(serde_json::Number::from(id)),
);
Ok(serde_json::Value::Object(map))
}
None => bail!(
"cannot encode {} as HANDLE; expected a task handle",
value.type_name()
),
}
}
pub fn json_to_value(v: serde_json::Value) -> Value {
match v {
serde_json::Value::String(s) => Value::string(s),
serde_json::Value::Bool(b) => Value::bool(b),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
Value::int(i)
} else if let Some(f) = n.as_f64() {
Value::float(f)
} else {
Value::string(n.to_string())
}
}
serde_json::Value::Array(arr) => Value::list(arr.into_iter().map(json_to_value).collect()),
serde_json::Value::Object(map) => Value::map(
map.into_iter()
.map(|(k, v)| (k, json_to_value(v)))
.collect(),
),
serde_json::Value::Null => Value::string(String::new()),
}
}
fn push_escaped_text(output: &mut String, text: &str) {
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\\' => match chars.peek() {
Some(&'\\') => {
output.push('\\');
chars.next();
}
Some(&'{') => {
let mut lookahead = chars.clone();
lookahead.next(); if lookahead.next() == Some('{') {
output.push_str("{{");
chars.next(); chars.next(); } else {
output.push('\\');
}
}
Some(&'n') => {
output.push('\n');
chars.next();
}
Some(&'t') => {
output.push('\t');
chars.next();
}
Some(&'r') => {
output.push('\r');
chars.next();
}
Some(&'"') => {
output.push('"');
chars.next();
}
_ => {
output.push('\\');
}
},
_ => {
output.push(c);
}
}
}
}
pub(crate) fn expand_string<P: ProcessManager>(
input: &str,
env: &std::collections::HashMap<String, String>,
state: &ExecState<P>,
) -> Result<String> {
use oxdock_parser::template::{
PlaceholderKey, TemplateSegment, TemplateSegments, bare_sigil_error,
classify_placeholder_key, qualified_keypath_error,
};
let mut output = String::with_capacity(input.len());
let missing_key = |key: &str| {
let mut msg = format!("undefined script variable: '{key}'");
if env.contains_key(key) || state.get_env(key).is_some() {
msg.push_str(&format!(
"; did you mean 'env:{key}' (environment variable)?"
));
} else {
msg.push_str(&format!("; did you mean '${key}'?"));
}
anyhow::anyhow!("{msg}")
};
for segment in TemplateSegments::new(input) {
match segment {
TemplateSegment::Text(text) => push_escaped_text(&mut output, text),
TemplateSegment::Placeholder { key, .. } => match classify_placeholder_key(key) {
PlaceholderKey::Empty => {
bail!("empty template placeholder");
}
PlaceholderKey::DollarQualified { alias, name, keys } => {
if keys.is_empty() {
let value = super::import::resolve_const_ref(state, alias, name)?;
output.push_str(&format_value_for_string(&value)?);
} else {
return Err(anyhow::anyhow!(qualified_keypath_error()));
}
}
PlaceholderKey::Dollar(rest) => {
let Some(parts) = oxdock_parser::template::parse_var_path(rest) else {
bail!("invalid placeholder key: '${rest}'");
};
let (base, segs) = parts.split_first().expect("split always yields one");
let base_value = load_var_binding(state, base)?;
let value = descend_value(base_value, segs)?;
output.push_str(&format_value_for_string(&value)?);
}
PlaceholderKey::Env(env_key) => {
let env_key = env_key.trim();
if env_key.is_empty() {
bail!("undefined environment variable: ''");
}
let val = env
.get(env_key)
.map(String::as_str)
.or_else(|| state.get_env(env_key));
if let Some(v) = val {
output.push_str(v);
}
}
PlaceholderKey::ScriptEnv(env_key) => {
let env_key = env_key.trim();
if env_key.is_empty() {
bail!("undefined environment variable: ''");
}
if let Some(v) = env.get(env_key).map(String::as_str) {
output.push_str(v);
}
}
PlaceholderKey::ConstRef { .. }
| PlaceholderKey::KeyPath { .. }
| PlaceholderKey::Var(_) => {
return Err(anyhow::anyhow!(bare_sigil_error(key.trim())));
}
PlaceholderKey::Bare(key) => {
return Err(missing_key(key));
}
PlaceholderKey::Call(call) => {
let Some(module) = call.module else {
return Err(missing_key(key));
};
let resolve = super::native::placeholder_resolver(state.pure_function_table());
let vars = state.all_vars();
let args_src = oxdock_parser::template::split_placeholder_args(call.args_raw);
let mut args = Vec::with_capacity(args_src.len());
for src in args_src {
if let Some(value) = resolve_const_call_arg(state, &src)? {
args.push(value);
} else {
args.push(oxdock_process::resolve_placeholder_arg(&src, &vars)?);
}
}
let result = match resolve(module, call.name, args) {
Ok(value) => value,
Err(err) => {
if let Some(text) = state.functions.describe_unit_placeholder_miss(
&super::import::active_unit_alias_targets(state),
module,
call.name,
) {
bail!("{text}");
}
return Err(err);
}
};
output.push_str(&format_value_for_string(&result)?);
}
},
}
}
Ok(output)
}
pub(crate) fn expand_dsl_vars<P: ProcessManager>(
input: &str,
state: &ExecState<P>,
) -> anyhow::Result<String> {
let mut output = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\' && chars.peek() == Some(&'$') {
output.push('$');
chars.next();
continue;
}
if c == '{' && chars.peek() == Some(&'{') {
output.push('{');
output.push(chars.next().unwrap_or('{'));
while let Some(ch) = chars.next() {
output.push(ch);
if ch == '}' && chars.peek() == Some(&'}') {
output.push(chars.next().unwrap_or('}'));
break;
}
}
continue;
}
if c == '$' {
let mut var_name = String::new();
while let Some(&ch) = chars.peek() {
if ch.is_ascii_alphanumeric() || ch == '_' {
var_name.push(ch);
chars.next();
} else {
break;
}
}
if var_name.is_empty() {
output.push('$');
continue;
}
if let Some(val) = state.get_var(&var_name) {
output.push_str(&format_value_for_string(&val)?);
} else {
output.push('$');
output.push_str(&var_name);
}
} else {
output.push(c);
}
}
Ok(output)
}
pub(crate) const TEXT_REGEX_SIZE_LIMIT: usize = 1_000_000;
const TEXT_PATTERN_CACHE_MAX: usize = 64;
static TEXT_PATTERN_CACHE: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashMap<String, regex::Regex>>,
> = std::sync::OnceLock::new();
fn text_pattern_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, regex::Regex>>
{
TEXT_PATTERN_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}
pub(crate) fn text_compile_pattern(func: &str, pattern: &str) -> Result<regex::Regex> {
if let Some(hit) = text_pattern_cache()
.lock()
.map(|guard| guard.get(pattern).cloned())
.unwrap_or(None)
{
return Ok(hit);
}
let re = regex::RegexBuilder::new(pattern)
.size_limit(TEXT_REGEX_SIZE_LIMIT)
.build()
.map_err(|e| anyhow::anyhow!("{func} invalid pattern {pattern:?}: {e}"))?;
if let Ok(mut guard) = text_pattern_cache().lock() {
if guard.len() >= TEXT_PATTERN_CACHE_MAX {
guard.clear();
}
guard.insert(pattern.to_string(), re.clone());
}
Ok(re)
}
pub(crate) fn text_trim_str(s: &str) -> String {
s.trim().to_string()
}
pub(crate) fn text_trim_prefix_str(s: &str, prefix: &str) -> String {
s.strip_prefix(prefix).unwrap_or(s).to_string()
}
pub(crate) fn text_trim_suffix_str(s: &str, suffix: &str) -> String {
s.strip_suffix(suffix).unwrap_or(s).to_string()
}
pub(crate) fn text_split_str(s: &str, delimiter: &str) -> Vec<String> {
if delimiter.is_empty() {
return s.chars().map(|c| c.to_string()).collect();
}
s.split(delimiter).map(str::to_string).collect()
}
pub(crate) fn text_fields_str(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_string).collect()
}
pub(crate) fn text_lines_str(s: &str) -> Vec<String> {
line_ending::LineEnding::split(&line_ending::LineEnding::normalize(s))
}
pub(crate) fn text_replace_literal_str(
s: &str,
from: &str,
to: &str,
func: &str,
) -> Result<String> {
if from.is_empty() {
bail!("{func} needs a non-empty search string");
}
Ok(s.replace(from, to))
}
pub(crate) fn text_replace_regex_str(
s: &str,
pattern: &str,
replacement: &str,
func: &str,
) -> Result<String> {
let re = text_compile_pattern(func, pattern)?;
Ok(re.replace_all(s, replacement).into_owned())
}
pub(crate) fn text_count_str(s: &str, needle: &str, func: &str) -> Result<i64> {
if needle.is_empty() {
bail!("{func} needs a non-empty needle");
}
Ok(s.match_indices(needle).count() as i64)
}
pub(crate) fn text_grep_str(
s: &str,
pattern: &str,
invert: bool,
func: &str,
) -> Result<Vec<String>> {
let re = text_compile_pattern(func, pattern)?;
Ok(text_lines_str(s)
.into_iter()
.filter(|line| re.is_match(line) != invert)
.collect())
}
pub(crate) fn text_count_matches_str(s: &str, pattern: &str, func: &str) -> Result<i64> {
Ok(text_grep_str(s, pattern, false, func)?.len() as i64)
}
pub(crate) fn text_invert_flag(options: &std::collections::BTreeMap<String, Value>) -> bool {
options
.get("invert")
.map(|value| value.as_bool().expect("check_options verified BOOL"))
.unwrap_or(false)
}
pub(crate) fn text_lines_range_str(s: &str, from: i64, to: i64, func: &str) -> Result<Vec<String>> {
if from < 1 {
bail!("{func} needs a 1-based start line, got {from}");
}
if from > to {
bail!("{func} needs start <= end, got {from}..={to}");
}
let lines = text_lines_str(s);
let start = (from - 1) as usize;
if start >= lines.len() {
return Ok(Vec::new());
}
let end = (to as usize).min(lines.len());
Ok(lines[start..end].to_vec())
}
pub(crate) fn text_extract_str(s: &str, pattern: &str, func: &str) -> Result<Vec<String>> {
let re = text_compile_pattern(func, pattern)?;
let Some(caps) = re.captures(s) else {
return Ok(Vec::new());
};
let mut out = Vec::with_capacity(caps.len());
for i in 0..caps.len() {
out.push(
caps.get(i)
.map(|m| m.as_str().to_string())
.unwrap_or_default(),
);
}
Ok(out)
}
pub(crate) enum TextPump {
Trim,
TrimPrefix(String),
TrimSuffix(String),
ToUpper,
ToLower,
ReplaceLiteral { from: String, to: String },
}
impl TextPump {
pub(crate) fn apply_str(&self, s: &str, func: &str) -> Result<String> {
match self {
TextPump::Trim => Ok(text_trim_str(s)),
TextPump::TrimPrefix(prefix) => Ok(text_trim_prefix_str(s, prefix)),
TextPump::TrimSuffix(suffix) => Ok(text_trim_suffix_str(s, suffix)),
TextPump::ToUpper => Ok(s.to_uppercase()),
TextPump::ToLower => Ok(s.to_lowercase()),
TextPump::ReplaceLiteral { from, to } => text_replace_literal_str(s, from, to, func),
}
}
}
pub(crate) fn mirror_string(func: &str, value: &Value, pump: TextPump) -> Result<Value> {
if let Some(s) = value.as_str() {
return pump.apply_str(s, func).map(Value::string);
}
Err(pipe_needs_step_io(func))
}
pub(crate) fn pipe_needs_step_io(func: &str) -> anyhow::Error {
anyhow::anyhow!(
"{func} on PIPE input needs step IO, unavailable to placeholder calls; pass a STRING there"
)
}
pub(crate) fn mirror_stream<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
func: &str,
value: &Value,
pump: TextPump,
) -> Result<Value> {
if let Some(s) = value.as_str() {
return pump.apply_str(s, func).map(Value::string);
}
if value.as_pipe_handle().is_none() {
return Err(type_mismatch(
&format!("{func} text position"),
&oxdock_parser::union_tag!(String, Pipe),
value,
));
}
if let TextPump::ReplaceLiteral { from, .. } = &pump
&& from.is_empty()
{
bail!("{func} needs a non-empty search string");
}
let reader = cx
.pipe_reader(value)
.map_err(|e| anyhow::anyhow!("{func} cannot read PIPE input: {e:#}"))?;
let output = cx.new_pipe();
let writer = cx
.pipe_writer(&output)
.map_err(|e| anyhow::anyhow!("{func} cannot create PIPE output: {e:#}"))?;
let cancelled = cx.cancel_token();
let thread_name = format!("oxdock-text-{func}-pump");
std::thread::Builder::new()
.name(thread_name)
.spawn(move || run_text_pump(reader, writer, pump, &cancelled))
.map_err(|e| anyhow::anyhow!("{func} cannot spawn pump thread: {e}"))?;
Ok(output)
}
#[derive(Debug)]
struct PumpDownstreamClosed;
impl std::fmt::Display for PumpDownstreamClosed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("text pump downstream closed its read end")
}
}
impl std::error::Error for PumpDownstreamClosed {}
fn run_text_pump(
reader: SharedInput,
writer: SharedOutput,
pump: TextPump,
cancelled: &AtomicBool,
) {
let fail_closed = |cancelled: &AtomicBool| {
cancelled.store(true, Ordering::SeqCst);
};
let mut state = TextPumpState::new(pump);
let mut chunk = [0u8; super::io::CHUNK_SIZE];
loop {
if cancelled.load(Ordering::SeqCst) {
break;
}
let n = match reader.lock() {
Ok(mut guard) => match guard.read(&mut chunk) {
Ok(n) => n,
Err(_) => {
fail_closed(cancelled);
break;
}
},
Err(_) => {
fail_closed(cancelled);
break;
}
};
if n == 0 {
if let Err(e) = state.flush(&writer)
&& e.downcast_ref::<PumpDownstreamClosed>().is_none()
{
fail_closed(cancelled);
}
break;
}
if let Err(e) = state.push(&chunk[..n], &writer) {
if e.downcast_ref::<PumpDownstreamClosed>().is_none() {
fail_closed(cancelled);
}
break;
}
}
}
enum TextPumpState {
Case {
upper: bool,
carry: Vec<u8>,
},
Trim {
leading: bool,
carry: Vec<u8>,
held: SpillBuffer,
},
Prefix {
prefix: Vec<u8>,
buf: Vec<u8>,
decided: bool,
},
Suffix {
suffix: Vec<u8>,
window: Vec<u8>,
},
Replace {
from: Vec<u8>,
to: Vec<u8>,
buf: Vec<u8>,
},
}
impl TextPumpState {
fn new(pump: TextPump) -> Self {
match pump {
TextPump::Trim => Self::Trim {
leading: false,
carry: Vec::new(),
held: SpillBuffer::new(),
},
TextPump::TrimPrefix(prefix) => Self::Prefix {
prefix: prefix.into_bytes(),
buf: Vec::new(),
decided: false,
},
TextPump::TrimSuffix(suffix) => Self::Suffix {
suffix: suffix.into_bytes(),
window: Vec::new(),
},
TextPump::ToUpper => Self::Case {
upper: true,
carry: Vec::new(),
},
TextPump::ToLower => Self::Case {
upper: false,
carry: Vec::new(),
},
TextPump::ReplaceLiteral { from, to } => Self::Replace {
from: from.into_bytes(),
to: to.into_bytes(),
buf: Vec::new(),
},
}
}
fn push(&mut self, data: &[u8], writer: &SharedOutput) -> Result<()> {
match self {
Self::Case { upper, carry } => Self::push_case(*upper, carry, data, writer),
Self::Trim {
leading,
carry,
held,
} => Self::push_trim(leading, carry, held, data, writer),
Self::Prefix {
prefix,
buf,
decided,
} => Self::push_prefix(prefix, buf, decided, data, writer),
Self::Suffix { suffix, window } => Self::push_suffix(suffix, window, data, writer),
Self::Replace { from, to, buf } => Self::push_replace(from, to, buf, data, writer),
}
}
fn flush(&mut self, writer: &SharedOutput) -> Result<()> {
match self {
Self::Case { upper, carry } => {
let text = std::str::from_utf8(carry)
.map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
let mapped = if *upper {
text.to_uppercase()
} else {
text.to_lowercase()
};
Self::write(writer, mapped.as_bytes())
}
Self::Trim {
leading,
carry,
held,
} => {
if !*leading {
return Ok(());
}
let _ = held;
let text = std::str::from_utf8(carry)
.map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
let head = text.trim_end_matches(char::is_whitespace);
Self::write(writer, head.as_bytes())
}
Self::Prefix { buf, decided, .. } => {
if *decided {
return Ok(());
}
*decided = true;
let rest = std::mem::take(buf);
Self::write(writer, &rest)
}
Self::Suffix { suffix, window } => {
let rest = std::mem::take(window);
if !suffix.is_empty() && rest.as_slice() == suffix.as_slice() {
return Ok(());
}
Self::write(writer, &rest)
}
Self::Replace { from, to, buf } => {
let (out, consumed) = Self::replace_scan(from, to, buf, buf.len());
buf.drain(..consumed);
Self::write(writer, &out)
}
}
}
fn write(writer: &SharedOutput, bytes: &[u8]) -> Result<()> {
if bytes.is_empty() {
return Ok(());
}
writer
.lock()
.map_err(|_| anyhow::anyhow!("text pump writer lock poisoned"))?
.write_all(bytes)
.map_err(|e| {
if e.kind() == std::io::ErrorKind::BrokenPipe {
anyhow::Error::new(PumpDownstreamClosed)
} else {
anyhow::anyhow!("text pump write failed: {e}")
}
})?;
Ok(())
}
fn drain_into(held: &SpillBuffer, writer: &SharedOutput) -> Result<()> {
let bytes = held
.drain_bytes()
.map_err(|e| anyhow::anyhow!("text pump spill drain failed: {e}"))?;
Self::write(writer, &bytes)
}
fn head_tail(staged: &[u8]) -> (&[u8], &[u8]) {
let hold = trailing_incomplete_len(staged);
staged.split_at(staged.len() - hold)
}
fn push_case(
upper: bool,
carry: &mut Vec<u8>,
data: &[u8],
writer: &SharedOutput,
) -> Result<()> {
let mut staged = std::mem::take(carry);
staged.extend_from_slice(data);
let (head, tail) = Self::head_tail(&staged);
let text = std::str::from_utf8(head)
.map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
let mapped = if upper {
text.to_uppercase()
} else {
text.to_lowercase()
};
Self::write(writer, mapped.as_bytes())?;
*carry = tail.to_vec();
Ok(())
}
fn push_trim(
leading: &mut bool,
carry: &mut Vec<u8>,
held: &SpillBuffer,
data: &[u8],
writer: &SharedOutput,
) -> Result<()> {
let mut staged = std::mem::take(carry);
staged.extend_from_slice(data);
let (head, tail) = Self::head_tail(&staged);
let mut text = std::str::from_utf8(head)
.map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
if !*leading {
text = text.trim_start_matches(char::is_whitespace);
if text.is_empty() {
*carry = tail.to_vec();
return Ok(());
}
*leading = true;
}
let content = text.trim_end_matches(char::is_whitespace);
let ws = &text[content.len()..];
if !content.is_empty() {
Self::drain_into(held, writer)?;
Self::write(writer, content.as_bytes())?;
}
held.push_bytes(ws.as_bytes())
.map_err(|e| anyhow::anyhow!("text pump spill failed: {e}"))?;
*carry = tail.to_vec();
Ok(())
}
fn push_prefix(
prefix: &[u8],
buf: &mut Vec<u8>,
decided: &mut bool,
data: &[u8],
writer: &SharedOutput,
) -> Result<()> {
if *decided {
return Self::write(writer, data);
}
buf.extend_from_slice(data);
if buf.len() < prefix.len() {
return Ok(());
}
*decided = true;
let taken = std::mem::take(buf);
match taken.strip_prefix(prefix) {
Some(rest) => Self::write(writer, rest),
None => Self::write(writer, &taken),
}
}
fn push_suffix(
suffix: &[u8],
window: &mut Vec<u8>,
data: &[u8],
writer: &SharedOutput,
) -> Result<()> {
if suffix.is_empty() {
return Self::write(writer, data);
}
window.extend_from_slice(data);
if window.len() > suffix.len() {
let emit = window.len() - suffix.len();
Self::write(writer, &window[..emit])?;
window.drain(..emit);
}
Ok(())
}
fn push_replace(
from: &[u8],
to: &[u8],
buf: &mut Vec<u8>,
data: &[u8],
writer: &SharedOutput,
) -> Result<()> {
buf.extend_from_slice(data);
let retain = (from.len() - 1).min(buf.len());
let emit_until = buf.len() - retain;
let (out, consumed) = Self::replace_scan(from, to, buf, emit_until);
buf.drain(..consumed);
Self::write(writer, &out)
}
fn replace_scan(from: &[u8], to: &[u8], buf: &[u8], limit: usize) -> (Vec<u8>, usize) {
let mut out = Vec::with_capacity(limit);
let mut i = 0;
while i < limit {
if buf[i..].starts_with(from) {
out.extend_from_slice(to);
i += from.len();
} else {
out.push(buf[i]);
i += 1;
}
}
(out, i)
}
}
fn trailing_incomplete_len(buf: &[u8]) -> usize {
for n in 1..=3 {
if n > buf.len() {
break;
}
let b = buf[buf.len() - n];
if b < 0x80 {
break;
}
if b >= 0xC0 {
if b > 0xF4 {
break;
}
let need = if b < 0xE0 {
2
} else if b < 0xF0 {
3
} else {
4
};
if n < need {
return n;
}
break;
}
}
0
}
pub(crate) fn read_pipe_eager<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
func: &str,
value: &Value,
) -> Result<String> {
if value.as_pipe_handle().is_none() {
return Err(type_mismatch(
&format!("{func} text position"),
&oxdock_parser::union_tag!(String, Pipe),
value,
));
}
let reader = cx
.pipe_reader(value)
.map_err(|e| anyhow::anyhow!("{func} cannot read PIPE input: {e:#}"))?;
let spill = SpillBuffer::new();
let mut carry = Vec::new();
let mut chunk = [0u8; super::io::CHUNK_SIZE];
loop {
let n = reader.lock().map(|mut guard| guard.read(&mut chunk));
let n = n
.map_err(|_| anyhow::anyhow!("{func} pipe reader lock poisoned"))?
.map_err(|e| anyhow::anyhow!("{func} cannot read PIPE input: {e}"))?;
if n == 0 {
break;
}
let mut staged = std::mem::take(&mut carry);
staged.extend_from_slice(&chunk[..n]);
let hold = trailing_incomplete_len(&staged);
let valid_len = staged.len() - hold;
std::str::from_utf8(&staged[..valid_len])
.map_err(|_| anyhow::anyhow!("{func} PIPE input is not valid UTF-8"))?;
spill
.push_bytes(&staged[..valid_len])
.map_err(|e| anyhow::anyhow!("{func} PIPE input exceeds the spill backlog: {e}"))?;
carry = staged[valid_len..].to_vec();
}
spill
.push_bytes(&carry)
.map_err(|e| anyhow::anyhow!("{func} PIPE input exceeds the spill backlog: {e}"))?;
spill
.drain_string_strict()
.map_err(|_| anyhow::anyhow!("{func} PIPE input is not valid UTF-8"))
}
pub(crate) fn write_completed_pipe<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
func: &str,
text: String,
) -> Result<Value> {
let pipe = cx.new_pipe();
let writer = cx
.pipe_writer(&pipe)
.map_err(|e| anyhow::anyhow!("{func} cannot create PIPE output: {e:#}"))?;
{
let mut guard = writer
.lock()
.map_err(|_| anyhow::anyhow!("{func} pipe writer lock poisoned"))?;
guard
.write_all(text.as_bytes())
.map_err(|e| anyhow::anyhow!("{func} cannot write PIPE output: {e}"))?;
guard
.flush()
.map_err(|e| anyhow::anyhow!("{func} cannot write PIPE output: {e}"))?;
}
Ok(pipe)
}
pub(crate) fn text_list_value(items: Vec<String>) -> Value {
Value::list(items.into_iter().map(Value::string).collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pop_stack_underflow_returns_error() {
let mut stack: Vec<Value> = Vec::new();
assert!(
pop_stack(&mut stack).is_err(),
"empty pop must error, not panic"
);
stack.push(Value::int(1));
assert_eq!(pop_stack(&mut stack).unwrap(), Value::int(1));
assert!(pop_stack(&mut stack).is_err());
}
#[test]
fn type_of_names_words_for_branching() {
use oxdock_parser::{
BOOL_TYPE_NAME, DURATION_TYPE_NAME, FLOAT_TYPE_NAME, HANDLE_TYPE_NAME, INT_TYPE_NAME,
LIST_TYPE_NAME, MAP_TYPE_NAME, PATH_TYPE_NAME, PERMIT_TYPE_NAME, PIPE_TYPE_NAME,
SEMAPHORE_TYPE_NAME, STRING_TYPE_NAME,
};
use std::collections::BTreeMap;
fn sample(name: &str) -> Option<Value> {
match name {
INT_TYPE_NAME => Some(Value::int(1)),
FLOAT_TYPE_NAME => Some(Value::float(1.5)),
STRING_TYPE_NAME => Some(Value::string("x".to_string())),
BOOL_TYPE_NAME => Some(Value::bool(true)),
LIST_TYPE_NAME => Some(Value::list(vec![])),
MAP_TYPE_NAME => Some(Value::map(BTreeMap::new())),
PATH_TYPE_NAME => {
#[allow(clippy::disallowed_types)]
let path = std::path::PathBuf::from("x");
Some(Value::path(path))
}
DURATION_TYPE_NAME => Some(Value::duration(std::time::Duration::from_secs(1))),
PIPE_TYPE_NAME => Some(Value::pipe_fresh()),
HANDLE_TYPE_NAME => Some(Value::handle(1)),
SEMAPHORE_TYPE_NAME => Some(Value::semaphore(1)),
PERMIT_TYPE_NAME => {
let sem = Value::semaphore(1);
let backend = sem.as_semaphore().expect("semaphore backend");
Some(Value::permit(&backend))
}
_ => None,
}
}
for (name, _) in oxdock_parser::startup_descriptors() {
let value =
sample(name).unwrap_or_else(|| panic!("no sampler for startup word {name}"));
let word = type_of_from_value(value).expect("type_of runs");
assert_eq!(word.as_str(), Some(name), "TYPE_OF must name {name}");
}
}
#[test]
fn map_set_inserts_and_rejects_duplicates() {
use std::collections::BTreeMap;
let empty = Value::map(BTreeMap::new());
let one = map_set_from_value(empty, "a".to_string(), Value::string("x".to_string()))
.expect("insert");
assert_eq!(
one.as_map().expect("map").get("a").expect("key").as_str(),
Some("x")
);
assert!(map_set_from_value(one, "a".to_string(), Value::string("y".to_string())).is_err());
assert!(
map_set_from_value(
Value::string("nope".to_string()),
"a".to_string(),
Value::int(1)
)
.is_err()
);
}
#[test]
fn has_key_reports_presence() {
use std::collections::BTreeMap;
let mut entries = BTreeMap::new();
entries.insert("name".to_string(), Value::string("mary".to_string()));
let mary = Value::map(entries);
assert_eq!(
has_key_from_value(mary.clone(), "name")
.expect("has")
.as_bool(),
Some(true)
);
assert_eq!(
has_key_from_value(mary, "globs").expect("has").as_bool(),
Some(false)
);
assert!(has_key_from_value(Value::int(1), "name").is_err());
}
#[test]
fn parse_text_matches_file_load_shapes() {
let json = parse_json_from_value(Value::string("{\"a\": 1}".to_string())).expect("parse");
assert_eq!(
json.as_map().expect("map").get("a").expect("key").as_i64(),
Some(1)
);
let toml = parse_toml_from_value(Value::string("a = 2\n".to_string())).expect("parse");
assert_eq!(
toml.as_map().expect("map").get("a").expect("key").as_i64(),
Some(2)
);
let list = parse_json_from_value(Value::string("[1, 2]".to_string())).expect("parse");
assert_eq!(list.as_list().expect("list").len(), 2);
assert!(parse_json_from_value(Value::string("{bad".to_string())).is_err());
assert!(parse_toml_from_value(Value::string("a = ".to_string())).is_err());
assert!(parse_json_from_value(Value::int(1)).is_err());
assert!(parse_toml_from_value(Value::bool(true)).is_err());
}
#[test]
fn json_comments_strip_outside_strings_only() {
let stripped = strip_json_comments("{\"u\": \"http://x/y\"} // note\n");
assert!(stripped.contains("http://x/y"), "string kept: {stripped}");
let doc = load_json_value(
"{\n// leading note\n\"a\": 1, /* mid note */ \"u\": \"http://x/y\"\n}\n",
)
.expect("commented json parses");
let map = doc.as_map().expect("map");
assert_eq!(map.get("a").expect("key").as_i64(), Some(1));
assert_eq!(map.get("u").expect("key").as_str(), Some("http://x/y"));
assert!(load_json_value("{\"a\": 1} // trailing note").is_ok());
assert!(load_json_value("{\"a\": 1, /* unterminated").is_err());
}
#[test]
fn json_comment_stripping_preserves_error_columns() {
let src = "{\"a\": 1 /* note */, bad}";
let stripped = strip_json_comments(src);
assert_eq!(stripped.len(), src.len(), "columns hold: {stripped:?}");
let err = load_json_value(src).expect_err("bad key must fail");
assert!(
format!("{err:#}").contains("line 1 column 21"),
"error names the original column: {err:#}"
);
let lined = "{\n \"a\": 1,\n // note\n bad\n}";
let lined_stripped = strip_json_comments(lined);
assert_eq!(lined_stripped.len(), lined.len());
let err = load_json_value(lined).expect_err("bad key must fail");
assert!(
format!("{err:#}").contains("line 4 column 3"),
"error names the original line: {err:#}"
);
}
#[test]
fn merge_maps_layers_in_order() {
use std::collections::BTreeMap;
let mut base_entries = BTreeMap::new();
base_entries.insert("a".to_string(), Value::string("1".to_string()));
let mut overlay_entries = BTreeMap::new();
overlay_entries.insert("b".to_string(), Value::string("2".to_string()));
overlay_entries.insert("c".to_string(), Value::int(3));
let merged = merge_maps_from_value(
Value::list(vec![Value::map(base_entries), Value::map(overlay_entries)]),
"overwrite".to_string(),
)
.expect("merge")
.as_map()
.expect("map")
.clone();
assert_eq!(merged.get("a").expect("a").as_str(), Some("1"));
assert_eq!(merged.get("c").expect("c").as_i64(), Some(3));
}
#[test]
fn merge_maps_fail_on_duplicate_names_the_key() {
use std::collections::BTreeMap;
let mut first_entries = BTreeMap::new();
first_entries.insert("name".to_string(), Value::string("base".to_string()));
let mut second_entries = BTreeMap::new();
second_entries.insert("name".to_string(), Value::string("overlay".to_string()));
let err = merge_maps_from_value(
Value::list(vec![Value::map(first_entries), Value::map(second_entries)]),
"fail_on_duplicate".to_string(),
)
.expect_err("duplicate must fail");
assert!(
format!("{err:#}").contains("name"),
"error names the key: {err:#}"
);
}
#[test]
fn merge_maps_rejects_bad_shapes() {
assert!(
merge_maps_from_value(Value::string("nope".to_string()), "overwrite".to_string())
.is_err(),
"non LIST fails",
);
for (element, word) in [
(Value::int(1), "INT"),
(Value::string("nope".to_string()), "STRING"),
(Value::list(vec![Value::int(1)]), "LIST"),
(Value::bool(true), "BOOL"),
] {
let err = merge_maps_from_value(Value::list(vec![element]), "overwrite".to_string())
.expect_err("non MAP element must fail");
let text = format!("{err:#}");
assert!(
text.contains("element 0") && text.contains(word),
"error names position and offending shape: {text}"
);
}
}
#[test]
fn rand_draws_stay_in_unit_interval() {
for _ in 0..1000 {
let draw = rand_float_from_value(None)
.expect("draw")
.as_f64()
.expect("float");
assert!((0.0..1.0).contains(&draw), "draw out of [0, 1): {draw}");
}
}
#[test]
fn rand_seed_is_deterministic() {
let first = rand_float_from_value(Some(7))
.expect("seeded")
.as_f64()
.expect("float");
let second = rand_float_from_value(Some(7))
.expect("seeded")
.as_f64()
.expect("float");
assert_eq!(first, second, "same seed draws the same value");
assert!(
(0.0..1.0).contains(&first),
"seeded draw out of [0, 1): {first}"
);
}
#[test]
fn base64_round_trips_standard_alphabet() {
let encoded = base64_encode_from_value(Value::string("hello".to_string()))
.expect("encode")
.as_str()
.expect("string")
.to_string();
assert_eq!(encoded, "aGVsbG8=");
let decoded = base64_decode_from_value(Value::string(encoded))
.expect("decode")
.as_str()
.expect("string")
.to_string();
assert_eq!(decoded, "hello");
assert!(base64_decode_from_value(Value::string("!!!".to_string())).is_err());
assert!(base64_encode_from_value(Value::int(1)).is_err());
assert!(base64_decode_from_value(Value::int(1)).is_err());
}
#[test]
fn to_json_sorts_keys_and_appends_newline() {
use std::collections::BTreeMap;
let mut entries = BTreeMap::new();
entries.insert("b".to_string(), Value::int(2));
entries.insert(
"a".to_string(),
Value::list(vec![Value::string("x".to_string()), Value::bool(true)]),
);
let encoded = to_json_from_value(Value::map(entries))
.expect("encode")
.as_str()
.expect("string")
.to_string();
assert_eq!(encoded, "{\"a\":[\"x\",true],\"b\":2}\n");
assert_eq!(
to_json_from_value(Value::handle(1))
.expect("handles project")
.as_str()
.expect("string"),
"{\"task_id\":1}\n"
);
}
#[test]
fn apply_arith_int_and_errors() {
assert_eq!(
apply_arith(ArithOp::Add, Value::int(2), Value::int(3)).unwrap(),
Value::int(5)
);
assert!(apply_arith(ArithOp::Div, Value::int(1), Value::int(0)).is_err());
assert!(
apply_arith(ArithOp::Add, Value::int(i64::MAX), Value::int(1)).is_err(),
"int overflow must bail"
);
assert!(
apply_arith(ArithOp::Add, Value::string("a".to_string()), Value::int(1)).is_err(),
"string arithmetic must be a Type Error"
);
assert!(apply_neg(Value::int(i64::MIN)).is_err());
}
#[test]
fn apply_arith_float_promotion() {
assert_eq!(
apply_arith(ArithOp::Add, Value::int(1), Value::float(2.5)).unwrap(),
Value::float(3.5)
);
assert!(apply_arith(ArithOp::Div, Value::float(1.0), Value::float(0.0)).is_err());
}
#[test]
fn apply_compare_numeric_and_fallback() {
assert_eq!(
apply_compare(CompareOp::Eq, &Value::int(1), &Value::float(1.0)).unwrap(),
Value::bool(true)
);
assert_eq!(
apply_compare(CompareOp::Lt, &Value::int(3), &Value::float(4.5)).unwrap(),
Value::bool(true)
);
assert_eq!(
apply_compare(
CompareOp::Eq,
&Value::string("a".to_string()),
&Value::string("a".to_string())
)
.unwrap(),
Value::bool(true)
);
assert!(
apply_compare(
CompareOp::Lt,
&Value::string("a".to_string()),
&Value::string("b".to_string())
)
.is_err(),
"ordering on strings must bail"
);
}
#[test]
fn int_float_conversions() {
assert_eq!(
int_from_value(Value::string(" 123\n".to_string())).unwrap(),
Value::int(123)
);
assert_eq!(int_from_value(Value::float(3.0)).unwrap(), Value::int(3));
assert!(int_from_value(Value::float(3.5)).is_err());
assert!(int_from_value(Value::string("abc".to_string())).is_err());
assert_eq!(int_from_value(Value::bool(true)).unwrap(), Value::int(1));
assert_eq!(int_from_value(Value::bool(false)).unwrap(), Value::int(0));
assert_eq!(
float_from_value(Value::string("2.5".to_string())).unwrap(),
Value::float(2.5)
);
assert_eq!(float_from_value(Value::int(3)).unwrap(), Value::float(3.0));
for bad in ["nan", "inf", "-inf", "abc"] {
assert!(
float_from_value(Value::string(bad.to_string())).is_err(),
"{bad:?} must fail"
);
}
}
#[test]
fn coerce_value_coerces_union_members_in_order() {
use oxdock_parser::union_tag;
let union = union_tag!(Int, Float);
assert_eq!(union.name(), "INT|FLOAT");
assert_eq!(
coerce_value(Value::int(7), &union)
.expect("int passes")
.as_i64(),
Some(7)
);
let err = coerce_value(Value::string("123".to_string()), &union).expect_err("string fails");
assert!(
format!("{err:#}").contains("expected INT|FLOAT"),
"names the set: {err:#}"
);
let mixed = union_tag!(Float, String);
assert_eq!(
coerce_value(Value::int(10), &mixed)
.expect("int coerces")
.as_f64(),
Some(10.0)
);
let err = coerce_value(Value::bool(true), &union).expect_err("bool fails");
assert!(
format!("{err:#}").contains("expected INT|FLOAT"),
"names the set: {err:#}"
);
}
#[test]
fn text_helpers_cover_table_ops() {
assert_eq!(text_trim_str(" hello "), "hello");
assert_eq!(text_trim_prefix_str("v1.2.3", "v"), "1.2.3");
assert_eq!(text_trim_prefix_str("1.2.3", "v"), "1.2.3");
assert_eq!(text_trim_suffix_str("archive.tar.gz", ".gz"), "archive.tar");
assert_eq!(text_trim_suffix_str("archive.tar", ".gz"), "archive.tar");
assert_eq!(text_split_str("a,b,c", ","), vec!["a", "b", "c"]);
assert_eq!(text_split_str("ab", ""), vec!["a", "b"]);
assert_eq!(text_fields_str(" abc def "), vec!["abc", "def"]);
assert_eq!(
text_lines_str("one\ntwo\nthree"),
vec!["one", "two", "three"]
);
assert_eq!(
text_lines_str("one\r\ntwo\r\nthree"),
vec!["one", "two", "three"]
);
assert_eq!(
text_lines_str("one\rtwo\rthree"),
vec!["one", "two", "three"]
);
assert_eq!(text_lines_str("a\r\nb\nc\rd"), vec!["a", "b", "c", "d"]);
assert_eq!(
text_replace_literal_str("hello world", "world", "there", "TEXT_REPLACE")
.expect("replace"),
"hello there"
);
assert!(
text_replace_literal_str("hello", "", "x", "TEXT_REPLACE").is_err(),
"empty search strings must fail closed"
);
assert_eq!(
text_replace_regex_str(
"2026-10-13",
"(\\d+)-(\\d+)-(\\d+)",
"$3/$2/$1",
"TEXT_REPLACE_REGEX"
)
.expect("regex replace"),
"13/10/2026"
);
assert_eq!(trailing_incomplete_len("abc".as_bytes()), 0);
assert_eq!(trailing_incomplete_len("é".as_bytes()), 0);
assert_eq!(trailing_incomplete_len(&[0xC3]), 1);
assert_eq!("héllo".chars().count(), 5);
assert_eq!(
text_count_str("hello world", "o", "TEXT_COUNT").expect("count"),
2
);
assert_eq!(text_count_str("aaa", "aa", "TEXT_COUNT").expect("once"), 1);
assert!(text_count_str("aaa", "", "TEXT_COUNT").is_err());
assert_eq!(
text_count_matches_str("test a: test\ntest b: nope", ": test", "TEXT_COUNT_MATCHES")
.expect("count matches"),
1
);
assert_eq!(
text_count_matches_str("a\r\nb\nc", "^[ab]$", "TEXT_COUNT_MATCHES")
.expect("universal lines"),
2
);
assert_eq!(
text_grep_str("one\ntwo\none more", "^one", false, "TEXT_GREP").expect("grep"),
vec!["one", "one more"]
);
assert!(
text_grep_str("one\ntwo", "^z", false, "TEXT_GREP")
.expect("miss")
.is_empty()
);
assert_eq!(
text_grep_str("one\ntwo\none more", "^one", true, "TEXT_GREP").expect("invert"),
vec!["two"]
);
assert!(
text_grep_str("one\ntwo", "^", true, "TEXT_GREP")
.expect("invert match-all")
.is_empty()
);
let first = text_compile_pattern("TEXT_MATCH", "\\d+").expect("compile");
let second = text_compile_pattern("TEXT_MATCH", "\\d+").expect("cached");
assert_eq!(first.as_str(), second.as_str());
assert_eq!(
text_lines_range_str("one\ntwo\nthree\nfour", 2, 3, "TEXT_LINES_RANGE")
.expect("window"),
vec!["two", "three"]
);
assert_eq!(
text_lines_range_str("one\ntwo", 2, 9, "TEXT_LINES_RANGE").expect("clamp"),
vec!["two"]
);
assert!(
text_lines_range_str("one\ntwo", 9, 12, "TEXT_LINES_RANGE")
.expect("past end")
.is_empty()
);
assert!(text_lines_range_str("one", 0, 2, "TEXT_LINES_RANGE").is_err());
assert!(text_lines_range_str("one", 3, 2, "TEXT_LINES_RANGE").is_err());
assert_eq!(
text_extract_str("abc123", "([a-z]+)(\\d+)", "TEXT_EXTRACT").expect("extract"),
vec!["abc123", "abc", "123"]
);
assert!(
text_extract_str("abc", "^\\d+$", "TEXT_EXTRACT")
.expect("miss")
.is_empty()
);
assert!(text_compile_pattern("TEXT_MATCH", "([").is_err());
assert_eq!(
text_list_value(vec!["a".to_string()])
.as_list()
.expect("list")
.len(),
1
);
}
fn pump_to_string(pump: TextPump, chunks: &[&[u8]]) -> String {
use std::sync::Arc;
let spill = Arc::new(SpillBuffer::new());
let writer = spill.writer();
let mut state = TextPumpState::new(pump);
for chunk in chunks {
state.push(chunk, &writer).expect("pump push runs");
}
state.flush(&writer).expect("pump flush runs");
let out = spill.drain_bytes().expect("spill drains");
String::from_utf8(out).expect("pump output is UTF-8")
}
#[test]
fn text_pump_streams_case_across_char_cuts() {
let out = pump_to_string(TextPump::ToUpper, &[&[0xC3], &[0xA9]]);
assert_eq!(out, "É");
let out = pump_to_string(TextPump::ToLower, &[b"HE", b"LLO"]);
assert_eq!(out, "hello");
use std::sync::Arc;
let spill = Arc::new(SpillBuffer::new());
let writer = spill.writer();
let mut state = TextPumpState::new(TextPump::ToUpper);
state.push(b"ok", &writer).expect("valid prefix writes");
assert!(state.push(&[0xFF], &writer).is_err());
}
#[test]
fn text_pump_trims_edges_streaming() {
let out = pump_to_string(TextPump::Trim, &[b" hel", b"lo ", b" "]);
assert_eq!(out, "hello");
let out = pump_to_string(TextPump::Trim, &[b" a b "]);
assert_eq!(out, "a b");
let out = pump_to_string(TextPump::Trim, &[b" ", b"\n\t "]);
assert_eq!(out, "");
}
#[test]
fn text_pump_prefix_decides_once_at_head() {
let out = pump_to_string(TextPump::TrimPrefix("v".to_string()), &[b"v", b"1.2.3"]);
assert_eq!(out, "1.2.3");
let out = pump_to_string(TextPump::TrimPrefix("v".to_string()), &[b"1", b".2"]);
assert_eq!(out, "1.2");
let out = pump_to_string(TextPump::TrimPrefix("ab".to_string()), &[b"ababa"]);
assert_eq!(out, "aba");
}
#[test]
fn text_pump_suffix_holds_trailing_window() {
let out = pump_to_string(
TextPump::TrimSuffix(".gz".to_string()),
&[b"archive.tar", b".g", b"z"],
);
assert_eq!(out, "archive.tar");
let out = pump_to_string(TextPump::TrimSuffix(".gz".to_string()), &[b"archive.tar"]);
assert_eq!(out, "archive.tar");
let out = pump_to_string(TextPump::TrimSuffix(".gz".to_string()), &[b"ab"]);
assert_eq!(out, "ab");
}
#[test]
fn text_pump_replace_spans_chunk_cuts() {
let out = pump_to_string(
TextPump::ReplaceLiteral {
from: "world".to_string(),
to: "there".to_string(),
},
&[b"hello wo", b"rld and world"],
);
assert_eq!(out, "hello there and there");
let out = pump_to_string(
TextPump::ReplaceLiteral {
from: "a".to_string(),
to: "b".to_string(),
},
&[b"aaa", b"aa"],
);
assert_eq!(out, "bbbbb");
}
}