use std::collections::{HashMap, HashSet};
type HomeFuncs = HashMap<(String, String), Vec<(Option<GuardExpr>, FuncInfo)>>;
use anyhow::{Result, bail};
use oxdock_fs::GuardedPath;
use oxdock_parser::constants::{
KEYWORD_BREAK, KEYWORD_CONST, KEYWORD_CONTINUE, KEYWORD_IMPORT, KEYWORD_LET, MODULE_SEPARATOR,
};
use oxdock_parser::template::{
PlaceholderKey, TemplateSegment, TemplateSegments, classify_placeholder_key,
};
use oxdock_parser::{
CompareOp, ExportKind, Expr, GuardExpr, IoBinding, MathOp, PipeTarget, Step, StepKind, TypeTag,
Value, base_name, qualify, render_structural, sigil_var, split_qualified,
};
use oxdock_process::ProcessManager;
use super::{
ExecState, FuncMeta, FuncParam,
import::{ClosureFile, ClosureSite},
required_arity, resolve_script_params,
};
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, Debug)]
struct FuncInfo {
params: Vec<(String, TypeTag, bool)>,
declared: TypeTag,
is_async: bool,
body: Vec<Step>,
module: Option<String>,
name: String,
line: usize,
col: usize,
}
#[derive(Clone, Debug)]
struct GuardedLet {
name: String,
tag: TypeTag,
guard: Option<GuardExpr>,
is_const: bool,
}
type ModuleLets = HashMap<String, Vec<GuardedLet>>;
fn seed_map(bindings: &[GuardedLet]) -> HashMap<String, Vec<Binding>> {
let mut map: HashMap<String, Vec<Binding>> = HashMap::new();
for entry in bindings {
map.entry(entry.name.clone()).or_default().push(Binding {
tag: entry.tag.clone(),
guard: entry.guard.clone(),
is_const: entry.is_const,
});
}
map
}
#[derive(Clone, Debug)]
struct Binding {
tag: TypeTag,
guard: Option<GuardExpr>,
is_const: bool,
}
#[derive(Clone, Default, Debug)]
struct Env {
frames: Vec<HashMap<String, Vec<Binding>>>,
module: Option<ModuleScope>,
env_frames: Vec<HashSet<String>>,
func_frames: Vec<HashMap<String, FuncInfo>>,
import_frames: Vec<super::native::AliasTargets>,
}
#[derive(Clone, Debug)]
struct ModuleScope {
key: String,
lets: HashMap<String, Vec<Binding>>,
touched: std::rc::Rc<std::cell::Cell<bool>>,
}
#[derive(Clone, Debug)]
enum RetCtx {
Top,
Func(String),
Block,
AsyncValue,
AsyncStmt,
}
#[derive(Clone)]
struct Scope<'x> {
label: &'x str,
ret: RetCtx,
loops: usize,
switches: usize,
site: Option<GuardExpr>,
line: usize,
col: usize,
idx: usize,
}
fn step_pos(line: usize, col: usize, idx: usize) -> String {
let mut loc = format!("step {}", idx + 1);
if line > 0 {
loc.push_str(&format!(", line {line}"));
if col > 0 {
loc.push_str(&format!(", col {col}"));
}
}
loc
}
struct Checker<'a, P: ProcessManager> {
exec: &'a ExecState<P>,
funcs: HashMap<String, FuncInfo>,
module_lets: ModuleLets,
entry_lets: Vec<GuardedLet>,
entry_let_scopes: HashMap<(String, usize, usize), Vec<GuardedLet>>,
module_env_unions: HashMap<String, HashSet<String>>,
entry_env_union: HashSet<String>,
seeded_env: HashSet<String>,
hosts: HashMap<String, FuncMeta>,
pure_hosts: HashMap<String, FuncMeta>,
inferred: HashMap<String, StaticTy>,
inferring: Vec<String>,
visits: u64,
strict_qualified: bool,
home_funcs: HomeFuncs,
harvest_first: HashMap<(String, String), FuncInfo>,
harvested: HashMap<(String, String), String>,
alias_targets: super::native::AliasTargets,
import_ctx: Option<ImportResolveCtx<'a>>,
module_const_exports: HashMap<String, Vec<String>>,
file_targets: HashMap<String, super::native::AliasTargets>,
module_func_exports: HashMap<String, Vec<String>>,
body_scopes: BodyScopes,
isolated_depth: usize,
}
#[derive(Clone, Copy)]
struct ImportResolveCtx<'a> {
files: &'a [super::import::ClosureFile],
parent: Option<&'a GuardedPath>,
dir: &'a GuardedPath,
is_entry: bool,
}
struct CheckerConstView<'a> {
exports: &'a HashMap<String, Vec<String>>,
targets: &'a HashMap<String, super::native::AliasTargets>,
lets: &'a ModuleLets,
}
impl super::native::ModuleGraphView for CheckerConstView<'_> {
fn const_exports(&self, file: &str) -> Option<&[String]> {
self.exports.get(file).map(Vec::as_slice)
}
fn alias_targets(&self, file: &str) -> super::native::AliasTargets {
self.targets.get(file).cloned().unwrap_or_default()
}
fn binding(&self, file: &str, name: &str) -> super::native::BindingPresence {
use super::native::BindingPresence;
match self
.lets
.get(file)
.and_then(|lets| lets.iter().find(|entry| entry.name == name))
{
Some(entry) if entry.is_const => BindingPresence::Const,
Some(_) => BindingPresence::Let,
None => BindingPresence::Absent,
}
}
}
pub fn validate_import_body_types<P: ProcessManager>(
steps: &[Step],
exec: &ExecState<P>,
module: &str,
) -> Result<()> {
let mut checker = Checker::new(exec);
checker.module_lets.insert(
module.to_string(),
module_lets(steps, exec)?.into_iter().collect(),
);
checker
.module_env_unions
.insert(module.to_string(), file_env_union(steps));
checker.collect_owned(steps, Some(module))?;
checker.check_import_body("import", steps, Some(module))?;
for key in checker.func_keys() {
checker.func_return(&key, 0)?;
}
Ok(())
}
pub(crate) fn harvest_touches_module<P: ProcessManager>(
exec: &ExecState<P>,
module: &str,
steps: &[Step],
names: &[String],
) -> Result<Option<String>> {
let mut checker = Checker::new(exec);
checker.module_lets.insert(
module.to_string(),
module_lets(steps, exec)?.into_iter().collect(),
);
checker
.module_env_unions
.insert(module.to_string(), file_env_union(steps));
for name in names {
let Some((params, return_type, is_async, body)) =
steps.iter().find_map(|step| match &step.kind {
StepKind::FuncDef {
name: def_name,
params,
return_type,
is_async,
body,
..
} if def_name == name => {
Some((params.clone(), return_type.clone(), *is_async, body.clone()))
}
_ => None,
})
else {
continue;
};
let probe_key = format!("__probe__::{name}");
checker.define_collected(
&probe_key,
vec![probe_key.clone()],
¶ms,
&return_type,
is_async,
&body,
Some(module),
0,
0,
)?;
if checker.func_touches_module(&probe_key)? {
return Ok(Some(name.clone()));
}
}
Ok(None)
}
fn module_lets<P: ProcessManager>(steps: &[Step], exec: &ExecState<P>) -> Result<Vec<GuardedLet>> {
Ok(module_lets_indexed(steps, exec)?
.into_iter()
.map(|(binding, _)| binding)
.collect())
}
fn module_lets_indexed<P: ProcessManager>(
steps: &[Step],
exec: &ExecState<P>,
) -> Result<Vec<(GuardedLet, usize)>> {
let mut out = Vec::new();
for (idx, step) in steps.iter().enumerate() {
if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
continue;
}
match &step.kind {
StepKind::Bind {
var,
decl_type,
is_const,
..
} => {
let tag = exec
.resolve_tag(decl_type)
.map_err(|err| anyhow::anyhow!("variable `${var}`: {err:#}"))?;
out.push((
GuardedLet {
name: clean_var(var),
tag,
guard: step.guard.clone(),
is_const: *is_const,
},
idx,
));
}
StepKind::ReadLine { var } | StepKind::Prompt { var, .. } => {
out.push((
GuardedLet {
name: clean_var(var),
tag: TypeTag::String,
guard: step.guard.clone(),
is_const: false,
},
idx,
));
}
_ => {}
}
}
Ok(out)
}
fn with_scope_aliases<P: ProcessManager, R>(
exec: &mut ExecState<P>,
aliases: &[(String, String)],
f: impl FnOnce(&mut ExecState<P>) -> Result<R>,
) -> Result<R> {
let saved: Vec<(String, Option<String>)> = aliases
.iter()
.map(|(name, _)| (name.clone(), exec.type_aliases.get(name).cloned()))
.collect();
for (name, target) in aliases {
exec.register_alias(name.clone(), target.clone());
}
let outcome = f(&mut *exec);
for (name, prev) in saved {
match prev {
Some(target) => {
exec.register_alias(name, target);
}
None => {
exec.remove_alias(&name);
}
}
}
outcome
}
fn merge_harvest<P: ProcessManager>(
exec: &mut ExecState<P>,
files: &[ClosureFile],
dir: &GuardedPath,
path: &str,
alias: Option<&str>,
type_names: &[String],
is_entry: bool,
) -> Result<()> {
let entry_parent = exec.entry_file.as_ref().and_then(|entry| entry.parent());
let Some(key) =
super::import::resolve_static_top_level(entry_parent.as_ref(), dir, files, path, is_entry)
else {
if exec.module_table.modules.contains_key(path) {
for name in type_names {
exec.resolve_tag(name).map_err(|err| {
anyhow::anyhow!("IMPORT `{path}` has no such TYPE `{name}`: {err:#}")
})?;
}
return Ok(());
}
anyhow::bail!("IMPORT `{path}` cannot be read: not in the import closure");
};
let Some(file) = files.iter().find(|f| f.key == key) else {
anyhow::bail!("IMPORT `{path}` cannot be read: not in the import closure");
};
let aliases = super::typing::collect_type_aliases(&file.steps, exec)?;
for name in type_names {
super::import::gate_harvested_name(
ExportKind::Type,
&file.steps,
&file.exports,
name,
path,
)?;
let Some(target) = aliases.get(name) else {
anyhow::bail!("IMPORT `{path}` has no such TYPE `{name}`");
};
super::import::insert_imported_type(exec, name, target, alias, path)?;
}
Ok(())
}
fn collect_func_harvest_edges<P: ProcessManager>(
exec: &ExecState<P>,
files: &[super::import::ClosureFile],
dir: &GuardedPath,
steps: &[Step],
unit: &str,
is_entry: bool,
out: &mut HashMap<(String, String), String>,
) -> Result<()> {
for step in steps {
if let StepKind::ImportFuncs {
path,
alias: None,
func_names,
..
} = &step.kind
&& !func_names.is_empty()
&& !exec.module_table.modules.contains_key(path)
{
let entry_parent = exec.entry_file.as_ref().and_then(|entry| entry.parent());
let Some(key) = super::import::resolve_static_top_level(
entry_parent.as_ref(),
dir,
files,
path,
is_entry,
) else {
anyhow::bail!("IMPORT `{path}` cannot be read: not in the import closure");
};
for name in func_names {
out.insert((unit.to_string(), name.clone()), key.clone());
}
}
for body in super::import::child_bodies(&step.kind) {
collect_func_harvest_edges(exec, files, dir, body, unit, is_entry, out)?;
}
}
Ok(())
}
fn merge_harvests_in<P: ProcessManager>(
exec: &mut ExecState<P>,
files: &[ClosureFile],
dir: &GuardedPath,
steps: &[Step],
is_entry: bool,
) -> Result<()> {
for step in steps {
if let StepKind::ImportFuncs {
path,
alias,
type_names,
..
} = &step.kind
&& !type_names.is_empty()
{
merge_harvest(
exec,
files,
dir,
path,
alias.as_deref(),
type_names,
is_entry,
)?;
}
for body in super::import::child_bodies(&step.kind) {
merge_harvests_in(exec, files, dir, body, is_entry)?;
}
}
Ok(())
}
pub fn validate_script_closure<P: ProcessManager>(
entry: &[Step],
files: &[super::import::ClosureFile],
exec: &mut ExecState<P>,
) -> Result<()> {
for file in files {
let mut local = std::collections::HashSet::new();
for step in &file.steps {
if let StepKind::TypeAlias { name, .. } = &step.kind {
local.insert(name.clone());
}
}
for name in &file.exports.types {
if !local.contains(name) {
anyhow::bail!(
"IMPORT `{}` EXPORT TYPE `{name}` does not match any top-level TYPE in that file",
file.path
);
}
}
}
let saved_global = exec.type_aliases.clone();
let outcome: Result<()> = (|| {
let entry_base = super::import::import_base(exec);
merge_harvests_in(exec, files, &entry_base, entry, true)?;
for file in files {
merge_harvests_in(exec, files, &file.dir, &file.steps, false)?;
}
for file in files {
let full = file.sites.iter().any(|site| {
site.alias.is_some() && site.func_names.is_none() && site.type_names.is_none()
});
if !full {
continue;
}
let defs = super::typing::collect_type_aliases(&file.steps, exec)?;
for site in &file.sites {
if site.alias.is_none() || site.func_names.is_some() || site.type_names.is_some() {
continue;
}
for name in &file.exports.types {
if let Some(target) = defs.get(name) {
super::import::insert_imported_type(
exec,
name,
target,
site.alias.as_deref(),
&file.path,
)?;
}
}
}
}
let mut all_funcs = HashMap::new();
let mut all_lets: ModuleLets = HashMap::new();
let mut all_const_exports: HashMap<String, Vec<String>> = HashMap::new();
let mut home_funcs: HomeFuncs = HashMap::new();
let mut harvest_first: HashMap<(String, String), FuncInfo> = HashMap::new();
let mut harvested: HashMap<(String, String), String> = HashMap::new();
let entry_base = super::import::import_base(exec);
let entry_parent = exec.entry_file.as_ref().and_then(|entry| entry.parent());
let mut entry_targets: super::native::AliasTargets = HashMap::new();
unit_imports(
entry,
&entry_base,
files,
entry_parent.as_ref(),
&mut entry_targets,
);
let mut file_targets: HashMap<String, super::native::AliasTargets> = HashMap::new();
for file in files {
let mut targets = HashMap::new();
unit_imports(&file.steps, &file.dir, files, None, &mut targets);
file_targets.insert(file.key.clone(), targets);
}
let mut body_scopes: BodyScopes = HashMap::new();
collect_body_scopes(
entry,
super::import::ENTRY_UNIT,
&entry_targets,
&mut body_scopes,
);
for file in files {
collect_body_scopes(
&file.steps,
&file.key,
&file_targets.get(&file.key).cloned().unwrap_or_default(),
&mut body_scopes,
);
}
let entry_defs: Vec<(String, String)> = super::typing::collect_type_aliases(entry, exec)?
.into_iter()
.collect();
let mut entry_lets: Vec<GuardedLet> = Vec::new();
with_scope_aliases(exec, &entry_defs, |exec| {
let mut checker = Checker::new(exec);
checker.collect(entry)?;
for step in entry {
if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
continue;
}
if let StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} = &step.kind
{
let info = checker.make_func_info(
name,
params,
return_type,
*is_async,
body,
None,
step.line,
step.col,
)?;
checker
.home_funcs
.entry((super::import::ENTRY_UNIT.to_string(), name.clone()))
.or_default()
.push((step.guard.clone(), info));
}
}
extend_funcs_checked(&mut all_funcs, checker.funcs, "entry")?;
home_funcs.extend(checker.home_funcs);
entry_lets = module_lets(entry, exec)?;
Ok(())
})?;
for file in files {
let defs: Vec<(String, String)> =
super::typing::collect_type_aliases(&file.steps, exec)?
.into_iter()
.collect();
with_scope_aliases(exec, &defs, |exec| {
let mut checker = Checker::new(exec);
for site in &file.sites {
checker.collect_site(site, file)?;
}
checker.collect_home(file)?;
extend_funcs_checked(&mut all_funcs, checker.funcs, &file.path)?;
home_funcs.extend(checker.home_funcs);
harvest_first.extend(checker.harvest_first);
all_lets.insert(file.key.clone(), module_lets(&file.steps, exec)?);
all_const_exports.insert(file.key.clone(), file.exports.consts.clone());
Ok(())
})?;
}
{
let view = CheckerConstView {
exports: &all_const_exports,
targets: &file_targets,
lets: &all_lets,
};
for file in files {
for entry in &file.exports.consts {
if let Some((_, base)) = split_qualified(entry) {
super::native::chase_const_forward(&view, &file.key, base, entry)
.map_err(|err| anyhow::anyhow!("{}: {err}", file.key))?;
}
}
}
}
collect_func_harvest_edges(
exec,
files,
&entry_base,
entry,
super::import::ENTRY_UNIT,
true,
&mut harvested,
)?;
for file in files {
collect_func_harvest_edges(
exec,
files,
&file.dir,
&file.steps,
&file.key,
false,
&mut harvested,
)?;
}
let entry_let_scopes = entry_let_scopes(entry, &all_funcs, exec)?;
let mut inferred: HashMap<String, StaticTy> = HashMap::new();
let mut keys: Vec<String> = all_funcs.keys().cloned().collect();
keys.sort();
for key in keys {
let owner = all_funcs.get(&key).and_then(|info| info.module.clone());
let defs: Vec<(String, String)> = match &owner {
None => entry_defs.clone(),
Some(module) => files
.iter()
.find(|f| f.key == *module)
.map(|file| {
super::typing::collect_type_aliases(&file.steps, exec)
.map(|aliases| aliases.into_iter().collect())
})
.transpose()?
.unwrap_or_default(),
};
let owner_targets: super::native::AliasTargets = match &owner {
None => entry_targets.clone(),
Some(module) => file_targets.get(module).cloned().unwrap_or_default(),
};
with_scope_aliases(exec, &defs, |exec| {
let import_ctx = match &owner {
None => Some(ImportResolveCtx {
files,
parent: entry_parent.as_ref(),
dir: &entry_base,
is_entry: true,
}),
Some(module) => {
files
.iter()
.find(|f| f.key == *module)
.map(|file| ImportResolveCtx {
files,
parent: None,
dir: &file.dir,
is_entry: false,
})
}
};
let mut checker = seeded_checker(
exec,
&all_funcs,
&home_funcs,
&harvest_first,
&harvested,
&all_lets,
&all_const_exports,
&entry_lets,
&inferred,
entry,
files,
&owner_targets,
&body_scopes,
&entry_let_scopes,
&file_targets,
import_ctx,
);
let ty = checker.func_return(&key, 0)?;
inferred.insert(key.clone(), ty);
Ok(())
})?;
}
let mut home_keys: Vec<(String, String)> = home_funcs.keys().cloned().collect();
home_keys.sort();
for (module, base) in home_keys {
let canonical = super::native::file_func_key(&module, &base);
if inferred.contains_key(&canonical) {
continue;
}
let Some(overloads) = home_funcs.get(&(module.clone(), base.clone())) else {
continue;
};
let Some((_, info)) = overloads.last().cloned() else {
continue;
};
let defs: Vec<(String, String)> = files
.iter()
.find(|f| f.key == module)
.map(|file| {
super::typing::collect_type_aliases(&file.steps, exec)
.map(|aliases| aliases.into_iter().collect())
})
.transpose()?
.unwrap_or_default();
let owner_targets: super::native::AliasTargets =
file_targets.get(&module).cloned().unwrap_or_default();
with_scope_aliases(exec, &defs, |exec| {
let import_ctx = if module == super::import::ENTRY_UNIT {
Some(ImportResolveCtx {
files,
parent: entry_parent.as_ref(),
dir: &entry_base,
is_entry: true,
})
} else {
files
.iter()
.find(|f| f.key == module)
.map(|file| ImportResolveCtx {
files,
parent: None,
dir: &file.dir,
is_entry: false,
})
};
let mut checker = seeded_checker(
exec,
&all_funcs,
&home_funcs,
&harvest_first,
&harvested,
&all_lets,
&all_const_exports,
&entry_lets,
&inferred,
entry,
files,
&owner_targets,
&body_scopes,
&entry_let_scopes,
&file_targets,
import_ctx,
);
let ty = checker.func_return_owned(&info, &canonical, 0)?;
inferred.insert(canonical.clone(), ty);
Ok(())
})?;
}
#[allow(clippy::too_many_arguments)]
fn seeded_checker<'a, P: ProcessManager>(
exec: &'a mut ExecState<P>,
funcs: &HashMap<String, FuncInfo>,
home_funcs: &HomeFuncs,
harvest_first: &HashMap<(String, String), FuncInfo>,
harvested: &HashMap<(String, String), String>,
lets: &ModuleLets,
const_exports: &HashMap<String, Vec<String>>,
entry_lets: &[GuardedLet],
inferred: &HashMap<String, StaticTy>,
entry: &[Step],
files: &'a [ClosureFile],
alias_targets: &super::native::AliasTargets,
body_scopes: &BodyScopes,
entry_let_scopes: &HashMap<(String, usize, usize), Vec<GuardedLet>>,
file_targets: &HashMap<String, super::native::AliasTargets>,
import_ctx: Option<ImportResolveCtx<'a>>,
) -> Checker<'a, P> {
let mut checker = Checker::new(exec);
checker.funcs = funcs.clone();
checker.home_funcs = home_funcs.clone();
checker.harvest_first = harvest_first.clone();
checker.harvested = harvested.clone();
checker.module_lets = lets.clone();
checker.module_const_exports = const_exports.clone();
checker.module_func_exports = files
.iter()
.map(|file| (file.key.clone(), file.exports.funcs.clone()))
.collect();
checker.entry_lets = entry_lets.to_vec();
checker.entry_let_scopes = entry_let_scopes.clone();
checker.inferred = inferred.clone();
checker.strict_qualified = true;
checker.alias_targets = alias_targets.clone();
checker.import_ctx = import_ctx;
checker.file_targets = file_targets.clone();
checker.body_scopes = body_scopes.clone();
checker.build_env_unions(entry, files);
checker
}
with_scope_aliases(exec, &entry_defs, |exec| {
seeded_checker(
exec,
&all_funcs,
&home_funcs,
&harvest_first,
&harvested,
&all_lets,
&all_const_exports,
&entry_lets,
&inferred,
entry,
files,
&entry_targets,
&body_scopes,
&entry_let_scopes,
&file_targets,
Some(ImportResolveCtx {
files,
parent: entry_parent.as_ref(),
dir: &entry_base,
is_entry: true,
}),
)
.check_top_level(entry)
})?;
for file in files {
let defs: Vec<(String, String)> =
super::typing::collect_type_aliases(&file.steps, exec)?
.into_iter()
.collect();
let targets = file_targets.get(&file.key).cloned().unwrap_or_default();
with_scope_aliases(exec, &defs, |exec| {
seeded_checker(
exec,
&all_funcs,
&home_funcs,
&harvest_first,
&harvested,
&all_lets,
&all_const_exports,
&entry_lets,
&inferred,
entry,
files,
&targets,
&body_scopes,
&entry_let_scopes,
&file_targets,
Some(ImportResolveCtx {
files,
parent: None,
dir: &file.dir,
is_entry: false,
}),
)
.check_import_body(&file.key, &file.steps, Some(&file.key))
})?;
}
Ok(())
})();
exec.restore_aliases(saved_global);
if outcome.is_ok() {
for file in files {
exec.validated_modules.insert(file.key.clone());
}
}
outcome
}
#[cfg(test)]
pub fn validate_script_types_counted<P: ProcessManager>(
steps: &[Step],
exec: &ExecState<P>,
) -> Result<u64> {
let mut checker = Checker::new(exec);
checker.entry_env_union = file_env_union(steps);
checker.entry_lets = module_lets(steps, 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::Void
| 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::HandleOf(a) => {
let TypeTag::HandleOf(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 is_compatible(actual: &TypeTag, declared: &TypeTag) -> bool {
if matches!(actual, TypeTag::Void) || matches!(declared, TypeTag::Void) {
return matches!(actual, TypeTag::Void) && matches!(declared, TypeTag::Void);
}
if matches!(declared, TypeTag::Any) {
return true;
}
if let TypeTag::Union(_, members) = actual {
return members.iter().all(|m| is_compatible(m, declared));
}
if let TypeTag::Union(_, members) = declared {
return members.iter().any(|m| is_compatible(actual, m));
}
match (actual, declared) {
(TypeTag::ListOf(a), TypeTag::ListOf(e)) => is_compatible(a, e),
(TypeTag::MapOf(a), TypeTag::MapOf(e)) => is_compatible(a, e),
(TypeTag::Record(a_fields), TypeTag::MapOf(e)) => {
a_fields.iter().all(|field| is_compatible(&field.ty, e))
}
(TypeTag::HandleOf(a), TypeTag::HandleOf(e)) => is_compatible(a, e),
(TypeTag::Record(a_fields), TypeTag::Record(e_fields)) => {
e_fields
.iter()
.all(|ef| match a_fields.iter().find(|af| af.name == ef.name) {
Some(af) => is_compatible(&af.ty, &ef.ty),
None => ef.optional,
})
&& a_fields
.iter()
.all(|af| e_fields.iter().any(|ef| ef.name == af.name))
}
(TypeTag::Record(_), TypeTag::Map) => true,
(TypeTag::MapOf(_), TypeTag::Map) => true,
(TypeTag::ListOf(_), TypeTag::List) => true,
(TypeTag::HandleOf(a), TypeTag::Handle) => is_compatible(a, &TypeTag::Any),
(TypeTag::Handle, TypeTag::HandleOf(e)) => is_compatible(&TypeTag::Any, e),
_ => tags_equal(actual, declared),
}
}
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 check_var_binding_access(
env: &Env,
key: &str,
site: Option<&GuardExpr>,
prefix: &str,
) -> Result<TypeTag> {
if !env.is_declared(key) {
bail!("{prefix}undefined variable ${key}");
}
env.read_guarded(key, site)
}
fn traverse_static_keypath(mut current: TypeTag, keys: &[String], prefix: &str) -> Result<TypeTag> {
for part in keys {
match current {
TypeTag::Record(fields) => {
let Some(field) = fields.iter().find(|field| field.name == *part) else {
bail!(
"{prefix}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!("{prefix}Invalid array index '{part}'");
}
current = element.as_ref().clone();
}
TypeTag::MapOf(values) => {
current = values.as_ref().clone();
}
TypeTag::Map | TypeTag::List | TypeTag::Any => {
return Ok(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!("{prefix}Cannot traverse into scalar value at key '{part}'");
}
return Ok(TypeTag::Any);
}
_ => {
bail!("{prefix}Cannot traverse into scalar value at key '{part}'");
}
}
}
Ok(current)
}
fn loc(at: Option<&str>) -> String {
at.map(|s| format!("{s}: ")).unwrap_or_default()
}
struct Callee {
params: Option<Vec<(String, TypeTag, bool)>>,
ret: StaticTy,
host_params: Option<Vec<FuncParam>>,
}
struct WalkOut {
falls_through: bool,
has_return: bool,
bare_return: bool,
types: Vec<(TypeTag, usize, usize)>,
}
fn file_env_union(steps: &[Step]) -> HashSet<String> {
let mut union = HashSet::new();
for step in steps {
match &step.kind {
StepKind::Env { key, .. } => {
union.insert(key.clone());
}
StepKind::InheritEnv { keys } | StepKind::IsolatedInheritEnv { keys } => {
union.extend(keys.iter().cloned());
}
_ => {}
}
}
union
}
fn unit_imports(
steps: &[Step],
dir: &GuardedPath,
files: &[ClosureFile],
entry_parent: Option<&GuardedPath>,
targets: &mut super::native::AliasTargets,
) {
let mut depth: usize = 0;
for step in steps {
depth = depth.saturating_add(step.scope_enter);
let live_top_level =
depth == 0 && !matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead);
let import = if live_top_level && !matches!(step.kind, StepKind::FuncDef { .. }) {
match &step.kind {
StepKind::ImportFile { path, alias } => Some((path.clone(), alias.clone())),
StepKind::ImportFuncs {
path,
alias: Some(alias),
..
} => Some((path.clone(), alias.clone())),
_ => None,
}
} else {
None
};
depth = depth.saturating_sub(step.scope_exit);
let Some((path, alias)) = import else {
continue;
};
let unit = targets.entry(alias).or_default();
let is_entry = entry_parent.is_some();
let defining =
super::import::resolve_static_top_level(entry_parent, dir, files, &path, is_entry);
unit.push((defining, step.guard.clone()));
}
}
fn step_call_names(kind: &StepKind, enter_funcdefs: bool, out: &mut Vec<String>) {
if !enter_funcdefs && matches!(kind, StepKind::FuncDef { .. }) {
return;
}
kind.walk_exprs(&mut |expr| expr_call_names(expr, enter_funcdefs, out));
kind.walk_raw_strings(&mut |text| template_call_names(text, out));
kind.walk_child_kinds(&mut |sub| step_call_names(sub, enter_funcdefs, out));
}
fn expr_call_names(expr: &Expr, enter_funcdefs: bool, out: &mut Vec<String>) {
match expr {
Expr::Call { name, args } => {
push_entry_call_name(name, out);
for arg in args {
expr_call_names(arg, enter_funcdefs, out);
}
}
Expr::CompiledMath(ops) => {
for op in ops {
match op {
MathOp::Call { name, .. } => push_entry_call_name(name, out),
MathOp::PushConst(value) => {
if let Some(text) = value.as_str() {
template_call_names(text, out);
}
}
_ => {}
}
}
}
Expr::Literal(value) => {
if let Some(text) = value.as_str() {
template_call_names(text, out);
}
}
Expr::Block(steps) => {
for step in steps {
step_call_names(&step.kind, enter_funcdefs, out);
}
}
Expr::List(items) => {
for item in items {
expr_call_names(item, enter_funcdefs, out);
}
}
Expr::Map(entries) => {
for (_, value) in entries {
expr_call_names(value, enter_funcdefs, out);
}
}
Expr::Compare { left, right, .. }
| Expr::Arithmetic { left, right, .. }
| Expr::Logical { left, right, .. } => {
expr_call_names(left, enter_funcdefs, out);
expr_call_names(right, enter_funcdefs, out);
}
Expr::Not(inner) => expr_call_names(inner, enter_funcdefs, out),
Expr::Var { .. }
| Expr::ConstRef { .. }
| Expr::Env(_)
| Expr::KeyPath { .. }
| Expr::Inspect { .. }
| Expr::FreshPipe
| Expr::UnsignedIntBoundary(_) => {}
}
}
fn push_entry_call_name(name: &str, out: &mut Vec<String>) {
if let Some((module, base)) = split_qualified(name) {
if module == oxdock_parser::SCRIPT_MODULE_NAME {
out.push(base.to_string());
}
} else {
out.push(name.to_string());
}
}
fn template_call_names(text: &str, out: &mut Vec<String>) {
for segment in TemplateSegments::new(text) {
if let TemplateSegment::Placeholder { key, .. } = segment
&& let PlaceholderKey::Call(call) = classify_placeholder_key(key)
{
match call.module {
None => out.push(call.name.to_string()),
Some(module) if module == oxdock_parser::SCRIPT_MODULE_NAME => {
out.push(call.name.to_string());
}
_ => {}
}
}
}
}
fn entry_let_scopes<P: ProcessManager>(
entry: &[Step],
all_funcs: &HashMap<String, FuncInfo>,
exec: &ExecState<P>,
) -> Result<HashMap<(String, usize, usize), Vec<GuardedLet>>> {
let indexed = module_lets_indexed(entry, exec)?;
let mut top_direct: HashMap<String, usize> = HashMap::new();
for (idx, step) in entry.iter().enumerate() {
if matches!(step.kind, StepKind::FuncDef { .. }) {
continue;
}
let mut names = Vec::new();
step_call_names(&step.kind, false, &mut names);
for name in names {
top_direct
.entry(name)
.and_modify(|at| *at = (*at).min(idx))
.or_insert(idx);
}
}
let mut funcs: Vec<(String, usize, usize)> = Vec::new();
let mut callees: HashMap<(String, usize, usize), Vec<String>> = HashMap::new();
for info in all_funcs.values() {
if info.module.is_some() {
continue;
}
let key = (info.name.clone(), info.line, info.col);
if callees.contains_key(&key) {
continue;
}
let mut names = Vec::new();
for step in &info.body {
step_call_names(&step.kind, true, &mut names);
}
funcs.push(key.clone());
callees.insert(key, names);
}
let mut earliest: HashMap<(String, usize, usize), usize> = HashMap::new();
for key in &funcs {
earliest.insert(
key.clone(),
top_direct.get(&key.0).copied().unwrap_or(usize::MAX),
);
}
for _ in 0..funcs.len() {
let mut changed = false;
for caller in &funcs {
let at = earliest[caller];
if at == usize::MAX {
continue;
}
for callee_name in callees[caller].clone() {
for callee in funcs.iter().filter(|key| key.0 == callee_name) {
if earliest[callee] > at {
earliest.insert(callee.clone(), at);
changed = true;
}
}
}
}
if !changed {
break;
}
}
let mut out = HashMap::new();
for key in &funcs {
let Some(&at) = earliest.get(key) else {
continue;
};
if at == usize::MAX {
continue;
}
let scoped: Vec<GuardedLet> = indexed
.iter()
.filter(|(_, idx)| *idx < at)
.map(|(binding, _)| binding.clone())
.collect();
out.insert(key.clone(), scoped);
}
Ok(out)
}
type BodyScopes = HashMap<(String, String, usize, usize), super::native::AliasTargets>;
fn collect_body_scopes(
steps: &[Step],
module_key: &str,
unit_top: &super::native::AliasTargets,
out: &mut BodyScopes,
) {
for step in steps {
if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
continue;
}
if let StepKind::FuncDef { name, body, .. } = &step.kind {
out.insert(
(module_key.to_string(), name.clone(), step.line, step.col),
unit_top.clone(),
);
collect_body_scopes(body, module_key, unit_top, out);
} else {
for nested in super::import::child_bodies(&step.kind) {
collect_body_scopes(nested, module_key, unit_top, out);
}
}
}
}
fn extend_funcs_checked(
all_funcs: &mut HashMap<String, FuncInfo>,
incoming: HashMap<String, FuncInfo>,
display: &str,
) -> Result<()> {
for (key, info) in incoming {
if let Some(existing) = all_funcs.get(&key)
&& existing.module != info.module
{
bail!("duplicate function `{key}` from `{display}` collides across imports");
}
all_funcs.insert(key, info);
}
Ok(())
}
impl Env {
fn one_frame(bindings: Vec<(String, TypeTag, bool)>) -> Self {
let mut top = HashMap::new();
for (name, tag, _) in bindings {
top.insert(
name,
vec![Binding {
tag,
guard: None,
is_const: false,
}],
);
}
Self {
frames: vec![top],
module: None,
env_frames: vec![HashSet::new()],
func_frames: vec![HashMap::new()],
import_frames: vec![HashMap::new()],
}
}
fn push_frame(&mut self) {
self.frames.push(HashMap::new());
self.env_frames.push(HashSet::new());
self.func_frames.push(HashMap::new());
self.import_frames.push(HashMap::new());
}
fn fork(&self) -> Self {
let mut fork = self.clone();
fork.push_frame();
fork
}
fn declare_env(&mut self, name: String) {
if let Some(frame) = self.env_frames.last_mut() {
frame.insert(name);
}
}
fn append_import_target(
&mut self,
alias: String,
defining: Option<String>,
guard: Option<GuardExpr>,
) {
if let Some(frame) = self.import_frames.last_mut() {
frame.entry(alias).or_default().push((defining, guard));
}
}
fn visible_imports(&self) -> super::native::AliasTargets {
let mut out = super::native::AliasTargets::new();
for frame in &self.import_frames {
for (alias, targets) in frame {
out.entry(alias.clone())
.or_default()
.extend(targets.iter().cloned());
}
}
out
}
fn is_env_declared(&self, name: &str) -> bool {
self.env_frames.iter().any(|frame| frame.contains(name))
}
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!("{} across platform guards", sigil_var(key)),
)?,
});
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));
}
}
if let Some(scope) = &self.module
&& let Some(entries) = scope.lets.get(key)
{
let live: Vec<&Binding> = entries
.iter()
.filter(|entry| oxdock_parser::guards_overlap(entry.guard.as_ref(), site))
.collect();
if !live.is_empty() {
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;
for entry in live {
unified = Some(match unified {
None => entry.tag.clone(),
Some(acc) => unify(
acc,
entry.tag.clone(),
&format!("{} across platform guards", sigil_var(key)),
)?,
});
}
scope.touched.set(true);
return Ok((unified.expect("live never empty"), None));
}
}
bail!("undefined variable ${key}");
}
fn is_declared(&self, key: &str) -> bool {
self.frames
.iter()
.rev()
.any(|frame| frame.contains_key(key))
|| self
.module
.as_ref()
.is_some_and(|scope| scope.lets.contains_key(key))
}
fn is_const(&self, key: &str, site: Option<&GuardExpr>) -> bool {
for frame in self.frames.iter().rev() {
if let Some(entries) = frame.get(key) {
return entries.iter().any(|entry| {
entry.is_const && oxdock_parser::guards_overlap(entry.guard.as_ref(), site)
});
}
}
if let Some(scope) = &self.module
&& let Some(entries) = scope.lets.get(key)
{
return entries.iter().any(|entry| {
entry.is_const && oxdock_parser::guards_overlap(entry.guard.as_ref(), site)
});
}
false
}
fn declare(
&mut self,
key: String,
tag: TypeTag,
guard: Option<&GuardExpr>,
idx: usize,
) -> Result<()> {
self.declare_inner(key, tag, guard, idx, false)
}
fn declare_const(
&mut self,
key: String,
tag: TypeTag,
guard: Option<&GuardExpr>,
idx: usize,
) -> Result<()> {
self.declare_inner(key, tag, guard, idx, true)
}
fn declare_inner(
&mut self,
key: String,
tag: TypeTag,
guard: Option<&GuardExpr>,
idx: usize,
is_const: bool,
) -> 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) {
if entry.is_const || is_const {
bail!(
"step {}: redeclaration error: {key} is a CONST binding and cannot be redeclared; CONST and LET share one namespace",
idx + 1
);
}
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(),
is_const,
});
}
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(),
is_const: false,
}],
);
}
}
}
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);
}
let mut pure_hosts = HashMap::new();
for meta in exec.functions.pure_metas() {
pure_hosts.insert(meta.name.clone(), meta);
}
Self {
exec,
funcs: HashMap::new(),
module_lets: HashMap::new(),
entry_lets: Vec::new(),
module_env_unions: HashMap::new(),
entry_env_union: HashSet::new(),
seeded_env: oxdock_process::seeded_env_names()
.into_iter()
.map(|name| name.to_string())
.collect(),
hosts,
pure_hosts,
inferred: HashMap::new(),
inferring: Vec::new(),
visits: 0,
strict_qualified: false,
home_funcs: HashMap::new(),
harvest_first: HashMap::new(),
harvested: HashMap::new(),
entry_let_scopes: HashMap::new(),
alias_targets: HashMap::new(),
import_ctx: None,
module_const_exports: HashMap::new(),
file_targets: HashMap::new(),
module_func_exports: HashMap::new(),
body_scopes: HashMap::new(),
isolated_depth: 0,
}
}
fn func_keys(&self) -> Vec<String> {
self.funcs.keys().cloned().collect()
}
fn collect_owned(&mut self, steps: &[Step], module: Option<&str>) -> Result<()> {
for step in steps {
if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
continue;
}
self.collect_step(step, module)?;
}
Ok(())
}
fn collect(&mut self, steps: &[Step]) -> Result<()> {
self.collect_owned(steps, None)
}
fn build_env_unions(&mut self, entry: &[Step], files: &[super::import::ClosureFile]) {
self.entry_env_union = file_env_union(entry);
for file in files {
self.module_env_unions
.insert(file.key.clone(), file_env_union(&file.steps));
}
}
fn env_declared(&self, env: &Env, name: &str) -> bool {
env.is_env_declared(name)
|| self.seeded_env.contains(name)
|| oxdock_process::is_sanctioned_seed(name)
}
fn check_env_name(&self, env: &Env, name: &str, prefix: &str, scope: &Scope) -> Result<()> {
if !self.env_declared(env, name) {
bail!(
"{} in {}: uses undeclared environment variable `{prefix}{name}`: declare it first with ENV or INHERIT_ENV",
step_pos(scope.line, scope.col, scope.idx),
scope.label,
);
}
Ok(())
}
fn check_template_env(
&mut self,
text: &str,
env: &mut Env,
scope: &Scope,
depth: usize,
) -> Result<()> {
use oxdock_parser::template::{
PlaceholderKey, TemplateSegment, TemplateSegments, classify_placeholder_key,
placeholder_vars,
};
for segment in TemplateSegments::new(text) {
let TemplateSegment::Placeholder { key, .. } = segment else {
continue;
};
match classify_placeholder_key(key) {
PlaceholderKey::Empty => {}
PlaceholderKey::Env(name) => {
let name = name.trim();
self.check_env_name(env, name, "env:", scope)?;
}
PlaceholderKey::ScriptEnv(name) => {
let name = name.trim();
self.check_env_name(env, name, "script_env:", scope)?;
}
PlaceholderKey::DollarQualified { alias, name, keys } => {
if !keys.is_empty() {
return Err(anyhow::anyhow!(
oxdock_parser::template::qualified_keypath_error()
));
}
let expr = Expr::ConstRef {
alias: alias.to_string(),
name: name.to_string(),
};
let idx = scope.idx;
let _ = self.infer_expr(&expr, env, scope, idx, depth + 1)?;
}
PlaceholderKey::Dollar(rest) => {
if oxdock_parser::template::parse_var_path(rest).is_none() {
bail!("invalid placeholder variable: empty variable reference");
}
for var in placeholder_vars(key) {
self.check_template_var(&var, env, scope, depth)?;
}
}
PlaceholderKey::ConstRef { .. }
| PlaceholderKey::KeyPath { .. }
| PlaceholderKey::Var(_) => {
return Err(anyhow::anyhow!(oxdock_parser::template::bare_sigil_error(
key.trim()
)));
}
PlaceholderKey::Bare(_) => {
for var in placeholder_vars(key) {
self.check_template_var(&var, env, scope, depth)?;
}
}
PlaceholderKey::Call(call) => {
for var in placeholder_vars(key) {
self.check_template_var(&var, env, scope, depth)?;
}
let Some(module) = call.module else {
bail!("undefined script variable: '{key}'");
};
self.check_template_call(module, call.name, call.args_raw, env, scope, depth)?;
}
}
}
Ok(())
}
fn check_template_var(
&mut self,
var: &oxdock_parser::template::TemplateVar,
env: &mut Env,
scope: &Scope,
depth: usize,
) -> Result<()> {
use oxdock_parser::template::{TemplateVar, bare_sigil_error};
let expr = match var {
TemplateVar::Path(parts) => {
let (base, rest) = parts
.split_first()
.expect("placeholder_vars never emits empty paths");
if rest.is_empty() {
Expr::Var { name: base.clone() }
} else {
Expr::KeyPath {
base: base.clone(),
keys: rest.to_vec(),
}
}
}
TemplateVar::ConstRef { alias, name } => {
return Err(anyhow::anyhow!(bare_sigil_error(&qualify(alias, name))));
}
TemplateVar::KeyPath { base, keys } => {
return Err(anyhow::anyhow!(bare_sigil_error(&format!(
"{base}.{}",
keys.join(".")
))));
}
TemplateVar::Var(name) => {
return Err(anyhow::anyhow!(bare_sigil_error(name)));
}
TemplateVar::Bare(name) => Expr::Var { name: name.clone() },
};
let idx = scope.idx;
let _ = self.infer_expr(&expr, env, scope, idx, depth + 1)?;
Ok(())
}
fn check_template_call(
&mut self,
module: &str,
name: &str,
args_raw: &str,
env: &mut Env,
scope: &Scope,
depth: usize,
) -> Result<()> {
let qualified = qualify(module, name);
let Some(meta) = self.pure_hosts.get(&qualified).cloned() else {
let mut is_script_visible = false;
let effective = self.effective_alias_targets(env);
match super::native::classify_alias_call(&effective, &qualified, &|key| {
self.funcs.contains_key(key)
}) {
super::native::AliasResolution::Global => {
is_script_visible = self.funcs.contains_key(&qualified);
if module == oxdock_parser::SCRIPT_MODULE_NAME {
let unit =
super::import::unit_key(env.module.as_ref().map(|m| m.key.as_str()));
if self
.find_frame_hit(unit, name, &env.func_frames, scope.site.as_ref())
.is_some()
{
is_script_visible = true;
}
}
}
super::native::AliasResolution::Canonical(canonical) => {
is_script_visible = self.funcs.contains_key(&canonical);
}
super::native::AliasResolution::Ambiguous { files, .. } => {
bail!(
"{}",
super::native::ambiguous_alias_message(module, name, &files)
);
}
super::native::AliasResolution::Any {
base,
files,
has_host,
} => {
bail!(
"{}",
super::native::disjoint_alias_placeholder_miss(
module,
name,
&base,
&files,
has_host,
&|key| self.funcs.contains_key(key),
)
);
}
super::native::AliasResolution::Unknown => {}
}
if let Some(text) = super::native::describe_placeholder_miss(
module,
name,
is_script_visible,
self.hosts.contains_key(&qualified),
effective.contains_key(module),
) {
bail!("{text}");
}
bail!("unknown placeholder function '{qualified}'");
};
let args_src = oxdock_parser::template::split_placeholder_args(args_raw);
if let Some(host_params) = meta.params.as_deref() {
let required = super::required_arity(host_params);
let total = host_params.len();
if args_src.len() < required || args_src.len() > total {
if required == total {
bail!(
"{} in {}: {}() expects {} argument(s), got {}",
step_pos(scope.line, scope.col, scope.idx),
scope.label,
qualified,
total,
args_src.len()
);
}
bail!(
"{} in {}: {}() expects {} to {} argument(s), got {}",
step_pos(scope.line, scope.col, scope.idx),
scope.label,
qualified,
required,
total,
args_src.len()
);
}
for (position, src) in args_src.iter().enumerate() {
let trimmed = src.trim();
let actual = self.infer_template_arg(trimmed, env, scope, depth, 0)?;
if let Some(param) = host_params.get(position) {
if let Some(expected) = param.param_type.clone() {
let pat = format!(
"{} in {}: {}() argument `${}`",
step_pos(scope.line, scope.col, scope.idx),
scope.label,
qualified,
param.name
);
self.check_arg(&expected, actual, &pat)?;
}
if let Some(allowed) = param.allowed
&& let Some(s) = self.template_arg_literal(trimmed)
&& !allowed.contains(&s.as_str())
{
bail!(
"{} in {}: {}() argument `${}` must be one of: {}, got {s:?}",
step_pos(scope.line, scope.col, scope.idx),
scope.label,
qualified,
param.name,
allowed.join(", ")
);
}
}
}
return Ok(());
}
for src in args_src.iter() {
let _ = self.infer_template_arg(src.trim(), env, scope, depth, 0)?;
}
Ok(())
}
fn infer_template_arg(
&mut self,
src: &str,
env: &mut Env,
scope: &Scope,
depth: usize,
literal_depth: usize,
) -> Result<StaticTy> {
use oxdock_parser::template::{
MAX_TEMPLATE_ARG_DEPTH, ScalarLit, TemplateArg, bare_sigil_error,
classify_template_arg, parse_string_literal, parse_var_path, qualified_keypath_error,
};
if literal_depth > MAX_TEMPLATE_ARG_DEPTH {
bail!("placeholder call argument nests too deep (limit {MAX_TEMPLATE_ARG_DEPTH})");
}
match classify_template_arg(src) {
TemplateArg::DollarQualified { alias, name, keys } => {
if !keys.is_empty() {
return Err(anyhow::anyhow!(qualified_keypath_error()));
}
let expr = Expr::ConstRef {
alias: alias.to_string(),
name: name.to_string(),
};
self.infer_expr(&expr, env, scope, scope.idx, depth + 1)
}
TemplateArg::Dollar(rest) => {
let Some(parts) = parse_var_path(rest) else {
bail!("invalid placeholder call argument: empty variable reference");
};
let (base, segs) = parts.split_first().expect("split always yields one");
let expr = if segs.is_empty() {
Expr::Var { name: base.clone() }
} else {
Expr::KeyPath {
base: base.clone(),
keys: segs.to_vec(),
}
};
self.infer_expr(&expr, env, scope, scope.idx, depth + 1)
}
TemplateArg::Str(literal_src) => {
let literal = parse_string_literal(literal_src)
.expect("classify_template_arg only yields Str for string shapes");
let _ = literal.map_err(|err| anyhow::anyhow!("{err:#}"))?;
Ok(StaticTy::Ty(TypeTag::String))
}
TemplateArg::Map(inner) => {
self.infer_template_map(inner, env, scope, depth, literal_depth)
}
TemplateArg::List(inner) => {
self.infer_template_list(inner, env, scope, depth, literal_depth)
}
TemplateArg::Scalar(scalar_src) => {
let Some(lit) = oxdock_parser::template::parse_scalar_literal(scalar_src) else {
bail!("invalid placeholder call argument '{scalar_src}'")
};
Ok(StaticTy::Ty(match lit {
ScalarLit::Bool(_) => TypeTag::Bool,
ScalarLit::Int(_) => TypeTag::Int,
ScalarLit::Float(_) => TypeTag::Float,
}))
}
TemplateArg::ConstRef { .. } | TemplateArg::KeyPath { .. } | TemplateArg::Var(_) => {
Err(anyhow::anyhow!(bare_sigil_error(src.trim())))
}
TemplateArg::Invalid(invalid) => {
bail!("invalid placeholder call argument '{invalid}'")
}
}
}
fn infer_template_map(
&mut self,
inner: &str,
env: &mut Env,
scope: &Scope,
depth: usize,
literal_depth: usize,
) -> Result<StaticTy> {
use oxdock_parser::template::{parse_map_key, split_map_entry, split_top_level};
if inner.trim().is_empty() {
return Ok(StaticTy::Ty(TypeTag::Map));
}
let mut seen = std::collections::HashSet::new();
let mut value_tags: Vec<TypeTag> = Vec::new();
for entry in split_top_level(inner, ',') {
let Some((key_src, value_src)) = split_map_entry(&entry) else {
bail!("invalid map literal entry '{entry}': use key: value");
};
let key = parse_map_key(&key_src)?;
if !seen.insert(key.clone()) {
bail!("duplicate key '{key}' in map literal");
}
let value_ty =
self.infer_template_arg(value_src.trim(), env, scope, depth, literal_depth + 1)?;
let StaticTy::Ty(tag) = value_ty else {
bail!("VOID has no value to pass");
};
value_tags.push(tag);
}
let mut iter = value_tags.into_iter();
let Some(first) = iter.next() else {
return Ok(StaticTy::Ty(TypeTag::Map));
};
if iter.all(|tag| tags_equal(&tag, &first)) {
return Ok(StaticTy::Ty(TypeTag::MapOf(std::sync::Arc::new(first))));
}
Ok(StaticTy::Ty(TypeTag::Map))
}
fn infer_template_list(
&mut self,
inner: &str,
env: &mut Env,
scope: &Scope,
depth: usize,
literal_depth: usize,
) -> Result<StaticTy> {
use oxdock_parser::template::split_top_level;
if inner.trim().is_empty() {
return Ok(StaticTy::Ty(TypeTag::List));
}
let mut element_tags: Vec<TypeTag> = Vec::new();
for item in split_top_level(inner, ',') {
let element_ty =
self.infer_template_arg(item.trim(), env, scope, depth, literal_depth + 1)?;
let StaticTy::Ty(tag) = element_ty else {
bail!("VOID has no value to pass");
};
element_tags.push(tag);
}
let mut iter = element_tags.into_iter();
let Some(first) = iter.next() else {
return Ok(StaticTy::Ty(TypeTag::List));
};
if iter.all(|tag| tags_equal(&tag, &first)) {
return Ok(StaticTy::Ty(TypeTag::ListOf(std::sync::Arc::new(first))));
}
Ok(StaticTy::Ty(TypeTag::List))
}
fn template_arg_literal(&self, src: &str) -> Option<String> {
use oxdock_parser::template::parse_string_literal;
parse_string_literal(src)?.ok()
}
fn guard_env_names(guard: &GuardExpr, out: &mut Vec<String>) {
match guard {
GuardExpr::Predicate(pred) => {
if let oxdock_parser::Guard::Attr { ns, key, .. } = pred
&& matches!(ns, oxdock_parser::Ns::Env)
&& let Some(name) = key
{
out.push(name.clone());
}
}
GuardExpr::All(children) | GuardExpr::Or(children) => {
for child in children {
Self::guard_env_names(child, out);
}
}
GuardExpr::Not(inner) => Self::guard_env_names(inner, out),
}
}
#[allow(clippy::too_many_arguments)]
fn make_func_info(
&self,
name: &str,
params: &[(String, String, bool)],
return_type: &str,
is_async: bool,
body: &[Step],
module: Option<&str>,
line: usize,
col: usize,
) -> Result<FuncInfo> {
let resolved = resolve_script_params(self.exec, name, params)?;
let declared = self
.exec
.resolve_tag(return_type)
.map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
self.exec
.check_return_tag(&format!("function `{name}` returns"), &declared)
.map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
Ok(FuncInfo {
params: resolved,
declared,
is_async,
body: body.to_vec(),
module: module.map(|m| m.to_string()),
name: name.to_string(),
line,
col,
})
}
#[allow(clippy::too_many_arguments)]
fn define_collected(
&mut self,
name: &str,
keys: Vec<String>,
params: &[(String, String, bool)],
return_type: &str,
is_async: bool,
body: &[Step],
module: Option<&str>,
line: usize,
col: usize,
) -> Result<()> {
let info =
self.make_func_info(name, params, return_type, is_async, body, module, line, col)?;
for key in keys {
self.funcs.insert(key, info.clone());
}
let nested = body.to_vec();
self.collect_owned(&nested, module)?;
Ok(())
}
fn collect_home(&mut self, file: &super::import::ClosureFile) -> Result<()> {
for step in &file.steps {
if let StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} = &step.kind
{
let key = (file.key.clone(), name.clone());
if !self.harvest_first.contains_key(&key) {
let info = self.make_func_info(
name,
params,
return_type,
*is_async,
body,
Some(file.key.as_str()),
step.line,
step.col,
)?;
self.harvest_first.insert(key, info);
}
}
if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
continue;
}
if let StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} = &step.kind
{
let info = self.make_func_info(
name,
params,
return_type,
*is_async,
body,
Some(file.key.as_str()),
step.line,
step.col,
)?;
self.home_funcs
.entry((file.key.clone(), name.clone()))
.or_default()
.push((step.guard.clone(), info));
}
}
Ok(())
}
fn collect_step(&mut self, step: &Step, module: Option<&str>) -> Result<()> {
match &step.kind {
StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} => {
self.define_collected(
name,
vec![
name.clone(),
oxdock_parser::qualify(oxdock_parser::SCRIPT_MODULE_NAME, name),
],
params,
return_type,
*is_async,
body,
module,
step.line,
step.col,
)?;
}
StepKind::If {
then_body,
else_ifs,
else_body,
..
} => {
self.collect_owned(then_body, module)?;
for (_, arm) in else_ifs {
self.collect_owned(arm, module)?;
}
if let Some(arm) = else_body {
self.collect_owned(arm, module)?;
}
}
StepKind::Switch {
cases,
default_body,
..
} => {
for (_, arm) in cases {
self.collect_owned(arm, module)?;
}
if let Some(arm) = default_body {
self.collect_owned(arm, module)?;
}
}
StepKind::For { body, .. } | StepKind::While { body, .. } => {
self.collect_owned(body, module)?;
}
StepKind::AsyncBlock { body } => self.collect_owned(body, module)?,
_ => {}
}
Ok(())
}
fn collect_site(&mut self, site: &ClosureSite, file: &ClosureFile) -> Result<()> {
let module = file.key.as_str();
let steps = file.steps.as_slice();
let alias = site.alias.as_deref();
let func_names = site.func_names.as_deref();
let type_names = site.type_names.as_deref();
let func_exports = &file.exports.funcs;
let file_path = file.path.as_str();
if !self.module_lets.contains_key(module) {
let lets = module_lets(steps, self.exec)?;
self.module_lets.insert(module.to_string(), lets);
}
if let Some(names) = func_names {
for name in names {
super::import::gate_harvested_name(
ExportKind::Func,
steps,
&file.exports,
name,
file_path,
)?;
}
}
if let Some(type_names) = type_names {
for name in type_names {
super::import::gate_harvested_name(
ExportKind::Type,
steps,
&file.exports,
name,
file_path,
)?;
}
}
let func_exported: std::collections::HashSet<&str> =
func_exports.iter().map(|e| e.as_str()).collect();
for step in steps {
if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
continue;
}
if let StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} = &step.kind
{
if !func_exported.contains(name.as_str()) {
continue;
}
if let Some(names) = func_names
&& !names.iter().any(|n| n == name)
{
continue;
}
match alias {
Some(_) => {
self.define_collected(
name,
vec![super::native::file_func_key(module, name)],
params,
return_type,
*is_async,
body,
Some(module),
step.line,
step.col,
)?;
}
None => {
self.define_collected(
name,
vec![
name.clone(),
oxdock_parser::qualify(oxdock_parser::SCRIPT_MODULE_NAME, name),
],
params,
return_type,
*is_async,
body,
Some(module),
step.line,
step.col,
)?;
}
}
} else {
self.collect_step(step, Some(module))?;
}
}
if let Some(names) = func_names {
for name in names {
let key = match alias {
Some(_) => super::native::file_func_key(module, name),
None => name.clone(),
};
if self.func_touches_module(&key)? {
bail!(
"IMPORT `{file_path}` cannot harvest stateful function `{name}`: import the file"
);
}
}
}
Ok(())
}
fn check_import_body(
&mut self,
label: &str,
steps: &[Step],
module: Option<&str>,
) -> Result<()> {
let mut env = Env::one_frame(Vec::new());
if let Some(module) = module {
let mut lets: HashMap<String, Vec<Binding>> = HashMap::new();
for entry in self.module_lets.get(module).cloned().unwrap_or_default() {
lets.entry(entry.name).or_default().push(Binding {
tag: entry.tag,
guard: entry.guard,
is_const: entry.is_const,
});
}
env.module = Some(ModuleScope {
key: module.to_string(),
lets,
touched: std::rc::Rc::new(std::cell::Cell::new(false)),
});
}
let scope = Scope {
label,
ret: RetCtx::Func(KEYWORD_IMPORT.to_string()),
loops: 0,
switches: 0,
site: None,
line: 0,
col: 0,
idx: 0,
};
let out = self.walk_body(steps, &mut env, &scope, 0)?;
let _ = out;
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,
switches: 0,
site: None,
line: 0,
col: 0,
idx: 0,
};
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> {
self.check_function_body_probed(key, info, depth, None, true)
}
fn check_function_body_probed(
&mut self,
key: &str,
info: &FuncInfo,
depth: usize,
probe: Option<std::rc::Rc<std::cell::Cell<bool>>>,
enforce_types: bool,
) -> Result<StaticTy> {
if depth > MAX_STATIC_DEPTH {
bail!("static analysis depth exceeded in function `{key}`");
}
let mut env = Env::one_frame(info.params.clone());
if let Some(module) = info.module.as_deref() {
let touched = probe.unwrap_or_default();
env.module = Some(ModuleScope {
key: module.to_string(),
lets: seed_map(
self.module_lets
.get(module)
.map(Vec::as_slice)
.unwrap_or(&[]),
),
touched,
});
if let Some(union) = self.module_env_unions.get(module) {
for name in union {
env.declare_env(name.clone());
}
}
} else {
let scoped = self
.entry_let_scopes
.get(&(info.name.clone(), info.line, info.col));
let source: &[GuardedLet] = match scoped {
Some(scope) => scope,
None => &self.entry_lets,
};
let seeds: Vec<GuardedLet> = source.iter().filter(|b| b.is_const).cloned().collect();
if !seeds.is_empty() {
env.frames.insert(0, seed_map(&seeds));
env.env_frames.insert(0, HashSet::new());
env.func_frames.insert(0, HashMap::new());
env.import_frames.insert(0, HashMap::new());
}
for name in &self.entry_env_union {
env.declare_env(name.clone());
}
}
let scope = Scope {
label: key,
ret: RetCtx::Func(key.to_string()),
loops: 0,
switches: 0,
site: None,
line: 0,
col: 0,
idx: 0,
};
let unit = super::import::unit_key(info.module.as_deref());
let overlay = self
.body_scopes
.get(&(unit.to_string(), info.name.clone(), info.line, info.col))
.cloned();
let saved = overlay.map(|targets| std::mem::replace(&mut self.alias_targets, targets));
let out = self.walk_body(&info.body, &mut env, &scope, depth + 1);
if let Some(targets) = saved {
self.alias_targets = targets;
}
let out = out?;
if !enforce_types {
return Ok(StaticTy::Ty(TypeTag::Any));
}
let declared = &info.declared;
let is_void = matches!(declared, TypeTag::Void);
if info.is_async && !matches!(declared, TypeTag::Handle | TypeTag::HandleOf(_)) {
bail!(
"function `{key}` declares {}, but ASYNC FUNC must declare HANDLE or HANDLE<T>",
render_structural(declared)
);
}
if out.has_return && out.falls_through && !is_void {
bail!(
"function `{key}` declares {} but may fall through with no RETURN on some path",
render_structural(declared)
);
}
if !out.has_return {
if is_void {
return Ok(StaticTy::Void);
}
bail!(
"function `{key}` declares {} but has no RETURN on any path",
render_structural(declared)
);
}
if out.bare_return && !is_void {
bail!(
"function `{key}` declares {} but has a bare RETURN on some path; bare RETURN is only a void exit",
render_structural(declared)
);
}
if is_void {
if let Some((ty, line, _col)) = out.types.first() {
bail!(
"function `{key}` declares VOID but RETURN at line {line} yields {}",
render_structural(ty)
);
}
return Ok(StaticTy::Void);
}
if out.types.is_empty() {
bail!(
"function `{key}` declares {} but has no value RETURN on any path",
render_structural(declared)
);
}
for (ty, line, _col) in &out.types {
if !is_compatible(ty, declared) {
bail!(
"function `{key}` declares {} but RETURN at line {line} yields {}",
render_structural(declared),
render_structural(ty)
);
}
}
Ok(StaticTy::Ty(declared.clone()))
}
#[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 base_env_frames = env.env_frames.len();
let base_func_frames = env.func_frames.len();
let base_import_frames = env.import_frames.len();
let mut out = WalkOut {
falls_through: true,
has_return: false,
bare_return: false,
types: Vec::new(),
};
for (idx, step) in steps.iter().enumerate() {
self.visits += 1;
let site = match (&scope.site, &step.guard) {
(None, None) => None,
(Some(rule), None) | (None, Some(rule)) => Some(rule.clone()),
(Some(outer), Some(own)) => Some(GuardExpr::all(vec![outer.clone(), own.clone()])),
};
let scoped = Scope {
label: scope.label,
ret: scope.ret.clone(),
loops: scope.loops,
switches: scope.switches,
site,
line: step.line,
col: step.col,
idx,
};
let scope = &scoped;
for _ in 0..step.scope_enter {
env.push_frame();
}
if let Some(guard) = step.guard.as_ref()
&& !matches!(classify_guard(Some(guard)), GuardClass::Dead)
{
let mut names = Vec::new();
Self::guard_env_names(guard, &mut names);
for name in names {
self.check_env_name(env, &name, "env:", scope)?;
}
}
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.bare_return |= inner.bare_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.bare_return |= inner.bare_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();
}
if env.env_frames.len() > base_env_frames {
env.env_frames.pop();
}
if env.func_frames.len() > base_func_frames {
env.func_frames.pop();
}
if env.import_frames.len() > base_import_frames {
env.import_frames.pop();
}
}
}
Ok(out)
}
#[allow(clippy::too_many_arguments)]
fn check_plain_rhs(
&mut self,
expr: &Expr,
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
var: &str,
) -> Result<()> {
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
);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn check_capture_rhs(
&mut self,
var: &str,
tag: &TypeTag,
cmd: &StepKind,
env: &mut Env,
scope: &Scope,
step: &Step,
idx: usize,
depth: usize,
is_const: bool,
) -> Result<()> {
self.walk_wrapped(step, cmd, env, scope, idx, depth + 1)?;
if let Some(yield_tag) = self.capture_yield(cmd, env, scope.site.as_ref(), depth)?
&& self
.check_arg(
tag,
StaticTy::Ty(yield_tag.clone()),
&format!("step {}", idx + 1),
)
.is_err()
{
let kw = if is_const { KEYWORD_CONST } else { KEYWORD_LET };
bail!(
"step {}: {kw} ${} captures {} but declares {}",
idx + 1,
clean_var(var),
render_structural(&yield_tag),
render_structural(tag)
);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn check_await_rhs(
&mut self,
out_var: &str,
tag: &TypeTag,
task_var: &str,
env: &mut Env,
scope: &Scope,
idx: usize,
) -> Result<()> {
let key = clean_var(task_var);
let prefix = format!("step {}: ", idx + 1);
let handle_tag = check_var_binding_access(env, &key, scope.site.as_ref(), &prefix)?;
let payload = match handle_tag {
TypeTag::Handle => TypeTag::Any,
TypeTag::HandleOf(inner) => (*inner).clone(),
other => bail!(
"step {}: AWAIT ${} is {}, not HANDLE",
idx + 1,
clean_var(task_var),
render_structural(&other)
),
};
if matches!(payload, TypeTag::Void) {
bail!(
"step {}: AWAIT ${} is HANDLE<VOID>: no value to bind to `${}`; use bare AWAIT for join",
idx + 1,
clean_var(task_var),
clean_var(out_var)
);
}
if !is_compatible(&payload, tag) && !is_compatible(tag, &payload) {
if self
.check_arg(
tag,
StaticTy::Ty(payload.clone()),
&format!("step {}", idx + 1),
)
.is_err()
{
bail!(
"step {}: AWAIT ${} yields {} but `${}` declares {}",
idx + 1,
clean_var(task_var),
render_structural(&payload),
clean_var(out_var),
render_structural(tag)
);
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn check_async_rhs(
&mut self,
var: &str,
tag: &TypeTag,
body: &[Step],
env: &mut Env,
scope: &Scope,
idx: usize,
depth: usize,
) -> Result<()> {
let mut fork = env.fork();
let task = Scope {
label: scope.label,
ret: RetCtx::AsyncValue,
loops: 0,
switches: 0,
site: scope.site.clone(),
line: scope.line,
col: scope.col,
idx: scope.idx,
};
let inner = self.walk_body(body, &mut fork, &task, depth + 1)?;
let payload = match &tag {
TypeTag::Handle => TypeTag::Any,
TypeTag::HandleOf(inner_tag) => (**inner_tag).clone(),
_ => bail!(
"step {}: ASYNC `${}` declares {}, not HANDLE; every ASYNC position is HANDLE-headed",
idx + 1,
clean_var(var),
render_structural(tag)
),
};
if inner.bare_return && !matches!(payload, TypeTag::Void) {
bail!(
"step {}: ASYNC `${}` declares {} but task has a bare RETURN; bare RETURN is only a void exit",
idx + 1,
clean_var(var),
render_structural(tag)
);
}
if matches!(payload, TypeTag::Void) {
if let Some((ty, line, _col)) = inner.types.first() {
bail!(
"step {}: HANDLE<VOID> task RETURN at line {line} yields {}",
idx + 1,
render_structural(ty)
);
}
} else if inner.types.is_empty() {
if !matches!(payload, TypeTag::Any) {
bail!(
"step {}: ASYNC `${}` declares {} but task has no value RETURN",
idx + 1,
clean_var(var),
render_structural(tag)
);
}
} else {
for (ty, line, _col) in &inner.types {
if !is_compatible(ty, &payload) {
bail!(
"step {}: ASYNC `${}` declares {} but task RETURN at line {line} yields {}",
idx + 1,
clean_var(var),
render_structural(tag),
render_structural(ty)
);
}
}
}
Ok(())
}
fn effective_alias_targets(&self, env: &Env) -> super::native::AliasTargets {
let mut out = self.alias_targets.clone();
for (alias, targets) in env.visible_imports() {
let entry = out.entry(alias).or_default();
for target in targets {
if !entry.contains(&target) {
entry.push(target);
}
}
}
out
}
fn record_walk_import(
&mut self,
alias: &str,
path: &str,
guard: Option<&GuardExpr>,
env: &mut Env,
) {
let Some(rctx) = &self.import_ctx else {
return;
};
let defining = super::import::resolve_static_top_level(
rctx.parent,
rctx.dir,
rctx.files,
path,
rctx.is_entry,
);
env.append_import_target(alias.to_string(), defining, guard.cloned());
}
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,
bare_return: false,
types: Vec::new(),
};
match &step.kind {
StepKind::Return { expr, is_bare } => {
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);
}
}
if *is_bare {
let mut out = live;
out.has_return = true;
out.falls_through = false;
out.bare_return = true;
return Ok(out);
}
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, scope.line, scope.col));
}
Ok(out)
}
StepKind::Break => self.walk_break(KEYWORD_BREAK, scope, idx),
StepKind::Continue => self.walk_break(KEYWORD_CONTINUE, scope, idx),
StepKind::Exit(_) => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
Ok(WalkOut {
falls_through: false,
has_return: false,
bare_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.bare_return |= arm_out.bare_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.bare_return |= arm_out.bare_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::Switch {
discriminant,
cases,
default_body,
} => {
if let Some(disc) = discriminant {
self.infer_expr(disc, env, scope, idx, depth + 1)?;
}
let mut arms_terminal = true;
let mut out = live;
for (values, arm) in cases {
for value in values {
self.infer_expr(value, env, scope, idx, depth + 1)?;
}
let mut fork = env.fork();
let mut inner_scope = scope.clone();
inner_scope.switches += 1;
let arm_out = self.walk_body(arm, &mut fork, &inner_scope, depth + 1)?;
out.has_return |= arm_out.has_return;
out.bare_return |= arm_out.bare_return;
out.types.extend(arm_out.types);
arms_terminal &= !arm_out.falls_through;
}
match default_body {
Some(arm) => {
let mut fork = env.fork();
let mut inner_scope = scope.clone();
inner_scope.switches += 1;
let arm_out = self.walk_body(arm, &mut fork, &inner_scope, depth + 1)?;
out.has_return |= arm_out.has_return;
out.bare_return |= arm_out.bare_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.bare_return = body_out.bare_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.bare_return = body_out.bare_return;
out.types = body_out.types;
Ok(out)
}
StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} => {
let resolved = resolve_script_params(self.exec, name, params)?;
let declared = self
.exec
.resolve_tag(return_type)
.map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
self.exec
.check_return_tag(&format!("function `{name}` returns"), &declared)
.map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
let info = FuncInfo {
params: resolved,
declared,
is_async: *is_async,
body: body.clone(),
module: env.module.as_ref().map(|scope| scope.key.clone()),
name: name.clone(),
line: step.line,
col: step.col,
};
if let Some(frame) = env.func_frames.last_mut() {
frame.insert(name.clone(), info.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::Bind {
var,
decl_type,
is_const,
rhs,
} => {
let tag = self
.exec
.resolve_tag(decl_type)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
match rhs {
oxdock_parser::BindRhs::Expr(expr) => {
self.check_plain_rhs(expr, env, scope, idx, depth, var)?;
}
oxdock_parser::BindRhs::Capture(cmd) => {
self.check_capture_rhs(
var, &tag, cmd, env, scope, step, idx, depth, *is_const,
)?;
}
oxdock_parser::BindRhs::Async(body) => {
self.check_async_rhs(var, &tag, body, env, scope, idx, depth)?;
}
oxdock_parser::BindRhs::Await { task_var } => {
self.check_await_rhs(var, &tag, task_var, env, scope, idx)?;
}
}
self.exec
.check_declaration_tag(&format!("step {}", idx + 1), &tag)
.map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
let key = clean_var(var);
if *is_const {
env.declare_const(key, tag, step.guard.as_ref(), idx)?;
} else {
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
);
}
if env.is_const(&key, scope.site.as_ref()) {
bail!(
"step {}: cannot mutate CONST {key}: CONST bindings are deeply immutable",
idx + 1
);
}
let _ = env.read_guarded(&key, scope.site.as_ref())?;
self.infer_expr(expr, env, scope, idx, depth + 1)?;
Ok(live)
}
StepKind::AsyncBlock { body } => {
let mut fork = env.fork();
let task = Scope {
label: scope.label,
ret: RetCtx::AsyncStmt,
loops: 0,
switches: 0,
site: scope.site.clone(),
line: scope.line,
col: scope.col,
idx: scope.idx,
};
self.walk_body(body, &mut fork, &task, depth + 1)?;
Ok(live)
}
StepKind::Timeout { body, .. } => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
env.frames.push(HashMap::new());
env.func_frames.push(HashMap::new());
env.import_frames.push(HashMap::new());
let inner = self.walk_body(body, env, scope, depth + 1);
env.frames.pop();
env.func_frames.pop();
env.import_frames.pop();
let inner = inner?;
let mut out = live;
out.has_return = inner.has_return;
out.bare_return = inner.bare_return;
out.types = inner.types;
out.falls_through = inner.falls_through;
if !inner.falls_through {
return Ok(out);
}
Ok(out)
}
StepKind::Fail { body, .. } => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
env.frames.push(HashMap::new());
env.func_frames.push(HashMap::new());
env.import_frames.push(HashMap::new());
let inner = self.walk_body(body, env, scope, depth + 1);
env.frames.pop();
env.func_frames.pop();
env.import_frames.pop();
let inner = inner?;
let mut out = live;
out.has_return = inner.has_return;
out.bare_return = inner.bare_return;
out.falls_through = false;
Ok(out)
}
StepKind::Isolated { body } => {
self.isolated_depth += 1;
let saved = std::mem::replace(&mut env.env_frames, vec![HashSet::new()]);
env.frames.push(HashMap::new());
env.func_frames.push(HashMap::new());
env.import_frames.push(HashMap::new());
let inner = self.walk_body(body, env, scope, depth + 1);
env.frames.pop();
env.func_frames.pop();
env.import_frames.pop();
env.env_frames = saved;
let inner = inner?;
self.isolated_depth -= 1;
let mut out = live;
out.has_return = inner.has_return;
out.bare_return = inner.bare_return;
out.types = inner.types;
out.falls_through = inner.falls_through;
if !inner.falls_through {
return Ok(out);
}
Ok(out)
}
StepKind::InheritEnv { keys } => {
for key in keys {
env.declare_env(key.clone());
}
Ok(live)
}
StepKind::IsolatedInheritEnv { keys } => {
if self.isolated_depth == 0 {
return Err(anyhow::anyhow!(
"step {}: isolated allowlist outside ISOLATED",
idx + 1
));
}
for key in keys {
env.declare_env(key.clone());
}
Ok(live)
}
StepKind::RemoteBlock {
target,
vars,
env: header_env,
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());
}
for name in header_env {
self.check_env_name(env, name, "env:", scope).map_err(|_| {
anyhow::anyhow!(
"{} in {}: REMOTE '{target}' ships undeclared environment variable `env:{name}`: declare it first with ENV or INHERIT_ENV",
step_pos(scope.line, scope.col, scope.idx),
scope.label,
)
})?;
sealed.declare_env(name.clone());
}
sealed.push_frame();
let remote = Scope {
label: scope.label,
ret: RetCtx::Top,
loops: 0,
switches: 0,
site: None,
line: scope.line,
col: scope.col,
idx: scope.idx,
};
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(step, cmd, env, scope, idx, depth + 1)
}
StepKind::ReadLine { var } => {
let key = clean_var(var);
if env.is_const(&key, scope.site.as_ref()) {
bail!(
"step {}: cannot mutate CONST {key}: CONST bindings are deeply immutable",
idx + 1
);
}
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_const(&key, scope.site.as_ref()) {
bail!(
"step {}: cannot mutate CONST {key}: CONST bindings are deeply immutable",
idx + 1
);
}
if !env.is_declared(&key) {
env.insert_top(key, TypeTag::String, step.guard.as_ref());
}
Ok(live)
}
StepKind::Env { key, .. } => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
env.declare_env(key.clone());
Ok(live)
}
StepKind::ImportFile { path, alias } => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
self.record_walk_import(alias, path, step.guard.as_ref(), env);
Ok(live)
}
StepKind::ImportFuncs { path, alias, .. } => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
if let Some(alias) = alias {
self.record_walk_import(alias, path, step.guard.as_ref(), env);
}
Ok(live)
}
_ => {
self.check_step_args(&step.kind, env, scope, idx, depth)?;
match &step.kind {
StepKind::Await { var } | StepKind::Cancel { var } => {
let key = clean_var(var);
let prefix = format!("step {}: ", idx + 1);
check_var_binding_access(env, &key, scope.site.as_ref(), &prefix)?;
}
StepKind::WithIoBlock { bindings } => {
Self::check_pipe_bindings(env, bindings, scope, idx)?;
}
StepKind::ListAppend { list, item } => {
let key = clean_var(list);
if env.is_const(&key, scope.site.as_ref()) {
bail!(
"step {}: cannot mutate CONST {key}: CONST bindings are deeply immutable",
idx + 1
);
}
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::HandleOf(_)
| TypeTag::Void
| 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);
}
let mut failed: Option<anyhow::Error> = None;
kind.walk_raw_strings(&mut |text| {
if failed.is_none()
&& let Err(err) = self.check_template_env(text, env, scope, depth)
{
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);
let prefix = format!("step {}: ", idx + 1);
check_var_binding_access(env, &key, scope.site.as_ref(), &prefix)
}
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 key = clean_var(name);
let prefix = format!("step {}: ", idx + 1);
let tag = check_var_binding_access(env, &key, scope.site.as_ref(), &prefix)?;
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> {
let legal = if word == KEYWORD_BREAK {
scope.loops > 0 || scope.switches > 0
} else {
scope.loops > 0
};
if legal {
return Ok(WalkOut {
falls_through: true,
has_return: false,
bare_return: false,
types: Vec::new(),
});
}
match &scope.ret {
RetCtx::Top => {
if word == KEYWORD_BREAK {
bail!("step {}: BREAK outside loop or SWITCH", idx + 1)
} else {
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,
outer: &Step,
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,
line: outer.line,
col: outer.col,
};
self.walk_step(&step, env, scope, idx, depth)
}
fn capture_yield(
&mut self,
cmd: &StepKind,
env: &Env,
site: Option<&GuardExpr>,
depth: usize,
) -> Result<Option<TypeTag>> {
let mut current = cmd;
loop {
match current {
StepKind::WithIo { cmd, .. } => current = cmd,
StepKind::Timeout { body, .. } if body.len() == 1 => {
current = &body[0].kind;
}
StepKind::Call { name, .. } => {
let callee = self.resolve_call(name, env, site, depth)?;
return Ok(match callee.ret {
StaticTy::Ty(tag) => Some(tag),
StaticTy::Void => None,
});
}
StepKind::ImportFile { .. } => return Ok(None),
_ => return Ok(Some(TypeTag::String)),
}
}
}
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!(expected, TypeTag::Handle | TypeTag::HandleOf(_))
&& matches!(actual, TypeTag::Handle | TypeTag::HandleOf(_))
{
return match is_compatible(&actual, expected) {
true => Ok(()),
false => Err(exact_mismatch(ctx, expected, &actual)),
};
}
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::HandleOf(a), TypeTag::HandleOf(e)) => Self::check_exact(e, a, ctx),
(TypeTag::HandleOf(a), TypeTag::Handle) => {
if matches!(a.as_ref(), TypeTag::Void) {
return Err(exact_mismatch(ctx, expected, actual));
}
Ok(())
}
(TypeTag::Handle, TypeTag::HandleOf(e)) => {
if matches!(e.as_ref(), TypeTag::Any) {
Ok(())
} else {
Err(exact_mismatch(ctx, expected, actual))
}
}
(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 || field.default.is_some() => {}
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 missing_import_hint(&self, targets: &super::native::AliasTargets, name: &str) -> String {
super::native::missing_import_hint(
self.module_func_exports
.iter()
.map(|(file, exports)| (file.as_str(), exports.as_slice())),
targets,
name,
)
.unwrap_or_default()
}
fn find_frame_hit(
&self,
unit: &str,
base: &str,
nested: &[HashMap<String, FuncInfo>],
site: Option<&GuardExpr>,
) -> Option<(FuncInfo, String)> {
use super::native::FuncFrameView;
struct StaticView<'a> {
unit: &'a str,
nested: &'a [HashMap<String, FuncInfo>],
home: &'a HomeFuncs,
harvested: &'a HashMap<(String, String), String>,
first: &'a HashMap<(String, String), FuncInfo>,
site: Option<&'a GuardExpr>,
}
impl FuncFrameView for StaticView<'_> {
type Hit = (FuncInfo, String);
fn find_nested(&self, base: &str) -> Option<Self::Hit> {
for frame in self.nested.iter().rev() {
if let Some(info) = frame.get(base) {
let info = info.clone();
let key = format!("nested:{}:{base}:{}:{}", self.unit, info.line, info.col);
return Some((info, key));
}
}
None
}
fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit> {
let overloads = self.home.get(&(unit.to_string(), base.to_string()))?;
let mut pick: Option<FuncInfo> = None;
for (guard, info) in overloads {
if oxdock_parser::guards_overlap(guard.as_ref(), self.site) {
pick = Some(info.clone());
}
}
let info = pick?;
let key = super::native::file_func_key(unit, base);
Some((info, key))
}
fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit> {
let defining = self.harvested.get(&(unit.to_string(), base.to_string()))?;
let info = self
.first
.get(&(defining.clone(), base.to_string()))?
.clone();
let key = super::native::file_func_key(defining, base);
Some((info, key))
}
}
StaticView {
unit,
nested,
home: &self.home_funcs,
harvested: &self.harvested,
first: &self.harvest_first,
site,
}
.walk(unit, base)
}
fn resolve_call(
&mut self,
name: &str,
env: &Env,
site: Option<&GuardExpr>,
depth: usize,
) -> Result<Callee> {
let env_module = env.module.as_ref().map(|m| m.key.as_str());
let nested: &[_] = &env.func_frames;
let effective = self.effective_alias_targets(env);
let mut lookup = name.to_string();
{
match super::native::classify_alias_call(&effective, name, &|key| {
self.funcs.contains_key(key)
}) {
super::native::AliasResolution::Global => {}
super::native::AliasResolution::Canonical(key) => lookup = key,
super::native::AliasResolution::Unknown => {
bail!(
"unknown function `{name}`{}",
self.missing_import_hint(&effective, name)
);
}
super::native::AliasResolution::Ambiguous { alias, base, files } => {
bail!(
"{}",
super::native::ambiguous_alias_message(&alias, &base, &files)
);
}
super::native::AliasResolution::Any {
base,
files,
has_host,
} => {
if has_host {
bail!(
"unknown function `{name}`{}",
self.missing_import_hint(&effective, name)
);
}
let mut canonicals = Vec::new();
for file in files {
let canonical = super::native::file_func_key(file.as_str(), base.as_str());
let Some(info) = self.funcs.get(&canonical) else {
bail!(
"unknown function `{name}`{}",
self.missing_import_hint(&effective, name)
);
};
canonicals.push((canonical, info.clone()));
}
canonicals.sort_by(|a, b| a.0.cmp(&b.0));
let (_, first) = canonicals.first().expect("Any is never empty");
let unified = canonicals.iter().all(|(_, info)| {
info.params.len() == first.params.len()
&& info.params.iter().zip(first.params.iter()).all(
|((_, param_tag, optional), (_, first_tag, first_optional))| {
optional == first_optional && tags_equal(param_tag, first_tag)
},
)
&& tags_equal(&info.declared, &first.declared)
});
if !unified {
return Ok(Callee {
params: None,
ret: StaticTy::Ty(TypeTag::Any),
host_params: None,
});
}
let mut inferred = Vec::new();
for (key, info) in &canonicals {
inferred.push(self.func_return_owned(info, key, depth)?);
}
let (_, first) = canonicals.first().expect("Any is never empty");
let first_ret = inferred.first().expect("Any is never empty");
let returns_unified = inferred.iter().all(|ty| match (ty, first_ret) {
(StaticTy::Void, StaticTy::Void) => true,
(StaticTy::Ty(left), StaticTy::Ty(right)) => tags_equal(left, right),
_ => false,
});
let any_branch = inferred.iter().any(|ty| match ty {
StaticTy::Ty(tag) => tags_equal(tag, &TypeTag::Any),
StaticTy::Void => false,
});
if !returns_unified || any_branch {
return Ok(Callee {
params: None,
ret: StaticTy::Ty(TypeTag::Any),
host_params: None,
});
}
return Ok(Callee {
params: Some(first.params.clone()),
ret: first_ret.clone(),
host_params: None,
});
}
}
}
if lookup != name {
if let Some(info) = self.funcs.get(&lookup) {
let info = info.clone();
let ret = self.func_return_owned(&info, &lookup, depth)?;
let params = info.params;
return Ok(Callee {
params: Some(params),
ret,
host_params: None,
});
}
} else if let Some(base) = match name.split_once(MODULE_SEPARATOR) {
Some((head, tail)) if head == oxdock_parser::SCRIPT_MODULE_NAME => Some(tail),
Some(_) => None,
None => Some(name),
} {
let unit = super::import::unit_key(env_module);
if let Some((info, key)) = self.find_frame_hit(unit, base, nested, site) {
let ret = self.func_return_owned(&info, &key, 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),
param.optional,
)
})
.collect()
});
return Ok(Callee {
params,
ret,
host_params: meta.params.clone(),
});
}
if self.strict_qualified
&& let Some((alias, _)) = name.split_once(MODULE_SEPARATOR)
&& alias != oxdock_parser::SCRIPT_MODULE_NAME
&& !self.hosts.contains_key(name)
{
bail!(
"unknown function `{name}`{}",
self.missing_import_hint(&effective, name)
);
}
Ok(Callee {
params: None,
ret: StaticTy::Ty(TypeTag::Any),
host_params: None,
})
}
fn resolve_const_ref(
&self,
alias: &str,
name: &str,
env: &Env,
scope: &Scope,
) -> Result<TypeTag> {
use super::native::{
ConstHolders, ambiguous_alias_message, chase_const_forward, const_holder_files,
missing_const_hint,
};
let at = || step_pos(scope.line, scope.col, scope.idx);
let qualified = oxdock_parser::qualify(alias, name);
let view = CheckerConstView {
exports: &self.module_const_exports,
targets: &self.file_targets,
lets: &self.module_lets,
};
let effective = self.effective_alias_targets(env);
let files = match const_holder_files(&view, &effective, alias, name) {
ConstHolders::Found(files) => files,
ConstHolders::NoAlias => {
if self.strict_qualified {
bail!(
"{}: unknown CONST `{qualified}`: no import alias `{alias}` exports that name",
at()
);
}
return Ok(TypeTag::Any);
}
ConstHolders::Ambiguous { alias, base, files } => {
bail!(
"{}: {}",
at(),
ambiguous_alias_message(&alias, &base, &files).replacen("function", "CONST", 1)
);
}
};
let mut tags: Vec<TypeTag> = Vec::new();
for file in &files {
let terminals = chase_const_forward(&view, file, name, &qualified)
.map_err(|err| anyhow::anyhow!("{}: {err}", at()))?;
for terminal in &terminals {
let Some(binding) = self
.module_lets
.get(terminal)
.and_then(|lets| lets.iter().find(|entry| entry.name == name))
else {
continue;
};
if !binding.is_const {
bail!(
"{}: `{qualified}` is a LET binding and cannot be exported: only CONST bindings cross the module boundary",
at()
);
}
tags.push(binding.tag.clone());
}
}
if tags.len() > 1 {
let first = tags[0].clone();
if !tags.iter().all(|tag| tags_equal(&first, tag)) {
return Ok(TypeTag::Any);
}
}
match tags.into_iter().next() {
Some(tag) => Ok(tag),
None => {
let hint = missing_const_hint(&view, &effective, alias, name);
match hint {
Some(hint) => bail!("{}: unknown CONST `{qualified}`: {hint}", at()),
None => bail!(
"{}: unknown CONST `{qualified}`: no import alias `{alias}` exports that name",
at()
),
}
}
}
}
fn func_touches_module(&mut self, key: &str) -> Result<bool> {
let info = self.funcs.get(key).cloned();
let Some(info) = info else {
return Ok(false);
};
if info.module.is_none() {
return Ok(false);
}
let probe = std::rc::Rc::new(std::cell::Cell::new(false));
let _ = self.check_function_body_probed(key, &info, 0, Some(probe.clone()), false)?;
Ok(probe.get())
}
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, env, scope.site.as_ref(), 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) => (Self::script_required(shape), 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) => (Self::script_required(shape), 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(", "));
}
}
Ok(ret.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) => {
if let Some(text) = value.as_str() {
self.check_template_env(text, env, scope, depth)?;
}
Ok(StaticTy::Ty(literal_tag(value)))
}
Expr::Var { name } => {
let key = clean_var(name);
let prefix = loc(Some(&at()));
Ok(StaticTy::Ty(check_var_binding_access(
env,
&key,
scope.site.as_ref(),
&prefix,
)?))
}
Expr::ConstRef { alias, name } => {
let tag = self.resolve_const_ref(alias, name, env, scope)?;
Ok(StaticTy::Ty(tag))
}
Expr::Env(name) => {
self.check_env_name(env, name, "env:", scope)?;
Ok(StaticTy::Ty(TypeTag::String))
}
Expr::KeyPath { base, keys } => {
let key = clean_var(base);
let prefix = loc(Some(&at()));
let current = check_var_binding_access(env, &key, scope.site.as_ref(), &prefix)?;
let traversed = traverse_static_keypath(current, keys, &format!("{}: ", at()))?;
Ok(StaticTy::Ty(traversed))
}
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,
switches: 0,
site: scope.site.clone(),
line: scope.line,
col: scope.col,
idx: scope.idx,
},
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);
}
if out.types.is_empty() {
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);
let prefix = loc(Some(&at()));
check_var_binding_access(env, &key, scope.site.as_ref(), &prefix)?;
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 script_required(params: &[(String, TypeTag, bool)]) -> usize {
params.len() - params.iter().rev().take_while(|entry| entry.2).count()
}
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) => {
if let Some(text) = value.as_str() {
self.check_template_env(text, env, scope, depth)?;
}
stack.push(StaticTy::Ty(literal_tag(value)))
}
MathOp::Load { name } => {
let key = clean_var(name);
let tag = check_var_binding_access(env, &key, scope.site.as_ref(), "")?;
stack.push(StaticTy::Ty(tag));
}
MathOp::LoadConstRef { alias, name } => {
let tag = self.resolve_const_ref(alias, name, env, scope)?;
stack.push(StaticTy::Ty(tag));
}
MathOp::LoadEnv(name) => {
self.check_env_name(env, name, "env:", scope)?;
stack.push(StaticTy::Ty(TypeTag::String))
}
MathOp::LoadKeyPath { base, keys } => {
let key = clean_var(base);
let current = check_var_binding_access(env, &key, scope.site.as_ref(), "")?;
let traversed = traverse_static_keypath(current, keys, "")?;
stack.push(StaticTy::Ty(traversed));
}
MathOp::Call { name, arity } => {
let before = stack.len();
if before < *arity {
bail!("internal error: RPN stack underflow");
}
let taken: Vec<StaticTy> = stack.split_off(before - arity);
let blanks = vec![None; taken.len()];
let callee = self.resolve_call(name, env, scope.site.as_ref(), depth)?;
let ret = self.apply_checked(name, &callee, &taken, &blanks, None)?;
stack.push(ret);
}
MathOp::Inspect { name } => {
let key = clean_var(name);
check_var_binding_access(env, &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;
use oxdock_process::MockProcessManager;
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());
}
macro_rules! tag_coverage {
(
units: [ $($unit:ident),* $(,)? ],
shaped: [ $($shaped:ident ( $($payload:ident),* )),* $(,)? ],
special: [ $($special:ident),* $(,)? ]
) => {
fn variant_inventory() -> Vec<TypeTag> {
vec![
$( TypeTag::$unit, )*
$( $( TypeTag::$shaped(std::sync::Arc::new(TypeTag::$payload)), )* )*
$( special_representative(stringify!($special)), )*
]
}
fn anchor_exhaustive(tag: &TypeTag) {
match tag {
$( TypeTag::$unit => {} ),*,
$( TypeTag::$shaped(_) => {} ),*,
TypeTag::Custom(_) => {},
TypeTag::Record(_) => {},
TypeTag::Union(..) => {},
}
}
};
}
fn special_representative(which: &str) -> TypeTag {
match which {
"Custom" => TypeTag::Custom(oxdock_parser::startup_descriptors()[0].1),
"Record" => TypeTag::Record(
vec![oxdock_parser::Field {
name: "name".to_string(),
ty: TypeTag::String,
docs: "",
optional: false,
default: None,
alias: None,
}]
.into(),
),
"Union" => TypeTag::union(vec![TypeTag::Int, TypeTag::String]),
_ => unreachable!("tag_coverage special must name Custom, Record, or Union"),
}
}
tag_coverage! {
units: [String, Int, Float, Bool, List, Map, Pipe, Handle, Void, Duration, Path, Semaphore, Permit, Any],
shaped: [HandleOf(String, Int, Void, Any), ListOf(Int), MapOf(String)],
special: [Custom, Record, Union]
}
fn law_universe() -> Vec<TypeTag> {
use std::sync::Arc;
let mut universe = variant_inventory();
universe.extend([
TypeTag::HandleOf(Arc::new(TypeTag::Void)),
TypeTag::HandleOf(Arc::new(TypeTag::Any)),
TypeTag::HandleOf(Arc::new(TypeTag::Int)),
TypeTag::HandleOf(Arc::new(TypeTag::ListOf(Arc::new(TypeTag::Int)))),
TypeTag::HandleOf(Arc::new(TypeTag::Union(
"INT|STRING".into(),
vec![TypeTag::Int, TypeTag::String].into(),
))),
TypeTag::ListOf(Arc::new(TypeTag::Union(
"INT|STRING".into(),
vec![TypeTag::Int, TypeTag::String].into(),
))),
TypeTag::ListOf(Arc::new(TypeTag::ListOf(Arc::new(TypeTag::Int)))),
TypeTag::MapOf(Arc::new(TypeTag::Union(
"INT|STRING".into(),
vec![TypeTag::Int, TypeTag::String].into(),
))),
TypeTag::Record(
vec![
oxdock_parser::Field {
name: "req".to_string(),
ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
docs: "",
optional: false,
default: None,
alias: None,
},
oxdock_parser::Field {
name: "opt".to_string(),
ty: TypeTag::Int,
docs: "",
optional: true,
default: None,
alias: None,
},
]
.into(),
),
TypeTag::Union(
"INT|STRING|BOOL".into(),
vec![TypeTag::Int, TypeTag::String, TypeTag::Bool].into(),
),
TypeTag::Union(
"LIST<INT>|MAP<STRING>".into(),
vec![
TypeTag::ListOf(Arc::new(TypeTag::Int)),
TypeTag::MapOf(Arc::new(TypeTag::String)),
]
.into(),
),
]);
universe
}
#[test]
fn anchor_covers_inventory() {
for tag in variant_inventory() {
anchor_exhaustive(&tag);
}
}
#[test]
fn subtyping_is_reflexive() {
for tag in law_universe() {
assert!(
is_compatible(&tag, &tag),
"must admit itself: {}",
render_structural(&tag)
);
}
}
#[test]
fn void_is_bottom() {
for tag in law_universe() {
let is_void = matches!(tag, TypeTag::Void);
assert_eq!(
is_compatible(&TypeTag::Void, &tag),
is_void,
"VOID actual vs {}",
render_structural(&tag)
);
assert_eq!(
is_compatible(&tag, &TypeTag::Void),
is_void,
"{} actual vs VOID",
render_structural(&tag)
);
}
}
#[test]
fn any_declared_is_top_for_values() {
for tag in law_universe() {
if matches!(tag, TypeTag::Void) {
continue;
}
assert!(
is_compatible(&tag, &TypeTag::Any),
"{} must flow into ANY",
render_structural(&tag)
);
}
}
#[test]
fn any_actual_admits_nothing_concrete() {
for tag in law_universe() {
assert_eq!(
is_compatible(&TypeTag::Any, &tag),
matches!(tag, TypeTag::Any),
"ANY actual vs {}",
render_structural(&tag)
);
}
}
#[test]
fn handle_bare_is_any_payload() {
use std::sync::Arc;
for payload in [TypeTag::String, TypeTag::Int, TypeTag::Void, TypeTag::Any] {
let shaped = TypeTag::HandleOf(Arc::new(payload));
assert_eq!(
is_compatible(&shaped, &TypeTag::Handle),
is_compatible(&shaped, &TypeTag::HandleOf(Arc::new(TypeTag::Any))),
"shaped->bare must equal shaped->HANDLE<ANY>: {}",
render_structural(&shaped)
);
assert!(
!is_compatible(
&TypeTag::HandleOf(Arc::new(TypeTag::Void)),
&TypeTag::Handle
),
"HANDLE<VOID> must never erase to HANDLE"
);
}
assert!(is_compatible(
&TypeTag::Handle,
&TypeTag::HandleOf(Arc::new(TypeTag::Any))
));
assert!(!is_compatible(
&TypeTag::Handle,
&TypeTag::HandleOf(Arc::new(TypeTag::String))
));
}
#[test]
fn subtyping_is_transitive() {
let universe = law_universe();
for a in &universe {
for b in &universe {
if !is_compatible(a, b) {
continue;
}
for c in &universe {
if !is_compatible(b, c) {
continue;
}
assert!(
is_compatible(a, c),
"transitivity violated: {} <: {} <: {} but {} !<: {}",
render_structural(a),
render_structural(b),
render_structural(c),
render_structural(a),
render_structural(c)
);
}
}
}
}
#[test]
fn union_subtyping_is_covariant() {
let narrow = TypeTag::Union(
"INT|STRING".into(),
vec![TypeTag::Int, TypeTag::String].into(),
);
let wide = TypeTag::Union(
"INT|STRING|BOOL".into(),
vec![TypeTag::Int, TypeTag::String, TypeTag::Bool].into(),
);
assert!(is_compatible(&TypeTag::Int, &narrow));
assert!(is_compatible(&TypeTag::String, &narrow));
assert!(!is_compatible(&TypeTag::Bool, &narrow));
assert!(is_compatible(&narrow, &wide));
assert!(!is_compatible(&wide, &narrow));
assert!(!is_compatible(&narrow, &TypeTag::Int));
}
#[test]
fn check_exact_handles_mirror_compatible() {
use std::sync::Arc;
type C = Checker<'static, MockProcessManager>;
let string_handle = || TypeTag::HandleOf(Arc::new(TypeTag::String));
let void_handle = || TypeTag::HandleOf(Arc::new(TypeTag::Void));
let any_handle = || TypeTag::HandleOf(Arc::new(TypeTag::Any));
assert!(C::check_exact(&TypeTag::Handle, &string_handle(), "t").is_ok());
assert!(C::check_exact(&TypeTag::Handle, &void_handle(), "t").is_err());
assert!(C::check_exact(&string_handle(), &string_handle(), "t").is_ok());
assert!(C::check_exact(&string_handle(), &any_handle(), "t").is_ok());
assert!(C::check_exact(&any_handle(), &TypeTag::Handle, "t").is_ok());
assert!(C::check_exact(&string_handle(), &TypeTag::Handle, "t").is_err());
assert!(C::check_exact(&void_handle(), &TypeTag::Handle, "t").is_err());
}
}