use std::collections::HashMap;
use anyhow::{Result, bail};
use oxdock_parser::{
CompareOp, Expr, GuardExpr, IoBinding, MathOp, PipeTarget, Step, StepKind, TypeTag, Value,
render_structural,
};
use oxdock_process::ProcessManager;
use super::{ExecState, FuncMeta, FuncParam, required_arity};
pub const MAX_STATIC_DEPTH: usize = 64;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum GuardClass {
Unconditional,
Conditional,
Dead,
}
#[derive(Clone, Debug)]
enum StaticTy {
Ty(TypeTag),
Void,
}
#[derive(Clone)]
struct FuncInfo {
params: Vec<(String, TypeTag)>,
body: Vec<Step>,
}
#[derive(Clone, Debug)]
struct Binding {
tag: TypeTag,
guard: Option<GuardExpr>,
}
#[derive(Clone, Default, Debug)]
struct Env {
frames: Vec<HashMap<String, Vec<Binding>>>,
}
#[derive(Clone, Debug)]
enum RetCtx {
Top,
Func(String),
Block,
AsyncValue,
AsyncStmt,
}
#[derive(Clone)]
struct Scope<'x> {
label: &'x str,
ret: RetCtx,
loops: usize,
site: Option<GuardExpr>,
}
struct Checker<'a, P: ProcessManager> {
exec: &'a ExecState<P>,
funcs: HashMap<String, FuncInfo>,
hosts: HashMap<String, FuncMeta>,
inferred: HashMap<String, StaticTy>,
inferring: Vec<String>,
visits: u64,
}
pub fn validate_script_types<P: ProcessManager>(steps: &[Step], exec: &ExecState<P>) -> Result<()> {
let mut checker = Checker::new(exec);
checker.collect(steps)?;
checker.check_top_level(steps)?;
for key in checker.func_keys() {
checker.func_return(&key, 0)?;
}
Ok(())
}
#[cfg(test)]
pub fn validate_script_types_counted<P: ProcessManager>(
steps: &[Step],
exec: &ExecState<P>,
) -> Result<u64> {
let mut checker = Checker::new(exec);
checker.collect(steps)?;
checker.check_top_level(steps)?;
for key in checker.func_keys() {
checker.func_return(&key, 0)?;
}
Ok(checker.visits)
}
pub(super) fn tags_equal(left: &TypeTag, right: &TypeTag) -> bool {
if std::mem::discriminant(left) != std::mem::discriminant(right) {
return false;
}
match left {
TypeTag::String
| TypeTag::Int
| TypeTag::Float
| TypeTag::Bool
| TypeTag::List
| TypeTag::Map
| TypeTag::Pipe
| TypeTag::Handle
| TypeTag::Duration
| TypeTag::Path
| TypeTag::Semaphore
| TypeTag::Permit
| TypeTag::Any => true,
TypeTag::Custom(a) => {
let TypeTag::Custom(b) = right else {
return false;
};
std::ptr::eq(*a, *b)
}
TypeTag::ListOf(a) => {
let TypeTag::ListOf(b) = right else {
return false;
};
tags_equal(a, b)
}
TypeTag::MapOf(a) => {
let TypeTag::MapOf(b) = right else {
return false;
};
tags_equal(a, b)
}
TypeTag::Record(a) => {
let TypeTag::Record(b) = right else {
return false;
};
std::sync::Arc::ptr_eq(a, b)
}
TypeTag::Union(_, a) => {
let TypeTag::Union(_, b) = right else {
return false;
};
a.len() == b.len()
&& a.iter()
.all(|member| b.iter().any(|other| tags_equal(member, other)))
}
}
}
fn coercible_pair(actual: &TypeTag, expected: &TypeTag) -> bool {
matches!(
(actual, expected),
(TypeTag::String, TypeTag::Bool)
| (TypeTag::String, TypeTag::Duration)
| (TypeTag::String, TypeTag::Path)
| (TypeTag::Int, TypeTag::String)
| (TypeTag::Int, TypeTag::Float)
| (TypeTag::Float, TypeTag::String)
| (TypeTag::Bool, TypeTag::String)
| (TypeTag::Duration, TypeTag::String)
| (TypeTag::Path, TypeTag::String)
| (TypeTag::ListOf(_), TypeTag::List)
| (TypeTag::List, TypeTag::ListOf(_))
| (TypeTag::Record(_), TypeTag::Map)
| (TypeTag::MapOf(_), TypeTag::Map)
| (TypeTag::Map, TypeTag::MapOf(_))
)
}
fn exact_mismatch(ctx: &str, expected: &TypeTag, actual: &TypeTag) -> anyhow::Error {
anyhow::anyhow!(
"{ctx}: TypeMismatch: expected {}, got {}",
render_structural(expected),
render_structural(actual)
)
}
fn is_maplike(tag: &TypeTag) -> bool {
matches!(tag, TypeTag::Map | TypeTag::Record(_) | TypeTag::MapOf(_))
}
fn is_listlike(tag: &TypeTag) -> bool {
matches!(tag, TypeTag::List | TypeTag::ListOf(_))
}
fn unify(left: TypeTag, right: TypeTag, ctx: &str) -> Result<TypeTag> {
if tags_equal(&left, &right) {
return Ok(left);
}
if matches!(left, TypeTag::Any) || matches!(right, TypeTag::Any) {
return Ok(TypeTag::Any);
}
if matches!(left, TypeTag::Union(..)) || matches!(right, TypeTag::Union(..)) {
return Ok(TypeTag::Any);
}
if matches!(
(&left, &right),
(TypeTag::ListOf(_), TypeTag::List) | (TypeTag::List, TypeTag::ListOf(_))
) {
return Ok(TypeTag::List);
}
if matches!(
(&left, &right),
(TypeTag::Record(_), TypeTag::Map)
| (TypeTag::Map, TypeTag::Record(_))
| (TypeTag::Record(_), TypeTag::MapOf(_))
| (TypeTag::MapOf(_), TypeTag::Record(_))
| (TypeTag::MapOf(_), TypeTag::Map)
| (TypeTag::Map, TypeTag::MapOf(_))
) {
return Ok(TypeTag::Map);
}
bail!(
"{ctx}: cannot unify {} and {}",
render_structural(&left),
render_structural(&right)
);
}
fn classify_guard(guard: Option<&GuardExpr>) -> GuardClass {
match guard {
None => GuardClass::Unconditional,
Some(expr) => {
if !oxdock_parser::guard_satisfiable(expr) {
GuardClass::Dead
} else if oxdock_parser::guard_valid(expr) {
GuardClass::Unconditional
} else {
GuardClass::Conditional
}
}
}
}
fn clean_var(name: &str) -> String {
name.trim_start_matches('$').to_string()
}
fn base_name(name: &str) -> &str {
name.rsplit("::").next().unwrap_or(name)
}
fn loc(at: Option<&str>) -> String {
at.map(|s| format!("{s}: ")).unwrap_or_default()
}
struct Callee {
params: Option<Vec<(String, TypeTag)>>,
ret: StaticTy,
host_params: Option<Vec<FuncParam>>,
}
struct WalkOut {
falls_through: bool,
has_return: bool,
types: Vec<TypeTag>,
}
impl Env {
fn one_frame(bindings: Vec<(String, TypeTag)>) -> Self {
let mut top = HashMap::new();
for (name, tag) in bindings {
top.insert(name, vec![Binding { tag, guard: None }]);
}
Self { frames: vec![top] }
}
fn fork(&self) -> Self {
let mut fork = self.clone();
fork.frames.push(HashMap::new());
fork
}
fn read_guarded(&self, key: &str, site: Option<&GuardExpr>) -> Result<TypeTag> {
Ok(self.read_entry_guarded(key, site)?.0)
}
fn read_entry_guarded(
&self,
key: &str,
site: Option<&GuardExpr>,
) -> Result<(TypeTag, Option<GuardExpr>)> {
for frame in self.frames.iter().rev() {
if let Some(entries) = frame.get(key) {
let live: Vec<&Binding> = entries
.iter()
.filter(|entry| oxdock_parser::guards_overlap(entry.guard.as_ref(), site))
.collect();
if live.is_empty() {
bail!("undefined variable ${key}");
}
let any_bare = live.iter().any(|entry| entry.guard.is_none());
if !any_bare {
let mut atoms: Vec<GuardExpr> = Vec::new();
if let Some(site_expr) = site {
atoms.push(site_expr.clone());
}
for entry in &live {
if let Some(guard) = entry.guard.as_ref() {
atoms.push(GuardExpr::Not(Box::new(guard.clone())));
}
}
if oxdock_parser::guard_satisfiable(&GuardExpr::All(atoms)) {
bail!(
"variable '${key}' is not guaranteed to be defined on all reachable paths for this step"
);
}
}
let mut unified: Option<TypeTag> = None;
let mut union: Option<GuardExpr> = None;
for entry in live {
unified = Some(match unified {
None => entry.tag.clone(),
Some(acc) => unify(
acc,
entry.tag.clone(),
&format!("${key} across platform guards"),
)?,
});
union = match (union, entry.guard.clone()) {
(None, None) => None,
(Some(g), None) | (None, Some(g)) => Some(g),
(Some(g1), Some(g2)) => Some(GuardExpr::Or(vec![g1, g2])),
};
}
let guard = match (site.cloned(), union) {
(None, union) => union,
(Some(site), None) => Some(site),
(Some(site), Some(union)) => Some(GuardExpr::All(vec![site, union])),
};
return Ok((unified.expect("live never empty"), guard));
}
}
bail!("undefined variable ${key}");
}
fn is_declared(&self, key: &str) -> bool {
self.frames
.iter()
.rev()
.any(|frame| frame.contains_key(key))
}
fn declare(
&mut self,
key: String,
tag: TypeTag,
guard: Option<&GuardExpr>,
idx: usize,
) -> Result<()> {
if let Some(frame) = self.frames.last()
&& let Some(entries) = frame.get(&key)
{
for entry in entries {
if oxdock_parser::guards_overlap(entry.guard.as_ref(), guard) {
bail!(
"step {}: redeclaration error: ${key} already declared in this scope; \
use ${key} = ... to mutate",
idx + 1
);
}
}
}
if let Some(frame) = self.frames.last_mut() {
frame.entry(key).or_default().push(Binding {
tag,
guard: guard.cloned(),
});
}
Ok(())
}
fn insert_top(&mut self, key: String, tag: TypeTag, guard: Option<&GuardExpr>) {
if let Some(frame) = self.frames.last_mut() {
frame.insert(
key,
vec![Binding {
tag,
guard: guard.cloned(),
}],
);
}
}
}
impl<'a, P: ProcessManager> Checker<'a, P> {
fn new(exec: &'a ExecState<P>) -> Self {
let mut hosts = HashMap::new();
for meta in exec.functions.all_metas() {
hosts.insert(meta.name.clone(), meta);
}
Self {
exec,
funcs: HashMap::new(),
hosts,
inferred: HashMap::new(),
inferring: Vec::new(),
visits: 0,
}
}
fn func_keys(&self) -> Vec<String> {
self.funcs.keys().cloned().collect()
}
fn collect(&mut self, steps: &[Step]) -> Result<()> {
for step in steps {
if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
continue;
}
self.collect_step(step)?;
}
Ok(())
}
fn collect_step(&mut self, step: &Step) -> Result<()> {
match &step.kind {
StepKind::FuncDef { name, params, body } => {
let mut resolved = Vec::with_capacity(params.len());
for (pname, ptype) in params {
let tag = self
.exec
.resolve_tag(ptype)
.map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
resolved.push((clean_var(pname), tag));
}
let info = FuncInfo {
params: resolved,
body: body.clone(),
};
self.funcs.insert(name.clone(), info);
self.funcs.insert(
format!("SCRIPT::{name}"),
FuncInfo {
params: self.funcs[name].params.clone(),
body: self.funcs[name].body.clone(),
},
);
let nested = self.funcs[name].body.clone();
self.collect(&nested)?;
}
StepKind::If {
then_body,
else_ifs,
else_body,
..
} => {
self.collect(then_body)?;
for (_, arm) in else_ifs {
self.collect(arm)?;
}
if let Some(arm) = else_body {
self.collect(arm)?;
}
}
StepKind::For { body, .. } | StepKind::While { body, .. } => {
self.collect(body)?;
}
StepKind::AsyncBlock { body } => self.collect(body)?,
_ => {}
}
Ok(())
}
fn check_top_level(&mut self, steps: &[Step]) -> Result<()> {
let mut env = Env::one_frame(Vec::new());
let scope = Scope {
label: "top level",
ret: RetCtx::Top,
loops: 0,
site: None,
};
let out = self.walk_body(steps, &mut env, &scope, 0)?;
let _ = out;
Ok(())
}
fn func_return(&mut self, key: &str, depth: usize) -> Result<StaticTy> {
if let Some(known) = self.inferred.get(key) {
return Ok(known.clone());
}
if self.inferring.iter().any(|name| name == key) {
return Ok(StaticTy::Ty(TypeTag::Any));
}
let info = self.funcs.get(key).cloned();
let Some(info) = info else {
return Ok(StaticTy::Ty(TypeTag::Any));
};
self.inferring.push(key.to_string());
let result = self.check_function_body(key, &info, depth);
self.inferring.pop();
let ty = result?;
self.inferred.insert(key.to_string(), ty.clone());
Ok(ty)
}
fn check_function_body(
&mut self,
key: &str,
info: &FuncInfo,
depth: usize,
) -> Result<StaticTy> {
if depth > MAX_STATIC_DEPTH {
bail!("static analysis depth exceeded in function `{key}`");
}
let mut env = Env::one_frame(info.params.clone());
let scope = Scope {
label: key,
ret: RetCtx::Func(key.to_string()),
loops: 0,
site: None,
};
let out = self.walk_body(&info.body, &mut env, &scope, depth + 1)?;
if out.has_return && out.falls_through {
bail!(
"function `{key}` may fall through with no RETURN on some path; \
add an unconditional RETURN or EXIT"
);
}
if !out.has_return {
return Ok(StaticTy::Void);
}
let mut unified: Option<TypeTag> = None;
for ty in out.types {
unified = Some(match unified {
None => ty,
Some(acc) => unify(acc, ty, &format!("function `{key}`"))?,
});
}
Ok(StaticTy::Ty(unified.expect("has_return implies a type")))
}
#[allow(clippy::too_many_lines)]
fn walk_body(
&mut self,
steps: &[Step],
env: &mut Env,
scope: &Scope,
depth: usize,
) -> Result<WalkOut> {
if depth > MAX_STATIC_DEPTH {
bail!("static analysis depth exceeded in `{}`", scope.label);
}
let base_frames = env.frames.len();
let mut out = WalkOut {
falls_through: true,
has_return: false,
types: Vec::new(),
};
for (idx, step) in steps.iter().enumerate() {
self.visits += 1;
let scoped = Scope {
label: scope.label,
ret: scope.ret.clone(),
loops: scope.loops,
site: step.guard.clone(),
};
let scope = &scoped;
for _ in 0..step.scope_enter {
env.frames.push(HashMap::new());
}
match classify_guard(step.guard.as_ref()) {
GuardClass::Dead => {}
GuardClass::Conditional => {
let inner = self.walk_step(step, env, scope, idx, depth)?;
out.has_return |= inner.has_return;
out.types.extend(inner.types);
}
GuardClass::Unconditional => {
let inner = self.walk_step(step, env, scope, idx, depth)?;
out.has_return |= inner.has_return;
out.types.extend(inner.types);
if !inner.falls_through {
out.falls_through = false;
return Ok(out);
}
}
}
for _ in 0..step.scope_exit {
if env.frames.len() > base_frames {
env.frames.pop();
}
}
}
Ok(out)
}
fn walk_step(
&mut self,
step: &Step,
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<WalkOut> {
let live = WalkOut {
falls_through: true,
has_return: false,
types: Vec::new(),
};
match &step.kind {
StepKind::Return { expr } => {
match &scope.ret {
RetCtx::Func(_) | RetCtx::Block | RetCtx::AsyncValue => {}
RetCtx::Top => {
bail!(
"step {}: RETURN outside function, ASYNC task, or LET block",
idx + 1
);
}
RetCtx::AsyncStmt => {
bail!("step {}: RETURN cannot cross ASYNC boundary", idx + 1);
}
}
let ty = self.infer_expr(expr, env, scope, idx, depth + 1)?;
let mut out = live;
out.has_return = true;
out.falls_through = false;
if let StaticTy::Ty(tag) = ty {
out.types.push(tag);
}
Ok(out)
}
StepKind::Break => self.walk_break("BREAK", scope, idx),
StepKind::Continue => self.walk_break("CONTINUE", scope, idx),
StepKind::Exit(_) => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
Ok(WalkOut {
falls_through: false,
has_return: false,
types: Vec::new(),
})
}
StepKind::If {
cond,
then_body,
else_ifs,
else_body,
} => {
self.infer_expr(cond, env, scope, idx, depth + 1)?;
let mut arms_terminal = true;
let mut out = live;
let mut arms = vec![then_body];
for (else_cond, arm) in else_ifs {
self.infer_expr(else_cond, env, scope, idx, depth + 1)?;
arms.push(arm);
}
for arm in arms {
let mut fork = env.fork();
let arm_out = self.walk_body(arm, &mut fork, scope, depth + 1)?;
out.has_return |= arm_out.has_return;
out.types.extend(arm_out.types);
arms_terminal &= !arm_out.falls_through;
}
match else_body {
Some(arm) => {
let mut fork = env.fork();
let arm_out = self.walk_body(arm, &mut fork, scope, depth + 1)?;
out.has_return |= arm_out.has_return;
out.types.extend(arm_out.types);
arms_terminal &= !arm_out.falls_through;
}
None => arms_terminal = false,
}
out.falls_through = !arms_terminal;
Ok(out)
}
StepKind::For {
key_var,
key_type,
var,
var_type,
in_expr,
body,
} => {
self.infer_expr(in_expr, env, scope, idx, depth + 1)?;
let val_tag = self
.exec
.resolve_tag(var_type)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
let mut fork = env.fork();
fork.insert_top(clean_var(var), val_tag, step.guard.as_ref());
if let Some(key) = key_var {
let key_tag = match key_type {
Some(name) => self
.exec
.resolve_tag(name)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?,
None => TypeTag::Int,
};
fork.insert_top(clean_var(key), key_tag, step.guard.as_ref());
}
let mut inner_scope = scope.clone();
inner_scope.loops += 1;
let body_out = self.walk_body(body, &mut fork, &inner_scope, depth + 1)?;
let mut out = live;
out.has_return = body_out.has_return;
out.types = body_out.types;
Ok(out)
}
StepKind::While { cond, body } => {
self.infer_expr(cond, env, scope, idx, depth + 1)?;
let mut fork = env.fork();
let mut inner_scope = scope.clone();
inner_scope.loops += 1;
let body_out = self.walk_body(body, &mut fork, &inner_scope, depth + 1)?;
let mut out = live;
out.has_return = body_out.has_return;
out.types = body_out.types;
Ok(out)
}
StepKind::FuncDef { name, params, body } => {
let mut resolved = Vec::with_capacity(params.len());
for (pname, ptype) in params {
let tag = self
.exec
.resolve_tag(ptype)
.map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
resolved.push((clean_var(pname), tag));
}
let info = FuncInfo {
params: resolved,
body: body.clone(),
};
self.check_function_body(name, &info, depth + 1)?;
Ok(live)
}
StepKind::Call { name, args } => {
self.check_call(name, args, env, scope, idx, depth + 1)?;
Ok(live)
}
StepKind::Assign {
var,
decl_type,
expr,
} => {
let rhs = self.infer_expr(expr, env, scope, idx, depth + 1)?;
if matches!(rhs, StaticTy::Void) {
bail!(
"step {}: VOID block has no value to bind to `${var}`",
idx + 1
);
}
let tag = self
.exec
.resolve_tag(decl_type)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
let key = clean_var(var);
env.declare(key, tag, step.guard.as_ref(), idx)?;
Ok(live)
}
StepKind::AssignCapture {
var,
decl_type,
cmd,
} => {
self.walk_wrapped(cmd, env, scope, idx, depth + 1)?;
let tag = self
.exec
.resolve_tag(decl_type)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
let key = clean_var(var);
env.declare(key, tag, step.guard.as_ref(), idx)?;
Ok(live)
}
StepKind::Set { var, expr } => {
let key = clean_var(var);
if !env.is_declared(&key) {
bail!(
"step {}: undeclared variable ${key}: declare it first with LET ${key}: TYPE = ...",
idx + 1
);
}
let _ = env.read_guarded(&key, scope.site.as_ref())?;
self.infer_expr(expr, env, scope, idx, depth + 1)?;
Ok(live)
}
StepKind::AwaitCapture {
out_var,
out_type,
task_var,
} => {
Self::check_name_read(env, task_var, scope, idx)?;
let tag = self
.exec
.resolve_tag(out_type)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
let key = clean_var(out_var);
env.declare(key, tag, step.guard.as_ref(), idx)?;
Ok(live)
}
StepKind::AsyncBlock { body } => {
let mut fork = env.fork();
let task = Scope {
label: scope.label,
ret: RetCtx::AsyncStmt,
loops: 0,
site: scope.site.clone(),
};
self.walk_body(body, &mut fork, &task, depth + 1)?;
Ok(live)
}
StepKind::AssignAsync {
var,
decl_type,
body,
} => {
let mut fork = env.fork();
let task = Scope {
label: scope.label,
ret: RetCtx::AsyncValue,
loops: 0,
site: scope.site.clone(),
};
self.walk_body(body, &mut fork, &task, depth + 1)?;
let tag = self
.exec
.resolve_tag(decl_type)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
let key = clean_var(var);
env.insert_top(key, tag, step.guard.as_ref());
Ok(live)
}
StepKind::Timeout { body, .. } => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
let inner = self.walk_body(body, env, scope, depth + 1)?;
let mut out = live;
out.has_return = inner.has_return;
out.types = inner.types;
out.falls_through = inner.falls_through;
if !inner.falls_through {
return Ok(out);
}
Ok(out)
}
StepKind::RemoteBlock {
target, vars, body, ..
} => {
let mut sealed = Env::one_frame(Vec::new());
for name in vars {
let key = clean_var(name);
let (tag, guard) =
env.read_entry_guarded(&key, step.guard.as_ref())
.map_err(|_| {
anyhow::anyhow!("REMOTE '{target}' uses unknown variable ${key}")
})?;
sealed.insert_top(key, tag, guard.as_ref());
}
sealed.frames.push(HashMap::new());
let remote = Scope {
label: scope.label,
ret: RetCtx::Top,
loops: 0,
site: None,
};
self.walk_body(body, &mut sealed, &remote, depth + 1)?;
Ok(live)
}
StepKind::WithIo { bindings, cmd } => {
Self::check_pipe_bindings(env, bindings, scope, idx)?;
self.walk_wrapped(cmd, env, scope, idx, depth + 1)
}
StepKind::ReadLine { var } => {
let key = clean_var(var);
if !env.is_declared(&key) {
env.insert_top(key, TypeTag::String, step.guard.as_ref());
}
Ok(live)
}
StepKind::Prompt { var, .. } => {
let key = clean_var(var);
if !env.is_declared(&key) {
env.insert_top(key, TypeTag::String, step.guard.as_ref());
}
Ok(live)
}
_ => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
match &step.kind {
StepKind::Await { var } | StepKind::Cancel { var } => {
Self::check_name_read(env, var, scope, idx)?;
}
StepKind::WithIoBlock { bindings } => {
Self::check_pipe_bindings(env, bindings, scope, idx)?;
}
StepKind::ListAppend { list, item } => {
let tag = Self::check_name_read(env, list, scope, idx)?;
let element = match tag {
TypeTag::List => None,
TypeTag::ListOf(element) => Some(element.as_ref().clone()),
TypeTag::String
| TypeTag::Int
| TypeTag::Float
| TypeTag::Bool
| TypeTag::Map
| TypeTag::Pipe
| TypeTag::Handle
| TypeTag::Duration
| TypeTag::Path
| TypeTag::Semaphore
| TypeTag::Permit
| TypeTag::Any
| TypeTag::Custom(_)
| TypeTag::MapOf(_)
| TypeTag::Record(_)
| TypeTag::Union(..) => bail!(
"step {}: LIST_APPEND ${}: variable is {}, not LIST",
idx + 1,
clean_var(list),
render_structural(&tag)
),
};
if let Some(expected) = element {
let actual = match item {
oxdock_parser::Arg::Expr(expr) => {
self.infer_expr(expr, env, scope, idx, depth + 1)?
}
_ => StaticTy::Ty(TypeTag::String),
};
let StaticTy::Ty(actual) = actual else {
bail!(
"step {}: LIST_APPEND ${}: VOID has no value to push",
idx + 1,
clean_var(list)
);
};
Self::check_exact(&expected, &actual, &format!("step {}", idx + 1))?;
}
}
_ => {}
}
Ok(live)
}
}
}
fn check_step_args(
&mut self,
kind: &StepKind,
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<()> {
let mut failed: Option<anyhow::Error> = None;
kind.walk_exprs(&mut |expr| {
if failed.is_none()
&& let Err(err) = self.infer_expr(expr, env, scope, idx, depth + 1)
{
failed = Some(err);
}
});
if let Some(err) = failed {
return Err(err);
}
Ok(())
}
fn check_name_read(env: &Env, name: &str, scope: &Scope, idx: usize) -> Result<TypeTag> {
let key = clean_var(name);
if !env.is_declared(&key) {
bail!("step {}: undefined variable ${key}", idx + 1);
}
env.read_guarded(&key, scope.site.as_ref())
}
fn check_pipe_bindings(
env: &Env,
bindings: &[IoBinding],
scope: &Scope,
idx: usize,
) -> Result<()> {
for binding in bindings {
if let Some(PipeTarget::Var(name)) = &binding.pipe {
let tag = Self::check_name_read(env, name, scope, idx)?;
if !tags_equal(&tag, &TypeTag::Pipe) {
bail!(
"step {}: TypeMismatch: expected PIPE, got {}",
idx + 1,
tag.name()
);
}
}
}
Ok(())
}
fn walk_break(&mut self, word: &str, scope: &Scope, idx: usize) -> Result<WalkOut> {
if scope.loops > 0 {
return Ok(WalkOut {
falls_through: true,
has_return: false,
types: Vec::new(),
});
}
match &scope.ret {
RetCtx::Top => bail!("step {}: {word} outside loop", idx + 1),
RetCtx::Func(name) => {
bail!(
"step {}: {word} cannot cross function boundary (in {name}())",
idx + 1
);
}
RetCtx::Block => {
bail!("step {}: {word} cannot cross block boundary", idx + 1);
}
RetCtx::AsyncValue | RetCtx::AsyncStmt => {
bail!("step {}: {word} cannot cross ASYNC boundary", idx + 1);
}
}
}
fn walk_wrapped(
&mut self,
cmd: &StepKind,
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<WalkOut> {
let step = Step {
guard: None,
kind: cmd.clone(),
scope_enter: 0,
scope_exit: 0,
};
self.walk_step(&step, env, scope, idx, depth)
}
fn check_arg(&mut self, expected: &TypeTag, actual: StaticTy, ctx: &str) -> Result<()> {
let StaticTy::Ty(actual) = actual else {
bail!("{ctx}: VOID has no value to pass");
};
if matches!(expected, TypeTag::Any) {
return Ok(());
}
if matches!(actual, TypeTag::Any) {
bail!(
"{ctx}: untyped ANY value flows into {} parameter; \
bind through LET $x: {} first",
render_structural(expected),
render_structural(expected)
);
}
if tags_equal(expected, &actual) {
return Ok(());
}
if let TypeTag::Union(_, members) = actual {
for member in members.iter() {
self.check_arg(expected, StaticTy::Ty((*member).clone()), ctx)?;
}
return Ok(());
}
if let TypeTag::Union(_, members) = expected {
for member in members.iter() {
if self
.check_arg(member, StaticTy::Ty(actual.clone()), ctx)
.is_ok()
{
return Ok(());
}
}
return Err(exact_mismatch(ctx, expected, &actual));
}
if coercible_pair(&actual, expected) {
return Ok(());
}
if matches!(
(&actual, expected),
(TypeTag::ListOf(_), TypeTag::ListOf(_))
| (TypeTag::MapOf(_), TypeTag::MapOf(_))
| (TypeTag::Record(_), TypeTag::Record(_))
| (TypeTag::Record(_), TypeTag::MapOf(_))
) {
return Self::check_exact(expected, &actual, ctx);
}
Err(exact_mismatch(ctx, expected, &actual))
}
fn check_exact(expected: &TypeTag, actual: &TypeTag, ctx: &str) -> Result<()> {
if tags_equal(expected, actual) {
return Ok(());
}
if matches!(expected, TypeTag::Any) || matches!(actual, TypeTag::Any) {
return Ok(());
}
match (actual, expected) {
(TypeTag::ListOf(a), TypeTag::ListOf(e)) | (TypeTag::MapOf(a), TypeTag::MapOf(e)) => {
Self::check_exact(e, a, ctx)
}
(TypeTag::Record(a_fields), TypeTag::Record(e_fields)) => {
for field in e_fields.iter() {
match a_fields.iter().find(|found| found.name == field.name) {
Some(found) => Self::check_exact(&field.ty, &found.ty, ctx)?,
None if field.optional => {}
None => bail!("{ctx}: missing field '{}'", field.name),
}
}
for field in a_fields.iter() {
if !e_fields.iter().any(|known| known.name == field.name) {
bail!("{ctx}: unknown field '{}'", field.name);
}
}
Ok(())
}
(TypeTag::Record(a_fields), TypeTag::MapOf(inner)) => {
for field in a_fields.iter() {
Self::check_exact(inner, &field.ty, ctx)?;
}
Ok(())
}
(TypeTag::ListOf(_), TypeTag::List)
| (TypeTag::Record(_), TypeTag::Map)
| (TypeTag::MapOf(_), TypeTag::Map) => Ok(()),
(TypeTag::Union(_, a_members), TypeTag::Union(_, e_members)) => {
if a_members.len() == e_members.len()
&& a_members.iter().all(|actual| {
e_members
.iter()
.any(|member| Self::check_exact(member, actual, ctx).is_ok())
})
{
Ok(())
} else {
Err(exact_mismatch(ctx, expected, actual))
}
}
(_, TypeTag::Union(_, e_members)) => {
if e_members
.iter()
.any(|member| Self::check_exact(member, actual, ctx).is_ok())
{
Ok(())
} else {
Err(exact_mismatch(ctx, expected, actual))
}
}
_ => Err(exact_mismatch(ctx, expected, actual)),
}
}
fn resolve_call(&mut self, name: &str, depth: usize) -> Result<Callee> {
if let Some(info) = self.funcs.get(name) {
let info = info.clone();
let ret = self.func_return_owned(&info, name, depth)?;
let params = info.params;
return Ok(Callee {
params: Some(params),
ret,
host_params: None,
});
}
if let Some(meta) = self.hosts.get(name) {
let meta = meta.clone();
let ret = meta
.returns
.map(StaticTy::Ty)
.unwrap_or(StaticTy::Ty(TypeTag::Any));
let params = meta.params.as_deref().map(|list| {
list.iter()
.map(|param| {
(
param.name.clone(),
param.param_type.clone().unwrap_or(TypeTag::Any),
)
})
.collect()
});
return Ok(Callee {
params,
ret,
host_params: meta.params.clone(),
});
}
Ok(Callee {
params: None,
ret: StaticTy::Ty(TypeTag::Any),
host_params: None,
})
}
fn func_return_owned(&mut self, info: &FuncInfo, key: &str, depth: usize) -> Result<StaticTy> {
if let Some(known) = self.inferred.get(key) {
return Ok(known.clone());
}
if self.inferring.iter().any(|name| name == key) {
return Ok(StaticTy::Ty(TypeTag::Any));
}
self.inferring.push(key.to_string());
let result = self.check_function_body(key, info, depth);
self.inferring.pop();
let ty = result?;
self.inferred.insert(key.to_string(), ty.clone());
Ok(ty)
}
fn check_call(
&mut self,
name: &str,
args: &[Expr],
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<StaticTy> {
let callee = self.resolve_call(name, depth)?;
let (required, total) = match callee.host_params.as_deref() {
Some(host) => (required_arity(host), host.len()),
None => match callee.params.as_deref() {
Some(shape) => (shape.len(), shape.len()),
None => (0, usize::MAX),
},
};
if args.len() < required || args.len() > total {
if required == total {
bail!(
"step {}: {}() expects {} argument(s), got {}",
idx + 1,
base_name(name),
total,
args.len()
);
}
bail!(
"step {}: {}() expects {} to {} argument(s), got {}",
idx + 1,
base_name(name),
required,
total,
args.len()
);
}
let mut tys = Vec::with_capacity(args.len());
let mut literals: Vec<Option<&str>> = Vec::with_capacity(args.len());
for arg in args.iter() {
let actual = self.infer_expr(arg, env, scope, idx, depth + 1)?;
let literal = match arg {
Expr::Literal(value) => value.as_str(),
_ => None,
};
tys.push(actual);
literals.push(literal);
}
self.apply_checked(
name,
&callee,
&tys,
&literals,
Some(&format!("step {}", idx + 1)),
)
}
fn apply_checked(
&mut self,
name: &str,
callee: &Callee,
arg_tys: &[StaticTy],
literals: &[Option<&str>],
at: Option<&str>,
) -> Result<StaticTy> {
let display = base_name(name);
let Callee {
params,
ret,
host_params,
} = callee;
let (required, total) = match host_params.as_deref() {
Some(host) => (required_arity(host), host.len()),
None => match params.as_deref() {
Some(shape) => (shape.len(), shape.len()),
None => (0, usize::MAX),
},
};
if arg_tys.len() < required || arg_tys.len() > total {
if required == total {
bail!(
"{}{display}() expects {} argument(s), got {}",
loc(at),
total,
arg_tys.len()
);
}
bail!(
"{}{display}() expects {} to {} argument(s), got {}",
loc(at),
required,
total,
arg_tys.len()
);
}
for (position, actual) in arg_tys.iter().enumerate() {
let Some(expected) = params.as_deref().and_then(|list| list.get(position)) else {
continue;
};
let (pname, ptype) = expected;
let pat = format!("{}{display}() argument `${pname}`", loc(at));
self.check_arg(ptype, (*actual).clone(), &pat)?;
if let Some(host_list) = host_params.as_deref()
&& let Some(param) = host_list.get(position)
&& let Some(allowed) = param.allowed
&& let Some(Some(text)) = literals.get(position)
&& !allowed.contains(text)
{
bail!("{pat} must be one of: {}, got {text:?}", allowed.join(", "));
}
}
match ret {
StaticTy::Void => Ok(StaticTy::Ty(TypeTag::String)),
other => Ok(other.clone()),
}
}
}
fn literal_tag(value: &Value) -> TypeTag {
TypeTag::builtin(value.type_name()).unwrap_or(TypeTag::Any)
}
fn numeric_pair(left: StaticTy, right: StaticTy, at: Option<&str>) -> Result<StaticTy> {
let (StaticTy::Ty(left), StaticTy::Ty(right)) = (left, right) else {
bail!("{}VOID has no value in arithmetic", loc(at));
};
if matches!(left, TypeTag::Any) || matches!(right, TypeTag::Any) {
return Ok(StaticTy::Ty(TypeTag::Any));
}
if matches!(
(&left, &right),
(TypeTag::Int, TypeTag::Int)
| (TypeTag::Int, TypeTag::Float)
| (TypeTag::Float, TypeTag::Int)
| (TypeTag::Float, TypeTag::Float)
) {
return Ok(StaticTy::Ty(
if matches!(left, TypeTag::Int) && matches!(right, TypeTag::Int) {
TypeTag::Int
} else {
TypeTag::Float
},
));
}
bail!("{}Type Error: arithmetic requires Int or Float", loc(at));
}
fn neg_rule(top: StaticTy, at: Option<&str>) -> Result<StaticTy> {
match top {
StaticTy::Ty(TypeTag::Int) => Ok(StaticTy::Ty(TypeTag::Int)),
StaticTy::Ty(TypeTag::Float) => Ok(StaticTy::Ty(TypeTag::Float)),
StaticTy::Ty(TypeTag::Any) => Ok(StaticTy::Ty(TypeTag::Any)),
StaticTy::Void => bail!("{}VOID has no value to negate", loc(at)),
StaticTy::Ty(other) => {
bail!(
"{}Type Error: unary '-' requires Int or Float, got {}",
loc(at),
other.name()
)
}
}
}
fn ordering_pair(left: StaticTy, right: StaticTy, at: Option<&str>) -> Result<()> {
let (StaticTy::Ty(left), StaticTy::Ty(right)) = (left, right) else {
bail!("{}VOID has no value to compare", loc(at));
};
if matches!(left, TypeTag::Any) || matches!(right, TypeTag::Any) {
return Ok(());
}
let numeric = |tag: &TypeTag| matches!(tag, TypeTag::Int | TypeTag::Float);
if numeric(&left) && numeric(&right) {
return Ok(());
}
bail!(
"{}Type Error: ordering comparison requires Int or Float",
loc(at)
);
}
impl<'a, P: ProcessManager> Checker<'a, P> {
fn infer_list_literal(
&mut self,
items: &[Expr],
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<StaticTy> {
let mut tags = Vec::with_capacity(items.len());
for item in items {
match self.infer_expr(item, env, scope, idx, depth + 1)? {
StaticTy::Ty(tag) => tags.push(tag),
StaticTy::Void => return Ok(StaticTy::Ty(TypeTag::List)),
}
}
let Some(first) = tags.first() else {
return Ok(StaticTy::Ty(TypeTag::List));
};
if matches!(first, TypeTag::Any) || !tags.iter().all(|tag| tags_equal(first, tag)) {
let join = if tags.iter().all(is_maplike) {
Some("LIST<MAP<ANY>>")
} else if tags.iter().all(is_listlike) {
Some("LIST<LIST<ANY>>")
} else {
None
};
let Some(spelling) = join else {
return Ok(StaticTy::Ty(TypeTag::List));
};
return Ok(self
.exec
.resolve_tag(spelling)
.map(StaticTy::Ty)
.unwrap_or(StaticTy::Ty(TypeTag::List)));
}
let spelling = format!("LIST<{}>", render_structural(first));
Ok(self
.exec
.resolve_tag(&spelling)
.map(StaticTy::Ty)
.unwrap_or(StaticTy::Ty(TypeTag::List)))
}
fn infer_map_literal(
&mut self,
entries: &[(String, Expr)],
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<StaticTy> {
let mut parts = Vec::with_capacity(entries.len());
for (key, value) in entries {
match self.infer_expr(value, env, scope, idx, depth + 1)? {
StaticTy::Ty(tag) => parts.push(format!("{key}: {}", render_structural(&tag))),
StaticTy::Void => return Ok(StaticTy::Ty(TypeTag::Map)),
}
}
if parts.is_empty() {
return Ok(StaticTy::Ty(TypeTag::Map));
}
let spelling = format!("MAP<{}>", parts.join(", "));
Ok(self
.exec
.resolve_tag(&spelling)
.map(StaticTy::Ty)
.unwrap_or(StaticTy::Ty(TypeTag::Map)))
}
fn infer_expr(
&mut self,
expr: &Expr,
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<StaticTy> {
if depth > MAX_STATIC_DEPTH {
bail!("static analysis depth exceeded in `{}`", scope.label);
}
self.visits += 1;
let at = || format!("step {}", idx + 1);
match expr {
Expr::Literal(value) => Ok(StaticTy::Ty(literal_tag(value))),
Expr::Var(name) => {
let key = clean_var(name);
if !env.is_declared(&key) {
bail!("{}undefined variable ${key}", loc(Some(&at())));
}
Ok(StaticTy::Ty(env.read_guarded(&key, scope.site.as_ref())?))
}
Expr::Env(_) => Ok(StaticTy::Ty(TypeTag::String)),
Expr::KeyPath { base, keys } => {
let key = clean_var(base);
if !env.is_declared(&key) {
bail!("{}undefined variable ${key}", loc(Some(&at())));
}
let mut current = env.read_guarded(&key, scope.site.as_ref())?;
for part in keys {
match current {
TypeTag::Record(fields) => {
let Some(field) = fields
.iter()
.find(|field| field.name.as_str() == part.as_str())
else {
bail!(
"{}: unknown field '{part}'; expected fields: {}",
at(),
fields
.iter()
.map(|field| field.name.as_str())
.collect::<Vec<_>>()
.join(", ")
);
};
current = field.ty.clone();
}
TypeTag::ListOf(element) => {
if part.parse::<usize>().is_err() {
bail!("{}: Invalid array index '{part}'", at());
}
current = element.as_ref().clone();
}
TypeTag::MapOf(values) => {
current = values.as_ref().clone();
}
TypeTag::Map | TypeTag::List | TypeTag::Any => {
return Ok(StaticTy::Ty(TypeTag::Any));
}
TypeTag::Union(_, members) => {
let traversable = |member: &TypeTag| {
matches!(
member,
TypeTag::Record(_)
| TypeTag::ListOf(_)
| TypeTag::MapOf(_)
| TypeTag::Map
| TypeTag::List
| TypeTag::Any
)
};
if members.iter().all(|member| !traversable(member)) {
bail!(
"{}: Cannot traverse into scalar value at key '{part}'",
at()
);
}
return Ok(StaticTy::Ty(TypeTag::Any));
}
_ => {
bail!(
"{}: Cannot traverse into scalar value at key '{part}'",
at()
);
}
}
}
Ok(StaticTy::Ty(current))
}
Expr::List(items) => self.infer_list_literal(items, env, scope, idx, depth),
Expr::Map(entries) => self.infer_map_literal(entries, env, scope, idx, depth),
Expr::Block(steps) => {
let mut fork = env.fork();
let out = self.walk_body(
steps,
&mut fork,
&Scope {
label: scope.label,
ret: RetCtx::Block,
loops: 0,
site: scope.site.clone(),
},
depth + 1,
)?;
if out.has_return && out.falls_through {
bail!(
"{}: block may fall through with no RETURN on some path",
at()
);
}
if !out.has_return {
return Ok(StaticTy::Void);
}
let mut unified: Option<TypeTag> = None;
for ty in out.types {
unified = Some(match unified {
None => ty,
Some(acc) => unify(acc, ty, &at())?,
});
}
Ok(StaticTy::Ty(unified.expect("has_return implies a type")))
}
Expr::Call { name, args } => self.check_call(name, args, env, scope, idx, depth),
Expr::Inspect(name) => {
let key = clean_var(name);
if !env.is_declared(&key) {
bail!("{}undefined variable ${key}", loc(Some(&at())));
}
env.read_guarded(&key, scope.site.as_ref())?;
Ok(StaticTy::Ty(TypeTag::Any))
}
Expr::Compare { op, left, right } => {
let left_ty = self.infer_expr(left, env, scope, idx, depth + 1)?;
let right_ty = self.infer_expr(right, env, scope, idx, depth + 1)?;
match op {
CompareOp::Eq | CompareOp::Ne => {}
CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => {
ordering_pair(left_ty, right_ty, Some(&at()))?;
}
}
Ok(StaticTy::Ty(TypeTag::Bool))
}
Expr::Arithmetic { left, right, .. } => {
let left_ty = self.infer_expr(left, env, scope, idx, depth + 1)?;
let right_ty = self.infer_expr(right, env, scope, idx, depth + 1)?;
numeric_pair(left_ty, right_ty, Some(&at()))
}
Expr::CompiledMath(ops) => self.infer_rpn(ops, env, scope, depth),
Expr::FreshPipe => Ok(StaticTy::Ty(TypeTag::Pipe)),
Expr::UnsignedIntBoundary(_) => Ok(StaticTy::Ty(TypeTag::Int)),
Expr::Not(inner) => {
self.infer_expr(inner, env, scope, idx, depth + 1)?;
Ok(StaticTy::Ty(TypeTag::Bool))
}
Expr::Logical { left, .. } => {
self.infer_expr(left, env, scope, idx, depth + 1)?;
Ok(StaticTy::Ty(TypeTag::Bool))
}
}
}
fn infer_rpn(
&mut self,
ops: &[MathOp],
env: &mut Env,
scope: &Scope,
depth: usize,
) -> Result<StaticTy> {
if depth > MAX_STATIC_DEPTH {
bail!("static analysis depth exceeded in `{}`", scope.label);
}
let mut stack: Vec<StaticTy> = Vec::new();
for op in ops {
match op {
MathOp::PushConst(value) => stack.push(StaticTy::Ty(literal_tag(value))),
MathOp::LoadVar(name) => {
let key = clean_var(name);
if !env.is_declared(&key) {
bail!("undefined variable ${key}");
}
stack.push(StaticTy::Ty(env.read_guarded(&key, scope.site.as_ref())?));
}
MathOp::LoadEnv(_) => stack.push(StaticTy::Ty(TypeTag::String)),
MathOp::LoadKeyPath { base, keys } => {
let key = clean_var(base);
if !env.is_declared(&key) {
bail!("undefined variable ${key}");
}
let mut current = env.read_guarded(&key, scope.site.as_ref())?;
for part in keys {
match current {
TypeTag::Record(fields) => {
let Some(field) = fields.iter().find(|field| field.name == *part)
else {
bail!(
"unknown field '{part}'; expected fields: {}",
fields
.iter()
.map(|field| field.name.as_str())
.collect::<Vec<_>>()
.join(", ")
);
};
current = field.ty.clone();
}
TypeTag::ListOf(element) => {
if part.parse::<usize>().is_err() {
bail!("Invalid array index '{part}'");
}
current = element.as_ref().clone();
}
TypeTag::MapOf(values) => {
current = values.as_ref().clone();
}
TypeTag::Map | TypeTag::List | TypeTag::Any => {
current = TypeTag::Any;
break;
}
TypeTag::Union(_, members) => {
let traversable = |member: &TypeTag| {
matches!(
member,
TypeTag::Record(_)
| TypeTag::ListOf(_)
| TypeTag::MapOf(_)
| TypeTag::Map
| TypeTag::List
| TypeTag::Any
)
};
if members.iter().all(|member| !traversable(member)) {
bail!("Cannot traverse into scalar value at key '{part}'");
}
current = TypeTag::Any;
break;
}
_ => {
bail!("Cannot traverse into scalar value at key '{part}'");
}
}
}
stack.push(StaticTy::Ty(current));
}
MathOp::Call { name, arity } => {
let before = stack.len();
if before < *arity {
bail!("internal error: RPN stack underflow");
}
let mut taken: Vec<StaticTy> = stack.split_off(before - arity);
taken.reverse();
let blanks = vec![None; taken.len()];
let callee = self.resolve_call(name, depth)?;
let ret = self.apply_checked(name, &callee, &taken, &blanks, None)?;
stack.push(ret);
}
MathOp::Inspect(name) => {
let key = clean_var(name);
if !env.is_declared(&key) {
bail!("undefined variable ${key}");
}
env.read_guarded(&key, scope.site.as_ref())?;
stack.push(StaticTy::Ty(TypeTag::Any));
}
MathOp::Neg => {
let Some(top) = stack.pop() else {
bail!("internal error: RPN stack underflow");
};
stack.push(neg_rule(top, None)?);
}
MathOp::Add | MathOp::Sub | MathOp::Mul | MathOp::Div => {
let (Some(right), Some(left)) = (stack.pop(), stack.pop()) else {
bail!("internal error: RPN stack underflow");
};
stack.push(numeric_pair(left, right, None)?);
}
MathOp::Lt | MathOp::Le | MathOp::Gt | MathOp::Ge => {
let (Some(right), Some(left)) = (stack.pop(), stack.pop()) else {
bail!("internal error: RPN stack underflow");
};
ordering_pair(left, right, None)?;
stack.push(StaticTy::Ty(TypeTag::Bool));
}
MathOp::Eq | MathOp::Ne => {
if stack.pop().is_none() || stack.pop().is_none() {
bail!("internal error: RPN stack underflow");
}
stack.push(StaticTy::Ty(TypeTag::Bool));
}
}
}
if stack.len() != 1 {
bail!("internal error: RPN stack left {} values", stack.len());
}
Ok(stack.pop().expect("length checked"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use oxdock_parser::Guard;
fn static_bool(value: &str) -> GuardExpr {
GuardExpr::Predicate(Guard::Attr {
ns: oxdock_parser::Ns::Bool,
key: None,
val: Some(value.to_string()),
})
}
#[test]
fn guard_trichotomy_classifies_statically() {
assert_eq!(classify_guard(None), GuardClass::Unconditional);
assert_eq!(
classify_guard(Some(&static_bool("true"))),
GuardClass::Unconditional
);
assert_eq!(
classify_guard(Some(&static_bool("false"))),
GuardClass::Dead
);
assert_eq!(
classify_guard(Some(&GuardExpr::All(vec![static_bool("true")]))),
GuardClass::Unconditional
);
assert_eq!(
classify_guard(Some(&GuardExpr::All(vec![static_bool("false")]))),
GuardClass::Dead
);
assert_eq!(
classify_guard(Some(&GuardExpr::Not(Box::new(static_bool("false"))))),
GuardClass::Unconditional
);
}
#[test]
fn unify_widens_any_unidirectionally() {
assert!(tags_equal(
&unify(TypeTag::Int, TypeTag::Int, "t").expect("same"),
&TypeTag::Int
));
assert!(tags_equal(
&unify(TypeTag::Int, TypeTag::Any, "t").expect("widen"),
&TypeTag::Any
));
assert!(tags_equal(
&unify(TypeTag::Any, TypeTag::Map, "t").expect("widen"),
&TypeTag::Any
));
assert!(unify(TypeTag::Int, TypeTag::String, "t").is_err());
}
}