use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use anyhow::Result;
use oxdock_fs::{CargoScratch, GuardedPath, WorkspaceFs, WorkspaceSelection};
use oxdock_parser::constants::KEYWORD_CONST;
use oxdock_parser::{Field, GuardExpr, Step, TypeDescriptor, TypeTag, Value, sigil_var};
use oxdock_process::{BackgroundHandle, CancelHub, CommandContext, ProcessManager};
use super::exit::exit_code_of;
use super::io::{ExactCapture, ExecIo, SlidingWindow, TeeStream};
use super::native::FunctionRegistry;
use oxdock_pipe::KeeperGuard;
pub(super) const MAX_CALL_DEPTH: usize = 64;
pub(super) const MAX_RETAINED_FINISHED: usize = 128;
pub const MAX_RUNNING_TASKS: usize = 64;
pub(super) struct TaskSlotGuard {
counter: Arc<AtomicU64>,
}
impl TaskSlotGuard {
pub(super) fn new(counter: Arc<AtomicU64>) -> Self {
Self { counter }
}
}
impl Drop for TaskSlotGuard {
fn drop(&mut self) {
self.counter.fetch_sub(1, Ordering::SeqCst);
}
}
const TASK_TAIL_CAP: usize = 64 * 1024;
pub fn const_mutation_error(what: &str) -> anyhow::Error {
anyhow::anyhow!(
"cannot mutate {kw} {what}: {kw} bindings are deeply immutable",
kw = KEYWORD_CONST,
)
}
pub struct ExecState<P: ProcessManager> {
pub(super) fs: Box<dyn WorkspaceFs>,
pub(super) cargo_scratch: CargoScratch,
pub(super) seed: Arc<HashMap<String, String>>,
pub(super) cwd: GuardedPath,
pub(super) envs: Arc<HashMap<String, String>>,
pub(super) isolated_stack: Vec<Arc<HashMap<String, String>>>,
pub(super) bg_children: Vec<BgChild>,
pub(super) scope_stack: Vec<ScopeSnapshot>,
pub(super) io: ExecIo,
pub(super) assert_windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
pub(super) assert_windows_stderr: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
pub(super) exact_stdout: Arc<Mutex<HashMap<usize, ExactCapture>>>,
pub(super) var_scopes: Vec<HashMap<String, (TypeTag, Value)>>,
pub(super) const_scopes: Vec<HashSet<String>>,
pub(super) types: HashMap<String, &'static TypeDescriptor>,
pub(super) record_schemas: HashMap<String, Arc<[Field]>>,
pub(super) module_states:
HashMap<(String, std::any::TypeId), Arc<dyn std::any::Any + Send + Sync>>,
pub(super) type_aliases: HashMap<String, String>,
pub(super) type_env_digest: u64,
#[allow(dead_code)]
pub(super) cancel_token: Arc<AtomicBool>,
#[allow(dead_code)]
pub(super) cancel_hub: Arc<CancelHub>,
#[allow(dead_code)]
pub(super) active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
#[allow(dead_code)]
pub(super) named_tasks: Arc<Mutex<HashMap<u64, Arc<TaskEntry>>>>,
#[allow(dead_code)]
pub(super) next_task_id: Arc<AtomicU64>,
pub(super) live_tasks: Arc<AtomicU64>,
pub(super) inside_async: bool,
pub(super) keeper_expiry: Option<KeeperExpiry>,
pub(super) cancellable: bool,
pub(super) reap_floor: Option<u64>,
pub(super) functions: FunctionRegistry<P>,
pub(super) entry_file: Option<GuardedPath>,
pub(super) import_stack: Vec<GuardedPath>,
pub(super) modules: HashMap<String, ModuleRecord>,
pub(super) validated_modules: HashSet<String>,
pub(super) module_stack: Vec<Option<String>>,
pub(super) executed_alias_targets: HashMap<String, super::native::AliasTargets>,
pub(super) scope_alias_frames: Vec<ScopeAliasFrame>,
pub(super) call_alias_frames: Vec<CallAliasFrame>,
pub(super) func_floors: Vec<usize>,
pub(super) harvest_map: HashMap<(String, String), String>,
pub(super) module_table: oxdock_parser::ModuleTable,
pub(super) call_depth: usize,
pub(super) init_inherit_stack: Vec<Vec<String>>,
pub(super) init_scope_depths: Vec<usize>,
pub(super) task_id: u64,
pub(super) push_manifest: Vec<(String, String)>,
pub(super) _marker: PhantomData<P>,
}
pub(super) struct ScopeSnapshot {
pub(super) cwd: GuardedPath,
pub(super) selection: WorkspaceSelection,
pub(super) envs: Arc<HashMap<String, String>>,
}
#[derive(Clone, Default)]
pub(super) struct ScopeAliasFrame {
pub(super) depth: usize,
pub(super) unit: String,
pub(super) targets: super::native::AliasTargets,
}
#[derive(Clone, Default)]
pub(super) struct CallAliasFrame {
pub(super) unit: String,
pub(super) depth: usize,
pub(super) targets: super::native::AliasTargets,
}
#[derive(Clone, Default)]
pub(super) struct ModuleRecord {
pub(super) steps: Vec<Step>,
pub(super) exports: oxdock_parser::Exports,
pub(super) init: Option<ModuleInit>,
pub(super) top_funcs: HashMap<String, Vec<RawFuncDef>>,
}
impl ModuleInit {
pub(super) fn entry_seed(envs: HashMap<String, String>, cwd: GuardedPath) -> Self {
Self {
vars: HashMap::new(),
const_vars: HashSet::new(),
return_value: Value::string(String::new()),
envs,
inherit_names: Vec::new(),
selection: WorkspaceSelection::Snapshot,
cwd,
}
}
}
impl ModuleRecord {
pub(super) fn entry_record(envs: HashMap<String, String>, cwd: GuardedPath) -> Self {
Self {
steps: Vec::new(),
exports: oxdock_parser::Exports::default(),
init: Some(ModuleInit::entry_seed(envs, cwd)),
top_funcs: HashMap::new(),
}
}
}
#[derive(Clone, Debug, Default)]
pub(super) struct RawFuncDef {
pub(super) params: Vec<(String, String, bool)>,
pub(super) return_spelling: String,
pub(super) is_async: bool,
pub(super) body: Vec<Step>,
pub(super) guard: Option<GuardExpr>,
pub(super) jail: Option<(WorkspaceSelection, GuardedPath)>,
}
#[derive(Clone)]
pub(super) struct ModuleInit {
pub(super) vars: HashMap<String, (TypeTag, Value)>,
pub(super) const_vars: HashSet<String>,
pub(super) return_value: Value,
pub(super) envs: HashMap<String, String>,
pub(super) inherit_names: Vec<String>,
pub(super) selection: WorkspaceSelection,
pub(super) cwd: GuardedPath,
}
pub(super) struct BgChild {
pub(super) handle: Box<dyn BackgroundHandle>,
pub(super) task_id: u64,
}
#[derive(Clone)]
pub(super) struct TaskCompletion {
pub(super) ok: bool,
pub(super) exit_code: i64,
pub(super) result: Option<Value>,
pub(super) error: String,
}
pub(super) struct TaskObservation {
pub(super) running: bool,
pub(super) ok: bool,
pub(super) exit_code: i64,
pub(super) result: Option<Value>,
pub(super) error: String,
}
pub(super) struct TaskTails {
out: Vec<u8>,
err: Vec<u8>,
total_out: u64,
total_err: u64,
}
impl TaskTails {
pub(super) fn new() -> Self {
Self {
out: Vec::new(),
err: Vec::new(),
total_out: 0,
total_err: 0,
}
}
pub(super) fn push(&mut self, stream: TeeStream, bytes: &[u8]) {
let (buf, total) = match stream {
TeeStream::Stdout => (&mut self.out, &mut self.total_out),
TeeStream::Stderr => (&mut self.err, &mut self.total_err),
};
*total += bytes.len() as u64;
buf.extend_from_slice(bytes);
let excess = buf.len().saturating_sub(TASK_TAIL_CAP);
if excess > 0 {
buf.drain(..excess);
}
}
pub(super) fn snapshot(&self) -> (String, String, u64) {
let dropped = self.total_out.saturating_sub(self.out.len() as u64)
+ self.total_err.saturating_sub(self.err.len() as u64);
(
String::from_utf8_lossy(&self.out).into_owned(),
String::from_utf8_lossy(&self.err).into_owned(),
dropped,
)
}
}
pub(super) enum TaskPhase {
Running,
Awaiting,
Cancelled,
Completed,
}
pub(super) struct TaskEntryState {
pub(super) phase: TaskPhase,
pub(super) handle: Option<Box<dyn BackgroundHandle>>,
pub(super) reaped: bool,
pub(super) return_value: Option<Value>,
pub(super) completion: Option<TaskCompletion>,
pub(super) returns_value: bool,
}
pub(super) struct TaskEntry {
pub(super) state: Mutex<TaskEntryState>,
pub(super) done: Condvar,
pub(super) tails: Arc<Mutex<TaskTails>>,
}
impl TaskEntry {
pub(super) fn is_live(&self) -> bool {
let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
match guard.phase {
TaskPhase::Running => match guard.handle.as_mut() {
Some(handle) => matches!(handle.try_wait(), Ok(None)),
None => false,
},
TaskPhase::Awaiting => true,
TaskPhase::Completed | TaskPhase::Cancelled => false,
}
}
pub(super) fn new(
handle: Box<dyn BackgroundHandle>,
returns_value: bool,
tails: Arc<Mutex<TaskTails>>,
) -> Self {
Self {
state: Mutex::new(TaskEntryState {
phase: TaskPhase::Running,
handle: Some(handle),
reaped: false,
return_value: None,
completion: None,
returns_value,
}),
done: Condvar::new(),
tails,
}
}
pub(super) fn snapshot_tails(&self) -> (String, String, u64) {
self.tails
.lock()
.map(|tails| tails.snapshot())
.unwrap_or_else(|e| e.into_inner().snapshot())
}
pub(super) fn observe_completion(&self) -> TaskObservation {
let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
if let Some(done) = guard.completion.clone() {
return TaskObservation {
running: false,
ok: done.ok,
exit_code: done.exit_code,
result: done.result,
error: done.error,
};
}
if !matches!(guard.phase, TaskPhase::Running) {
return TaskObservation {
running: false,
ok: false,
exit_code: -1,
result: None,
error: "task handle was not found or has already been awaited".to_string(),
};
}
match guard.handle.as_mut() {
None => TaskObservation {
running: true,
ok: true,
exit_code: -1,
result: None,
error: String::new(),
},
Some(handle) => match handle.try_wait() {
Ok(Some(status)) => {
let completion = TaskCompletion {
ok: status.success(),
exit_code: status.code().map(i64::from).unwrap_or(-1),
result: guard.return_value.clone(),
error: if status.success() {
String::new()
} else {
format!("task exited with status {status}")
},
};
guard.completion = Some(TaskCompletion {
ok: completion.ok,
exit_code: completion.exit_code,
result: completion.result.clone(),
error: completion.error.clone(),
});
TaskObservation {
running: false,
ok: completion.ok,
exit_code: completion.exit_code,
result: completion.result,
error: completion.error,
}
}
Ok(None) => TaskObservation {
running: true,
ok: true,
exit_code: -1,
result: None,
error: String::new(),
},
Err(err) => {
let completion = TaskCompletion {
ok: false,
exit_code: exit_code_of(&err).unwrap_or(1),
result: None,
error: format!("{err:#}"),
};
guard.completion = Some(TaskCompletion {
ok: completion.ok,
exit_code: completion.exit_code,
result: completion.result.clone(),
error: completion.error.clone(),
});
TaskObservation {
running: false,
ok: completion.ok,
exit_code: completion.exit_code,
result: completion.result,
error: completion.error,
}
}
},
}
}
pub(super) fn wait_reaped(&self) {
let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
while !guard.reaped {
guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
}
}
pub(super) fn finish_teardown(&self) {
{
let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
guard.handle = None;
guard.reaped = true;
}
self.done.notify_all();
}
}
pub(super) struct KeeperExpiry {
body_addr: usize,
body_len: usize,
map: HashMap<usize, Vec<KeeperGuard>>,
}
impl KeeperExpiry {
pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
Self {
body_addr: steps.as_ptr() as usize,
body_len: steps.len(),
map,
}
}
pub(super) fn matches(&self, steps: &[Step]) -> bool {
self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
}
pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
if self.matches(steps) {
drop(self.map.remove(&idx));
}
self.map.is_empty()
}
}
pub(super) type FileCallCtx = (
HashMap<String, String>,
Vec<String>,
WorkspaceSelection,
GuardedPath,
);
impl<P: ProcessManager> ExecState<P> {
pub(super) fn get_env(&self, key: &str) -> Option<&str> {
if let Some(v) = self.envs.get(key) {
return Some(v.as_str());
}
#[allow(clippy::disallowed_macros)]
if cfg!(windows) {
return self
.envs
.iter()
.find(|(k, _)| oxdock_process::names_eq(k, key))
.map(|(_, v)| v.as_str());
}
None
}
pub(super) fn command_ctx(&self) -> Result<CommandContext> {
let cwd = self.fs.resolve_write(&self.cwd, ".")?;
self.cargo_scratch.ensure_materialized()?;
Ok(CommandContext::new(
&cwd.into(),
Arc::clone(&self.envs),
&self.cargo_scratch,
self.fs.root(),
self.fs.build_context(),
))
}
pub(super) fn alloc_task_id(&mut self) -> anyhow::Result<u64> {
self.bg_children
.retain_mut(|child| match child.handle.try_wait() {
Ok(None) => true,
Ok(Some(status)) => !status.success(),
Err(_) => true,
});
self.live_tasks
.try_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
(n < MAX_RUNNING_TASKS as u64).then_some(n + 1)
})
.map_err(|_| {
anyhow::anyhow!(
"concurrency limit exceeded: maximum of {MAX_RUNNING_TASKS} running background tasks allowed"
)
})?;
let id = self.next_task_id.fetch_add(1, Ordering::SeqCst);
self.sweep_finished_tasks();
Ok(id)
}
fn sweep_finished_tasks(&self) {
let mut finished: Vec<u64> = Vec::new();
{
let named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
for (id, entry) in named.iter() {
if !entry.is_live() {
finished.push(*id);
}
}
}
if finished.len() <= MAX_RETAINED_FINISHED {
return;
}
finished.sort_unstable();
let mut named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
for id in finished.iter().take(finished.len() - MAX_RETAINED_FINISHED) {
named.remove(id);
}
}
#[allow(dead_code)]
pub(super) fn fork(&self) -> Self {
let mut executed_alias_targets = self.executed_alias_targets.clone();
for frame in &self.scope_alias_frames {
for (alias, targets) in &frame.targets {
executed_alias_targets
.entry(frame.unit.clone())
.or_default()
.entry(alias.clone())
.or_default()
.extend(targets.iter().cloned());
}
}
Self {
fs: self.fs.clone_box(),
cargo_scratch: self.cargo_scratch.clone(),
seed: Arc::clone(&self.seed),
cwd: self.cwd.clone(),
envs: Arc::clone(&self.envs),
bg_children: Vec::new(),
scope_stack: Vec::new(),
isolated_stack: self.isolated_stack.clone(),
io: self.io.clone(),
assert_windows: Arc::clone(&self.assert_windows),
assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
exact_stdout: Arc::clone(&self.exact_stdout),
var_scopes: self.var_scopes.clone(),
const_scopes: self.const_scopes.clone(),
cancel_token: Arc::new(AtomicBool::new(false)),
cancel_hub: Arc::new(CancelHub::with_counter(self.cancel_hub.worker_counter())),
active_process: Arc::new(Mutex::new(None)),
named_tasks: Arc::clone(&self.named_tasks),
next_task_id: Arc::clone(&self.next_task_id),
live_tasks: Arc::clone(&self.live_tasks),
inside_async: true,
keeper_expiry: None,
cancellable: self.cancellable,
reap_floor: self.reap_floor,
functions: self.functions.clone(),
entry_file: self.entry_file.clone(),
import_stack: self.import_stack.clone(),
modules: self.modules.clone(),
validated_modules: self.validated_modules.clone(),
module_stack: self.module_stack.clone(),
executed_alias_targets,
call_alias_frames: self.call_alias_frames.clone(),
scope_alias_frames: Vec::new(),
init_scope_depths: Vec::new(),
func_floors: self.func_floors.clone(),
harvest_map: self.harvest_map.clone(),
module_table: self.module_table.clone(),
types: self.types.clone(),
record_schemas: self.record_schemas.clone(),
module_states: self.module_states.clone(),
type_aliases: self.type_aliases.clone(),
type_env_digest: self.type_env_digest,
call_depth: self.call_depth,
init_inherit_stack: self.init_inherit_stack.clone(),
task_id: self.task_id,
push_manifest: Vec::new(),
_marker: PhantomData,
}
}
pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
pipe.declaring_task() == task_id && !pipe.has_escaped()
}
pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
Self::can_promote_in_task(pipe, self.task_id)
}
pub(super) fn mark_captured_pipes_escaped(&self) {
for scope in self.var_scopes.iter() {
for (_, value) in scope.values() {
mark_value_pipes_escaped(value);
}
}
for record in self.modules.values() {
if let Some(init) = record.init.as_ref() {
for entry in init.vars.values() {
mark_value_pipes_escaped(&entry.1);
}
}
}
}
pub(super) fn push_var_scope(&mut self) {
self.var_scopes.push(HashMap::new());
self.const_scopes.push(HashSet::new());
}
pub(super) fn pop_var_scope(&mut self) {
self.var_scopes.pop();
self.const_scopes.pop();
}
pub(super) fn reset_module_env(&mut self, envs: HashMap<String, String>) {
self.envs = Arc::new(envs);
}
pub(super) fn is_entry_top_level(&self) -> bool {
self.call_depth == 0 && self.module_stack.is_empty() && self.scope_stack.is_empty()
}
pub(super) fn callee_file_ctx(
&self,
module_key: Option<&str>,
def_jail: Option<(WorkspaceSelection, GuardedPath)>,
) -> Option<FileCallCtx> {
let unit = super::import::unit_key(module_key);
if let Some((selection, cwd)) = def_jail {
let (envs, inherit_names) = self.modules.get(unit).and_then(|record| {
record
.init
.as_ref()
.map(|init| (init.envs.clone(), init.inherit_names.clone()))
})?;
return Some((envs, inherit_names, selection, cwd));
}
self.modules.get(unit).and_then(|record| {
record.init.as_ref().map(|init| {
(
init.envs.clone(),
init.inherit_names.clone(),
init.selection,
init.cwd.clone(),
)
})
})
}
pub(super) fn push_scope(&mut self) {
self.scope_stack.push(ScopeSnapshot {
cwd: self.cwd.clone(),
selection: self.fs.selection(),
envs: Arc::clone(&self.envs),
});
self.functions.push_scope();
self.push_var_scope();
}
pub(super) fn pop_scope(&mut self) -> Result<()> {
let snapshot = self
.scope_stack
.pop()
.ok_or_else(|| anyhow::anyhow!("scope stack underflow during pop"))?;
self.fs.restore_selection(snapshot.selection);
self.cwd = snapshot.cwd;
self.envs = snapshot.envs;
self.functions.pop_scope();
self.pop_var_scope();
let depth = self.scope_stack.len();
self.scope_alias_frames.retain(|frame| frame.depth <= depth);
Ok(())
}
pub(super) fn declare_var(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
if self
.var_scopes
.last()
.map(|s| s.contains_key(&key))
.unwrap_or(false)
{
anyhow::bail!(
"redeclaration error: ${} already declared in this scope; use ${} = ... to mutate",
key,
key
);
}
let coerced = super::args::coerce_value(value, &kind)?;
let scope = self
.var_scopes
.last_mut()
.ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
scope.insert(key, (kind, coerced));
Ok(())
}
pub(super) fn declare_const(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
let at_entry_top = self.is_entry_top_level();
if self
.var_scopes
.last()
.map(|s| s.contains_key(&key))
.unwrap_or(false)
{
anyhow::bail!(
"redeclaration error: {key} already declared in this scope; {kw} bindings are immutable and cannot redeclare it",
kw = KEYWORD_CONST,
);
}
let coerced = super::args::coerce_value(value, &kind)?;
let frozen = Value::deep_freeze(&coerced);
let scope = self
.var_scopes
.last_mut()
.ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
scope.insert(key.clone(), (kind.clone(), frozen.clone()));
if let Some(frame) = self.const_scopes.last_mut() {
frame.insert(key.clone());
}
if at_entry_top {
if let Some(init) = self
.modules
.get_mut(super::import::ENTRY_UNIT)
.and_then(|record| record.init.as_mut())
{
init.vars.insert(key.clone(), (kind, frozen));
init.const_vars.insert(key);
}
}
Ok(())
}
fn entry_fallback_allowed(&self) -> bool {
if self.current_module().is_some() {
return false;
}
match self.module_stack.len() {
0 => true,
1 => true,
_ => matches!(
self.module_stack.get(self.module_stack.len() - 2),
None | Some(None)
),
}
}
fn entry_const_init(&self) -> Option<&ModuleInit> {
if !self.entry_fallback_allowed() {
return None;
}
self.modules.get(super::import::ENTRY_UNIT)?.init.as_ref()
}
pub(super) fn is_const_var(&self, key: &str) -> bool {
for idx in (0..self.var_scopes.len()).rev() {
if self.var_scopes[idx].contains_key(key) {
return self
.const_scopes
.get(idx)
.is_some_and(|frame| frame.contains(key));
}
}
if let Some(module) = self.current_module()
&& let Some(record) = self.modules.get(&module)
&& let Some(init) = record.init.as_ref()
&& init.vars.contains_key(key)
{
return init.const_vars.contains(key);
}
self.entry_const_init()
.is_some_and(|init| init.vars.contains_key(key) && init.const_vars.contains(key))
}
pub(super) fn declare_binding(
&mut self,
key: String,
kind: TypeTag,
value: Value,
is_const: bool,
) -> Result<()> {
if is_const {
self.declare_const(key, kind, value)
} else {
self.declare_var(key, kind, value)
}
}
pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> Result<()> {
if self.is_const_var(key) {
return Err(const_mutation_error(key));
}
let kind = self
.var_scopes
.iter()
.rev()
.find_map(|s| s.get(key).map(|(k, _)| k.clone()))
.or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
.ok_or_else(|| {
anyhow::anyhow!(
"undeclared variable ${key}: declare it first with LET ${key}: TYPE = ..."
)
})?;
let coerced = super::args::coerce_value(value, &kind)?;
for scope in self.var_scopes.iter_mut().rev() {
if let Some(slot) = scope.get_mut(key) {
slot.1 = coerced;
return Ok(());
}
}
if let Some((_, stored)) = self.module_var_mut(key) {
*stored = coerced;
return Ok(());
}
anyhow::bail!("undeclared variable ${key}");
}
pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> Result<()> {
if self.is_const_var(key) {
return Err(const_mutation_error(key));
}
let kind = self
.var_scopes
.iter()
.rev()
.find_map(|s| s.get(key).map(|(k, _)| k.clone()))
.or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
.ok_or_else(|| {
anyhow::anyhow!(
"undeclared variable ${key}: declare it first with LET ${key}: LIST<...> = ..."
)
})?;
let element = match kind {
TypeTag::List => None,
TypeTag::ListOf(element) => Some(element.as_ref().clone()),
_ => {
anyhow::bail!("LIST_APPEND ${key}: variable is {}, not LIST", kind.name());
}
};
for scope in self.var_scopes.iter_mut().rev() {
if let Some(slot) = scope.get_mut(key) {
if slot.1.is_frozen() {
return Err(const_mutation_error(key));
}
let list = slot.1.as_list_mut().ok_or_else(|| {
anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
})?;
if let Some(expected) = element {
oxdock_parser::check_value_at(
&expected,
&item,
&format!("{}[{}]", sigil_var(key), list.len()),
)?;
}
list.push(item);
return Ok(());
}
}
if let Some((_, value)) = self.module_var_mut(key) {
if value.is_frozen() {
return Err(const_mutation_error(key));
}
let list = value.as_list_mut().ok_or_else(|| {
anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
})?;
if let Some(expected) = element {
oxdock_parser::check_value_at(
&expected,
&item,
&format!("{}[{}]", sigil_var(key), list.len()),
)?;
}
list.push(item);
return Ok(());
}
anyhow::bail!("undeclared variable ${key}");
}
pub(super) fn get_var(&self, key: &str) -> Option<Value> {
for scope in self.var_scopes.iter().rev() {
if let Some((_, value)) = scope.get(key) {
return Some(value.clone());
}
}
if let Some((_, value)) = self.module_var(key) {
return Some(value.clone());
}
if let Some(init) = self.entry_const_init()
&& let Some((_, value)) = init.vars.get(key)
&& init.const_vars.contains(key)
{
return Some(value.clone());
}
None
}
pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
for scope in self.var_scopes.iter().rev() {
if let Some(entry) = scope.get(key) {
return Some(entry.clone());
}
}
if let Some(entry) = self.module_var(key) {
return Some(entry.clone());
}
if let Some(init) = self.entry_const_init()
&& let Some(entry) = init.vars.get(key)
&& init.const_vars.contains(key)
{
return Some(entry.clone());
}
None
}
pub(super) fn current_module(&self) -> Option<String> {
match self.module_stack.last() {
Some(Some(key)) => Some(key.clone()),
_ => None,
}
}
pub(super) fn unit_top_funcs(&self, unit: &str) -> Option<&HashMap<String, Vec<RawFuncDef>>> {
self.modules.get(unit).map(|record| &record.top_funcs)
}
fn module_var(&self, key: &str) -> Option<&(TypeTag, Value)> {
self.module_store()?.get(key)
}
fn module_var_mut(&mut self, key: &str) -> Option<&mut (TypeTag, Value)> {
self.module_store_mut()?.get_mut(key)
}
pub(super) fn all_vars(&self) -> HashMap<String, Value> {
let mut result = HashMap::new();
for scope in self.var_scopes.iter().rev() {
for (k, (_, v)) in scope {
result.entry(k.clone()).or_insert_with(|| v.clone());
}
}
if let Some(store) = self.module_store() {
for (k, (_, v)) in store {
result.entry(k.clone()).or_insert_with(|| v.clone());
}
}
if let Some(init) = self.entry_const_init() {
for (k, (_, v)) in &init.vars {
if init.const_vars.contains(k) {
result.entry(k.clone()).or_insert_with(|| v.clone());
}
}
}
result
}
fn module_store(&self) -> Option<&HashMap<String, (TypeTag, Value)>> {
let module = self.current_module()?;
self.modules
.get(&module)?
.init
.as_ref()
.map(|init| &init.vars)
}
fn module_store_mut(&mut self) -> Option<&mut HashMap<String, (TypeTag, Value)>> {
let module = self.current_module()?;
self.modules
.get_mut(&module)?
.init
.as_mut()
.map(|init| &mut init.vars)
}
}
fn mark_value_pipes_escaped(value: &Value) {
if let Some(handle) = value.as_pipe_handle() {
handle.mark_escaped();
return;
}
if let Some(items) = value.as_list() {
for item in items {
mark_value_pipes_escaped(item);
}
}
if let Some(entries) = value.as_map() {
for item in entries.values() {
mark_value_pipes_escaped(item);
}
}
}