use std::collections::HashMap;
use anyhow::Result;
use super::diagnostics as import_diag;
use oxdock_diagnostics::DiagnosticResult;
use oxdock_fs::{GuardedPath, WorkspaceFs};
use oxdock_parser::{
ExportKind, Exports, KEYWORD_BREAK, KEYWORD_CONST, KEYWORD_CONTINUE, KEYWORD_FUNC,
KEYWORD_TYPE, MODULE_SEPARATOR, ModuleTable, Step, StepKind, Value, qualify,
};
use oxdock_process::ProcessManager;
use super::resolve_script_params;
use super::state::{ExecState, RawFuncDef, ScopeAliasFrame};
use super::steps::{Flow, StepCtx, execute_steps};
fn read_import_bytes(fs: &dyn WorkspaceFs, resolved: &GuardedPath) -> Result<Vec<u8>> {
match fs.read_file(resolved) {
Ok(bytes) => Ok(bytes),
Err(first) => {
#[cfg(miri)]
{
let _ = resolved;
Err(anyhow::Error::from(first))
}
#[cfg(not(miri))]
{
if !fs.is_host_backed() {
return Err(anyhow::Error::from(first));
}
let root = resolved.root();
match oxdock_fs::PathResolver::new(root, root) {
Ok(fallback) => match fallback.read_file(resolved) {
Ok(bytes) => Ok(bytes),
Err(_) => Err(anyhow::Error::from(first)),
},
Err(_) => Err(anyhow::Error::from(first)),
}
}
}
}
}
#[derive(Debug, Clone)]
pub struct DryRunStep {
pub file: String,
pub step: Step,
}
pub(super) const MAX_IMPORT_DEPTH: usize = 32;
pub fn dry_run_closure(
steps: &[Step],
entry_label: &str,
base: &GuardedPath,
fs: &dyn WorkspaceFs,
table: &ModuleTable,
) -> DiagnosticResult<Vec<DryRunStep>> {
let mut out = Vec::new();
let mut stack: Vec<String> = Vec::new();
let mut cache: HashMap<String, Vec<Step>> = HashMap::new();
dry_run_walk(
steps,
entry_label,
base,
fs,
table,
&mut stack,
&mut cache,
&mut out,
)?;
Ok(out)
}
#[allow(clippy::too_many_arguments)]
fn dry_run_walk(
steps: &[Step],
file: &str,
dir: &GuardedPath,
fs: &dyn WorkspaceFs,
table: &ModuleTable,
stack: &mut Vec<String>,
cache: &mut HashMap<String, Vec<Step>>,
out: &mut Vec<DryRunStep>,
) -> DiagnosticResult<()> {
for step in steps {
out.push(DryRunStep {
file: file.to_string(),
step: step.clone(),
});
if let StepKind::ImportFile { path, .. } = &step.kind {
let (key, body, nested_dir) = dry_run_load(fs, dir, path, table, stack, cache)?;
stack.push(key.clone());
dry_run_walk(&body, &key, &nested_dir, fs, table, stack, cache, out)?;
stack.pop();
}
if let StepKind::ImportFuncs {
path,
func_names,
type_names,
..
} = &step.kind
{
let load_result = dry_run_load(fs, dir, path, table, stack, cache);
match load_result {
Ok((key, body, nested_dir)) => {
stack.push(key.clone());
dry_run_walk_top_imports(
&body,
&key,
&nested_dir,
fs,
table,
stack,
cache,
out,
)?;
stack.pop();
}
Err(e) => {
let is_host_type_only = func_names.is_empty()
&& !type_names.is_empty()
&& table.modules.contains_key(path);
if !is_host_type_only {
return Err(e);
}
}
}
}
dry_run_walk_kind(&step.kind, file, dir, fs, table, stack, cache, out)?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn dry_run_load(
fs: &dyn WorkspaceFs,
dir: &GuardedPath,
path: &str,
table: &ModuleTable,
stack: &[String],
cache: &mut HashMap<String, Vec<Step>>,
) -> DiagnosticResult<(String, Vec<Step>, GuardedPath)> {
let resolved = dry_run_resolve(fs, dir, path, stack.is_empty())?;
let key = resolved.display();
if stack.iter().any(|p| p == &key) {
let mut chain = stack.to_vec();
chain.push(key);
return Err(import_diag::import_cycle(&chain));
}
if stack.len() >= MAX_IMPORT_DEPTH {
return Err(import_diag::import_depth_limit(MAX_IMPORT_DEPTH, path));
}
let nested_dir = resolved.parent().unwrap_or_else(|| dir.clone());
if let Some(cached) = cache.get(&key) {
return Ok((key, cached.clone(), nested_dir));
}
let parsed = read_and_parse_import(fs, &resolved, path, table)?;
cache.insert(key.clone(), parsed.clone());
Ok((key, parsed, nested_dir))
}
fn workspace_fallback(fs: &dyn WorkspaceFs) -> GuardedPath {
fs.workspace_root()
.cloned()
.unwrap_or_else(|| fs.build_context().clone())
}
fn resolve_top_level_with(
fs: &dyn WorkspaceFs,
dir: &GuardedPath,
top: bool,
entry_parent: Option<&GuardedPath>,
fallback: Option<&GuardedPath>,
path: &str,
) -> DiagnosticResult<GuardedPath> {
if top
&& let Some(eparent) = entry_parent
&& eparent != dir
&& let Ok(candidate) = eparent.join(path)
&& fs.entry_kind(&candidate).is_ok()
{
return Ok(candidate);
}
if let Ok(candidate) = dir.join(path)
&& fs.entry_kind(&candidate).is_ok()
{
return Ok(candidate);
}
if top
&& let Some(root) = fallback
&& root != dir
&& !dir.as_path().starts_with(root.as_path())
&& let Ok(candidate) = root.join(path)
&& fs.entry_kind(&candidate).is_ok()
{
return Ok(candidate);
}
dir.join(path)
.map_err(|e| import_diag::import_cannot_resolve(path, &e))
}
fn dry_run_resolve(
fs: &dyn WorkspaceFs,
dir: &GuardedPath,
path: &str,
is_top: bool,
) -> DiagnosticResult<GuardedPath> {
let fallback = workspace_fallback(fs);
resolve_top_level_with(fs, dir, is_top, None, is_top.then_some(&fallback), path)
}
#[allow(clippy::too_many_arguments)]
fn dry_run_walk_top_imports(
steps: &[Step],
file: &str,
dir: &GuardedPath,
fs: &dyn WorkspaceFs,
table: &ModuleTable,
stack: &mut Vec<String>,
cache: &mut HashMap<String, Vec<Step>>,
out: &mut Vec<DryRunStep>,
) -> DiagnosticResult<()> {
for step in steps {
match &step.kind {
StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => {
out.push(DryRunStep {
file: file.to_string(),
step: step.clone(),
});
}
_ => {}
}
}
for step in steps {
if let StepKind::ImportFile { path, .. } = &step.kind {
let (key, body, nested_dir) = dry_run_load(fs, dir, path, table, stack, cache)?;
stack.push(key.clone());
dry_run_walk(&body, &key, &nested_dir, fs, table, stack, cache, out)?;
stack.pop();
}
if let StepKind::ImportFuncs {
path,
func_names,
type_names,
..
} = &step.kind
{
match dry_run_load(fs, dir, path, table, stack, cache) {
Ok((key, body, nested_dir)) => {
stack.push(key.clone());
dry_run_walk_top_imports(
&body,
&key,
&nested_dir,
fs,
table,
stack,
cache,
out,
)?;
stack.pop();
}
Err(e) => {
let is_host_type_only = func_names.is_empty()
&& !type_names.is_empty()
&& table.modules.contains_key(path);
if !is_host_type_only {
return Err(e);
}
}
}
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn dry_run_walk_kind(
kind: &StepKind,
file: &str,
dir: &GuardedPath,
fs: &dyn WorkspaceFs,
table: &ModuleTable,
stack: &mut Vec<String>,
cache: &mut HashMap<String, Vec<Step>>,
out: &mut Vec<DryRunStep>,
) -> DiagnosticResult<()> {
for body in child_bodies(kind) {
dry_run_walk(body, file, dir, fs, table, stack, cache, out)?;
}
Ok(())
}
fn read_and_parse_import(
fs: &dyn WorkspaceFs,
resolved: &GuardedPath,
path: &str,
table: &ModuleTable,
) -> DiagnosticResult<Vec<Step>> {
let bytes = read_import_bytes(fs, resolved)
.map_err(|e| import_diag::import_cannot_read(path, &super::args::lift_dispatch_error(e)))?;
let text = std::str::from_utf8(&bytes).map_err(|e| import_diag::import_bad_utf8(path, &e))?;
let table = table.clone();
let mut reserved = super::native::builtin_function_names();
reserved.extend(table.reserved_base_names());
oxdock_parser::parse_script_with_modules(text, crate::lower_command, reserved, table)
.map_err(|e| import_diag::import_parse_failed(path, &e))
}
pub(crate) fn gate_harvested_name(
kind: ExportKind,
steps: &[Step],
exports: &Exports,
name: &str,
path: &str,
) -> DiagnosticResult<()> {
let (exported, kind, noun, defined) = match kind {
ExportKind::Func => (
&exports.funcs,
KEYWORD_FUNC,
"function",
steps.iter().any(|step| {
matches!(&step.kind, StepKind::FuncDef { name: def, .. } if def.as_str() == name)
}),
),
ExportKind::Type => (
&exports.types,
KEYWORD_TYPE,
KEYWORD_TYPE,
steps.iter().any(|step| {
matches!(&step.kind, StepKind::TypeAlias { name: alias, .. } if alias.as_str() == name)
}),
),
ExportKind::Const => (&exports.consts, KEYWORD_CONST, KEYWORD_CONST, true),
};
if !exported.iter().any(|e| e == name) {
return Err(import_diag::import_missing_export(path, kind, name));
}
if !defined {
return Err(import_diag::import_unknown_member(path, noun, name));
}
Ok(())
}
pub(crate) fn import_funcs<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path: &str,
alias: Option<&str>,
func_names: &[String],
type_names: &[String],
) -> DiagnosticResult<()> {
if func_names.is_empty() && !type_names.is_empty() {
let base = import_base(cx.state);
let stack = cx.state.import_stack.clone();
let file_exists = top_level_file_exists(cx.state, &base, &stack, path);
if !file_exists && cx.state.module_table.modules.contains_key(path) {
for name in type_names {
cx.state
.resolve_tag(name)
.map_err(|e| import_diag::import_unknown_type(path, name, Some(e)))?;
}
if let Some(alias) = alias {
record_executed_alias(cx.state, alias, None);
}
return Ok(());
}
}
let LoadedFile {
resolved,
steps,
exports,
} = load_import(cx.state, path)?;
let key = resolved.display();
if let Some(alias) = alias {
record_executed_alias(cx.state, alias, Some(key.clone()));
}
cx.state.import_stack.push(resolved.clone());
let saved_aliases = cx.state.type_aliases.clone();
let outcome: DiagnosticResult<()> = (|| {
let aliases = super::typing::collect_type_aliases(&steps, cx.state)?;
for (name, target) in aliases {
cx.state.register_alias(name, target);
}
if !cx.state.validated_modules.contains(&key) {
super::static_check::validate_import_body_types(&steps, cx.state, &key)
.map_err(|e| import_diag::import_failed_validation(path, e))?;
}
if let Some(offender) =
super::static_check::harvest_touches_module(cx.state, &key, &steps, func_names)
.map_err(|e| import_diag::import_failed_validation(path, e))?
{
return Err(import_diag::import_stateful_harvest(path, &offender));
}
for name in func_names {
gate_harvested_name(ExportKind::Func, &steps, &exports, name, path)?;
let Some(def) = 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 {
return Err(import_diag::import_unknown_function(path, name));
};
let resolved_params = resolve_script_params(cx.state, name, &def.0)?;
let return_tag = cx.state.resolve_tag(&def.1)?;
cx.state
.check_return_tag(&format!("function `{name}` returns"), &return_tag)?;
match alias {
Some(_) => {
let canonical = super::native::file_func_key(&key, name);
if cx.state.functions.get(&canonical).is_none() {
cx.state.functions.define_file_func(
name,
&resolved_params,
return_tag.clone(),
&def.1,
def.2,
&def.3,
&key,
)?;
}
}
None => {
if cx.state.functions.get(name).is_none() {
cx.state.functions.define_script(
name,
&resolved_params,
return_tag.clone(),
&def.1,
def.2,
&def.3,
Some(&key),
None,
)?;
}
let unit = active_unit_key(cx.state);
cx.state
.harvest_map
.insert((unit, name.clone()), key.clone());
}
}
}
{
let file_aliases = super::typing::collect_type_aliases(&steps, cx.state)?;
for name in type_names {
gate_harvested_name(ExportKind::Type, &steps, &exports, name, path)?;
let Some(target) = file_aliases.get(name) else {
return Err(import_diag::import_unknown_type(path, name, None));
};
insert_imported_type(cx.state, name, target, alias, path)?;
}
}
cx.state.module_stack.push(Some(key.clone()));
let mut nested_cause: Option<oxdock_diagnostics::Diagnostic> = None;
for step in &steps {
match &step.kind {
StepKind::ImportFile { path, alias } => {
if let Err(e) = import_file(cx, path, alias) {
nested_cause = Some(e);
break;
}
}
StepKind::ImportFuncs {
path,
alias,
func_names,
type_names: nested_types,
} => {
if let Err(e) =
import_funcs(cx, path, alias.as_deref(), func_names, nested_types)
{
nested_cause = Some(e);
break;
}
}
_ => {}
}
}
let _ = cx.state.module_stack.pop();
if let Some(e) = nested_cause {
return Err(e);
}
if module_top_level_sets_jail(&steps) {
ensure_module_init(cx, &key, &resolved, &steps, path)?;
}
Ok(())
})();
let _ = cx.state.import_stack.pop();
{
let mut persisted: Vec<(String, String)> = Vec::new();
for name in type_names {
if let Some(target) = cx.state.type_aliases.get(name).cloned() {
persisted.push((name.clone(), target));
}
}
cx.state.restore_aliases(saved_aliases);
for (name, target) in persisted {
if let Some(existing) = cx.state.type_aliases.get(&name) {
if existing != &target {
return Err(import_diag::import_type_collision(
path, &name, existing, &target,
));
}
} else {
cx.state.register_alias(name, target);
}
}
}
outcome
}
pub(crate) fn insert_imported_type<P: ProcessManager>(
state: &mut ExecState<P>,
name: &str,
target: &str,
alias: Option<&str>,
path: &str,
) -> DiagnosticResult<()> {
let key = match alias {
Some(alias) => qualify(alias, name),
None => name.to_string(),
};
if let Some(existing) = state.type_aliases.get(&key) {
if existing != target {
return Err(import_diag::import_type_collision(
path, name, existing, target,
));
}
} else {
state.register_alias(key, target.to_string());
}
Ok(())
}
fn resolve_own_type_harvests<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
steps: &[Step],
resolved: &GuardedPath,
) -> DiagnosticResult<()> {
let pushed = if cx.state.import_stack.iter().any(|p| p == resolved) {
false
} else {
cx.state.import_stack.push(resolved.clone());
true
};
let outcome = resolve_own_type_harvests_inner(cx, steps);
if pushed {
let _ = cx.state.import_stack.pop();
}
outcome
}
fn resolve_own_type_harvests_inner<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
steps: &[Step],
) -> DiagnosticResult<()> {
for step in steps {
let StepKind::ImportFuncs {
path: harvest_path,
alias: harvest_alias,
func_names: harvest_funcs,
type_names: harvest_types,
} = &step.kind
else {
continue;
};
if harvest_types.is_empty() {
continue;
}
if harvest_funcs.is_empty() {
let base = import_base(cx.state);
let resolved_opt = base.join(harvest_path).ok();
let file_exists = resolved_opt
.as_ref()
.is_some_and(|r| cx.state.fs.entry_kind(r).is_ok());
if !file_exists && cx.state.module_table.modules.contains_key(harvest_path) {
for name in harvest_types {
cx.state.resolve_tag(name).map_err(|e| {
import_diag::import_unknown_type(harvest_path, name, Some(e))
})?;
}
continue;
}
}
let harvested = load_import(cx.state, harvest_path)?;
let file_aliases = super::typing::collect_type_aliases(&harvested.steps, cx.state)?;
for name in harvest_types {
gate_harvested_name(
ExportKind::Type,
&harvested.steps,
&harvested.exports,
name,
harvest_path,
)?;
let Some(target) = file_aliases.get(name) else {
return Err(import_diag::import_unknown_type(harvest_path, name, None));
};
insert_imported_type(
cx.state,
name,
target,
harvest_alias.as_deref(),
harvest_path,
)?;
}
}
Ok(())
}
fn module_top_level_sets_jail(steps: &[Step]) -> bool {
steps.iter().any(|step| step_sets_jail(&step.kind))
}
fn step_sets_jail(kind: &StepKind) -> bool {
matches!(kind, StepKind::Workspace(_) | StepKind::Workdir(_))
}
fn ensure_module_init<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
key: &str,
resolved: &GuardedPath,
steps: &[Step],
path: &str,
) -> DiagnosticResult<Value> {
if let Some(init) = cx
.state
.modules
.get(key)
.and_then(|record| record.init.as_ref())
{
return Ok(init.return_value.clone());
}
let saved_vars = std::mem::take(&mut cx.state.var_scopes);
let saved_consts = std::mem::take(&mut cx.state.const_scopes);
let saved_aliases = cx.state.type_aliases.clone();
let saved_isolated = std::mem::take(&mut cx.state.isolated_stack);
let outcome: DiagnosticResult<Value> = (|| {
let aliases = super::typing::collect_type_aliases(steps, cx.state)?;
for (name, target) in aliases {
cx.state.register_alias(name, target);
}
cx.state.import_stack.push(resolved.clone());
cx.state
.init_scope_depths
.push(cx.state.scope_stack.len() + 1);
cx.state.push_scope();
cx.state
.func_floors
.push(cx.state.functions.scope_depth().saturating_sub(1));
let saved_call_depth = cx.state.call_depth;
cx.state.call_depth = 0;
cx.state.init_inherit_stack.push(Vec::new());
cx.state.fs.switch_to_snapshot();
cx.state.cwd = cx.state.fs.root().clone();
cx.state.envs = std::sync::Arc::new((*cx.state.seed).clone());
cx.state.isolated_stack = Vec::new();
let env_before: std::collections::HashMap<String, String> = (*cx.state.seed).clone();
cx.state.module_stack.push(Some(key.to_string()));
let flow = execute_steps(
cx.state,
cx.process,
steps,
cx.stdin.clone(),
false,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
false,
);
let _ = cx.state.module_stack.pop();
let inherit_names = cx.state.init_inherit_stack.pop().unwrap_or_default();
cx.state.call_depth = saved_call_depth;
let flow = flow?;
let drained = std::mem::take(
cx.state
.var_scopes
.last_mut()
.expect("import pushed exactly one var scope"),
);
let drained_consts = std::mem::take(
cx.state
.const_scopes
.last_mut()
.expect("import pushed exactly one const scope"),
);
let init_selection = cx.state.fs.selection();
let init_cwd = cx.state.cwd.clone();
let value = match flow {
Flow::Done => Value::string(String::new()),
Flow::Return { value, .. } => value,
Flow::Break { idx } => {
return Err(import_diag::import_flow_crosses_boundary(
KEYWORD_BREAK,
idx + 1,
path,
));
}
Flow::Continue { idx } => {
return Err(import_diag::import_flow_crosses_boundary(
KEYWORD_CONTINUE,
idx + 1,
path,
));
}
};
let record = cx.state.modules.entry(key.to_string()).or_default();
let after = cx.state.envs.clone();
let mut module_env = (*cx.state.seed).clone();
for (name, value) in after.iter() {
if env_before.get(name) != Some(value) {
module_env.insert(name.clone(), value.clone());
}
}
for name in env_before.keys() {
if !after.contains_key(name) {
module_env.remove(name);
}
}
record.init = Some(super::state::ModuleInit {
vars: drained,
const_vars: drained_consts,
return_value: value.clone(),
envs: module_env,
inherit_names,
selection: init_selection,
cwd: init_cwd,
});
Ok(value)
})();
let pop_res = cx.state.pop_scope();
let _ = cx.state.func_floors.pop();
let init_depth = cx.state.scope_stack.len() + 1;
cx.state
.init_scope_depths
.retain(|depth| *depth != init_depth);
cx.state.var_scopes = saved_vars;
cx.state.const_scopes = saved_consts;
cx.state.isolated_stack = saved_isolated;
let _ = cx.state.import_stack.pop();
cx.state.restore_aliases(saved_aliases);
match (outcome, pop_res) {
(Ok(value), Ok(())) => Ok(value),
(Err(e), _) => Err(e),
(Ok(_), Err(e)) => Err(e),
}
}
pub(crate) fn import_file<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path: &str,
alias: &str,
) -> DiagnosticResult<Value> {
let LoadedFile {
resolved,
steps,
exports,
} = load_import(cx.state, path)?;
let key = resolved.display();
record_executed_alias(cx.state, alias, Some(key.clone()));
let saved_aliases = cx.state.type_aliases.clone();
let phase_one: DiagnosticResult<Option<Value>> = (|| {
let aliases = super::typing::collect_type_aliases(&steps, cx.state)?;
for (name, target) in &aliases {
cx.state.register_alias(name.clone(), target.clone());
}
resolve_own_type_harvests(cx, &steps, &resolved)?;
if !cx.state.validated_modules.contains(&key) {
super::static_check::validate_import_body_types(&steps, cx.state, &key)
.map_err(|e| import_diag::import_failed_validation(path, e))?;
}
let func_exported: std::collections::HashSet<&str> =
exports.funcs.iter().map(|e| e.as_str()).collect();
for step in &steps {
if let StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} = &step.kind
&& func_exported.contains(name.as_str())
{
let canonical = super::native::file_func_key(&key, name);
if cx.state.functions.get(&canonical).is_none() {
let resolved_params = resolve_script_params(cx.state, name, params)?;
let return_tag = cx.state.resolve_tag(return_type)?;
cx.state
.check_return_tag(&format!("function `{name}` returns"), &return_tag)?;
cx.state.functions.define_file_func(
name,
&resolved_params,
return_tag,
return_type,
*is_async,
body,
&key,
)?;
}
}
}
{
let type_exported: std::collections::HashSet<&str> =
exports.types.iter().map(|e| e.as_str()).collect();
for (name, target) in &aliases {
if !type_exported.contains(name.as_str()) {
continue;
}
insert_imported_type(cx.state, name, target, Some(alias), path)?;
}
}
if let Some(init) = cx
.state
.modules
.get(&key)
.and_then(|record| record.init.as_ref())
{
return Ok(Some(init.return_value.clone()));
}
Ok(None)
})();
cx.state.restore_aliases(saved_aliases.clone());
let cached = phase_one?;
{
if let Ok(aliases) = super::typing::collect_type_aliases(&steps, cx.state) {
for (name, target) in &aliases {
cx.state.register_alias(name.clone(), target.clone());
}
let type_exported: std::collections::HashSet<&str> =
exports.types.iter().map(|e| e.as_str()).collect();
let mut to_persist: Vec<(String, String)> = Vec::new();
for (name, target) in &aliases {
if type_exported.contains(name.as_str()) {
to_persist.push((name.clone(), target.clone()));
}
}
cx.state.restore_aliases(saved_aliases.clone());
for (name, target) in to_persist {
insert_imported_type(cx.state, &name, &target, Some(alias), path)?;
}
} else {
cx.state.restore_aliases(saved_aliases.clone());
}
}
if let Some(value) = cached {
return Ok(value);
}
let outcome = ensure_module_init(cx, &key, &resolved, &steps, path);
if outcome.is_ok() {
resolve_own_type_harvests(cx, &steps, &resolved)?;
}
outcome
}
#[derive(Debug, Clone)]
pub(super) struct ClosureSite {
pub alias: Option<String>,
pub func_names: Option<Vec<String>>,
pub type_names: Option<Vec<String>>,
}
#[derive(Debug, Clone)]
pub(super) struct ClosureFile {
pub key: String,
pub path: String,
pub dir: GuardedPath,
pub steps: Vec<Step>,
pub exports: Exports,
pub sites: Vec<ClosureSite>,
}
pub(crate) fn expand_import_closure<P: ProcessManager>(
state: &mut ExecState<P>,
steps: &[Step],
) -> DiagnosticResult<Vec<ClosureFile>> {
let base = import_base(state);
let mut stack: Vec<GuardedPath> = Vec::new();
let mut files: Vec<ClosureFile> = Vec::new();
expand_walk(state, steps, &base, &mut stack, &mut files)?;
Ok(files)
}
fn expand_walk<P: ProcessManager>(
state: &mut ExecState<P>,
steps: &[Step],
dir: &GuardedPath,
stack: &mut Vec<GuardedPath>,
files: &mut Vec<ClosureFile>,
) -> DiagnosticResult<()> {
for step in steps {
match &step.kind {
StepKind::ImportFile { path, alias } => {
let target = expand_load(state, dir, stack, path)?;
record_site(
files,
&target,
path.clone(),
ClosureSite {
alias: Some(alias.clone()),
func_names: None,
type_names: None,
},
);
stack.push(target.resolved);
expand_walk(state, &target.body, &target.nested, stack, files)?;
stack.pop();
}
StepKind::ImportFuncs {
path,
alias,
func_names,
type_names,
} => {
if func_names.is_empty() && !type_names.is_empty() {
let file_exists = top_level_file_exists(state, dir, stack, path);
if !file_exists && state.module_table.modules.contains_key(path) {
for name in type_names {
state.resolve_tag(name).map_err(|e| {
import_diag::import_unknown_type(path, name, Some(e))
})?;
}
expand_walk_kind(state, &step.kind, dir, stack, files)?;
continue;
}
}
let target = expand_load(state, dir, stack, path)?;
record_site(
files,
&target,
path.clone(),
ClosureSite {
alias: alias.clone(),
func_names: Some(func_names.clone()),
type_names: Some(type_names.clone()),
},
);
stack.push(target.resolved);
expand_walk_top(state, &target.body, &target.nested, stack, files)?;
stack.pop();
}
_ => {}
}
expand_walk_kind(state, &step.kind, dir, stack, files)?;
}
Ok(())
}
fn expand_walk_top<P: ProcessManager>(
state: &mut ExecState<P>,
steps: &[Step],
dir: &GuardedPath,
stack: &mut Vec<GuardedPath>,
files: &mut Vec<ClosureFile>,
) -> DiagnosticResult<()> {
for step in steps {
match &step.kind {
StepKind::ImportFile { path, alias } => {
let target = expand_load(state, dir, stack, path)?;
record_site(
files,
&target,
path.clone(),
ClosureSite {
alias: Some(alias.clone()),
func_names: None,
type_names: None,
},
);
stack.push(target.resolved);
expand_walk(state, &target.body, &target.nested, stack, files)?;
stack.pop();
}
StepKind::ImportFuncs {
path,
alias,
func_names,
type_names,
} => {
if func_names.is_empty() && !type_names.is_empty() {
let file_exists = top_level_file_exists(state, dir, stack, path);
if !file_exists && state.module_table.modules.contains_key(path) {
for name in type_names {
state.resolve_tag(name).map_err(|e| {
import_diag::import_unknown_type(path, name, Some(e))
})?;
}
continue;
}
}
let target = expand_load(state, dir, stack, path)?;
record_site(
files,
&target,
path.clone(),
ClosureSite {
alias: alias.clone(),
func_names: Some(func_names.clone()),
type_names: Some(type_names.clone()),
},
);
stack.push(target.resolved);
expand_walk_top(state, &target.body, &target.nested, stack, files)?;
stack.pop();
}
_ => {}
}
}
Ok(())
}
fn expand_walk_kind<P: ProcessManager>(
state: &mut ExecState<P>,
kind: &StepKind,
dir: &GuardedPath,
stack: &mut Vec<GuardedPath>,
files: &mut Vec<ClosureFile>,
) -> DiagnosticResult<()> {
for body in child_bodies(kind) {
expand_walk(state, body, dir, stack, files)?;
}
Ok(())
}
pub(crate) fn child_bodies(kind: &StepKind) -> Vec<&[Step]> {
use oxdock_parser::BindRhs;
let mut out: Vec<&[Step]> = match kind {
StepKind::WithIo { cmd, .. } => child_bodies(cmd),
StepKind::Bind { rhs, .. } => match rhs {
BindRhs::Capture(cmd) => child_bodies(cmd),
BindRhs::Async(body) => vec![body],
BindRhs::Expr(_) | BindRhs::Await { .. } => Vec::new(),
},
StepKind::For { body, .. }
| StepKind::While { body, .. }
| StepKind::FuncDef { body, .. }
| StepKind::Timeout { body, .. }
| StepKind::Fail { body, .. }
| StepKind::Isolated { body, .. }
| StepKind::AsyncBlock { body, .. }
| StepKind::RemoteBlock { body, .. } => vec![body],
StepKind::If {
then_body,
else_ifs,
else_body,
..
} => {
let mut out = vec![then_body.as_slice()];
for (_, arm) in else_ifs {
out.push(arm);
}
if let Some(arm) = else_body {
out.push(arm);
}
out
}
StepKind::Switch {
cases,
default_body,
..
} => {
let mut out: Vec<&[Step]> = Vec::new();
for (_, arm) in cases {
out.push(arm);
}
if let Some(arm) = default_body {
out.push(arm);
}
out
}
_ => Vec::new(),
};
match kind {
StepKind::Bind {
rhs: oxdock_parser::BindRhs::Expr(expr),
..
}
| StepKind::Set { expr, .. } => {
if let oxdock_parser::Expr::Block(body) = expr {
out.push(body);
}
}
StepKind::Return { expr, .. } => {
if let oxdock_parser::Expr::Block(body) = expr.as_ref() {
out.push(body);
}
}
StepKind::Call { args, .. } => {
for arg in args {
if let oxdock_parser::Expr::Block(body) = arg {
out.push(body);
}
}
}
_ => {}
}
out
}
fn record_site(
files: &mut Vec<ClosureFile>,
target: &ExpandedImport,
path: String,
site: ClosureSite,
) {
let key = target.resolved.display();
match files.iter_mut().find(|f| f.key == key) {
Some(found) => {
if !found.sites.iter().any(|s| {
s.alias == site.alias
&& s.func_names == site.func_names
&& s.type_names == site.type_names
}) {
found.sites.push(site);
}
}
None => files.push(ClosureFile {
key,
path,
dir: target.nested.clone(),
steps: target.body.clone(),
exports: target.exports.clone(),
sites: vec![site],
}),
}
}
struct ExpandedImport {
resolved: GuardedPath,
body: Vec<Step>,
exports: Exports,
nested: GuardedPath,
}
fn expand_load<P: ProcessManager>(
state: &mut ExecState<P>,
dir: &GuardedPath,
stack: &[GuardedPath],
path: &str,
) -> DiagnosticResult<ExpandedImport> {
let resolved = resolve_top_level(state, dir, stack, path)?;
let key = resolved.display();
if stack.iter().any(|p| p == &resolved) {
let mut chain: Vec<String> = stack.iter().map(|p| p.display()).collect();
chain.push(key);
return Err(import_diag::import_cycle(&chain));
}
if stack.len() >= MAX_IMPORT_DEPTH {
return Err(import_diag::import_depth_limit(MAX_IMPORT_DEPTH, path));
}
if state.fs.entry_kind(&resolved).is_err() {
return Err(import_diag::import_not_found(path));
}
let LoadedFile {
resolved,
steps: body,
exports,
} = load_file(state, dir, stack, path)?;
let nested = resolved.parent().unwrap_or_else(|| dir.clone());
Ok(ExpandedImport {
resolved,
body,
exports,
nested,
})
}
fn load_import<P: ProcessManager>(
state: &mut ExecState<P>,
path: &str,
) -> DiagnosticResult<LoadedFile> {
let base = import_base(state);
let stack = state.import_stack.clone();
load_file(state, &base, &stack, path)
}
struct LoadedFile {
resolved: GuardedPath,
steps: Vec<Step>,
exports: Exports,
}
fn load_file<P: ProcessManager>(
state: &mut ExecState<P>,
base: &GuardedPath,
stack: &[GuardedPath],
path: &str,
) -> DiagnosticResult<LoadedFile> {
let resolved = resolve_top_level(state, base, stack, path)?;
let key = resolved.display();
if stack.iter().any(|p| p == &resolved) {
let mut chain: Vec<String> = stack.iter().map(|p| p.display()).collect();
chain.push(key.clone());
return Err(import_diag::import_cycle(&chain));
}
if stack.len() >= MAX_IMPORT_DEPTH {
return Err(import_diag::import_depth_limit(MAX_IMPORT_DEPTH, path));
}
if let Some(record) = state.modules.get(&key) {
return Ok(LoadedFile {
resolved,
steps: record.steps.clone(),
exports: record.exports.clone(),
});
}
let bytes = read_import_bytes(state.fs.as_ref(), &resolved)
.map_err(|e| import_diag::import_cannot_read(path, &super::args::lift_dispatch_error(e)))?;
let text = std::str::from_utf8(&bytes).map_err(|e| import_diag::import_bad_utf8(path, &e))?;
let table = state.module_table.clone();
let mut reserved = super::native::builtin_function_names();
reserved.extend(table.reserved_base_names());
let parsed = oxdock_parser::parse_script_with_modules_and_exports(
text,
crate::lower_command,
reserved,
table,
)
.map_err(|e| import_diag::import_parse_failed(path, &e))?;
state.modules.insert(
key,
super::state::ModuleRecord {
steps: parsed.steps.clone(),
exports: parsed.exports.clone(),
init: None,
top_funcs: collect_top_funcs(&parsed.steps),
},
);
Ok(LoadedFile {
resolved,
steps: parsed.steps,
exports: parsed.exports,
})
}
pub(crate) fn import_base<P: ProcessManager>(state: &ExecState<P>) -> GuardedPath {
if let Some(top) = state.import_stack.last() {
if let Some(parent) = top.parent() {
return parent;
}
} else if let Some(parent) = state.entry_file.as_ref().and_then(|entry| entry.parent()) {
let base = workspace_fallback(state.fs.as_ref());
if !parent.as_path().starts_with(base.as_path()) {
return base;
}
return parent;
}
workspace_fallback(state.fs.as_ref())
}
pub(crate) fn resolve_top_level<P: ProcessManager>(
state: &ExecState<P>,
dir: &GuardedPath,
stack: &[GuardedPath],
path: &str,
) -> DiagnosticResult<GuardedPath> {
resolve_top_level_with(
state.fs.as_ref(),
dir,
stack.is_empty(),
state
.entry_file
.as_ref()
.and_then(|entry| entry.parent())
.as_ref(),
None,
path,
)
}
pub(crate) const ENTRY_UNIT: &str = "entry";
pub(super) fn collect_top_funcs(steps: &[Step]) -> HashMap<String, Vec<RawFuncDef>> {
let mut out: HashMap<String, Vec<RawFuncDef>> = HashMap::new();
for step in steps {
if let StepKind::FuncDef {
name,
params,
return_type,
is_async,
body,
..
} = &step.kind
{
out.entry(name.clone()).or_default().push(RawFuncDef {
params: params.clone(),
return_spelling: return_type.clone(),
is_async: *is_async,
body: body.clone(),
guard: step.guard.clone(),
jail: None,
});
}
}
out
}
pub(super) fn live_top_func(
defs: &[RawFuncDef],
envs: &impl oxdock_parser::EnvLookup,
) -> Option<RawFuncDef> {
let mut found = None;
for def in defs {
if oxdock_parser::guard_option_allows(def.guard.as_ref(), envs) {
found = Some(def.clone());
}
}
found
}
pub(super) enum ScriptSite<P: ProcessManager> {
Live(super::native::FuncEntry<P>),
File {
raw: RawFuncDef,
unit: Option<String>,
},
}
struct RuntimeFrame<'a, P: ProcessManager> {
state: &'a ExecState<P>,
current: Option<String>,
}
impl<P: ProcessManager> super::native::FuncFrameView for RuntimeFrame<'_, P> {
type Hit = ScriptSite<P>;
fn find_nested(&self, base: &str) -> Option<Self::Hit> {
let floor = self.state.func_floors.last().copied().unwrap_or(0);
self.state
.functions
.get_scoped(base, floor)
.map(ScriptSite::Live)
}
fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit> {
let tops = self.state.unit_top_funcs(unit)?;
let defs = tops.get(base)?;
let raw = live_top_func(defs, &self.state.envs)?;
let unit = self.current.clone();
Some(ScriptSite::File { raw, unit })
}
fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit> {
let defining = self
.state
.harvest_map
.get(&(unit.to_string(), base.to_string()))?;
let raw = self
.state
.modules
.get(defining)
.and_then(|r| r.top_funcs.get(base))
.and_then(|defs| defs.first().cloned())?;
Some(ScriptSite::File {
raw,
unit: Some(defining.clone()),
})
}
}
pub(super) fn find_script_site<P: ProcessManager>(
state: &ExecState<P>,
name: &str,
) -> DiagnosticResult<Option<ScriptSite<P>>> {
use super::native::FuncFrameView;
let base = match name.split_once(MODULE_SEPARATOR) {
Some((module, base)) if module == oxdock_parser::SCRIPT_MODULE_NAME => base,
Some(_) => return Ok(None),
None => name,
};
let current = state.current_module();
let view = RuntimeFrame {
state,
current: current.clone(),
};
Ok(view.walk(unit_key(current.as_deref()), base))
}
pub(crate) fn missing_import_hint<P: ProcessManager>(state: &ExecState<P>, name: &str) -> String {
super::native::missing_import_hint(
state
.modules
.iter()
.map(|(file, record)| (file.as_str(), record.exports.funcs.as_slice())),
&active_unit_alias_targets(state),
name,
)
.unwrap_or_default()
}
pub(crate) fn unit_key(owner: Option<&str>) -> &str {
owner.unwrap_or(ENTRY_UNIT)
}
pub(crate) fn active_unit_key<P: ProcessManager>(state: &ExecState<P>) -> String {
unit_key(state.current_module().as_deref()).to_string()
}
pub(crate) fn unit_alias_targets<P: ProcessManager>(
state: &ExecState<P>,
unit: &str,
) -> super::native::AliasTargets {
let mut out = state
.executed_alias_targets
.get(unit)
.cloned()
.unwrap_or_default();
let live_floor = {
let mut floor = 0;
let mut inherited: Option<&super::native::AliasTargets> = None;
for frame in state.call_alias_frames.iter().rev() {
if frame.unit == unit {
if frame.depth <= state.scope_stack.len() {
for (alias, targets) in &frame.targets {
out.entry(alias.clone())
.or_default()
.extend(targets.iter().cloned());
}
floor = frame.depth;
inherited = None;
break;
}
inherited.get_or_insert(&frame.targets);
}
}
if let Some(targets) = inherited {
for (alias, alias_targets) in targets {
out.entry(alias.clone())
.or_default()
.extend(alias_targets.iter().cloned());
}
}
floor
};
for frame in state
.scope_alias_frames
.iter()
.filter(|frame| frame.unit == unit && frame.depth > live_floor)
{
for (alias, targets) in &frame.targets {
out.entry(alias.clone())
.or_default()
.extend(targets.iter().cloned());
}
}
out
}
pub(crate) fn active_unit_alias_targets<P: ProcessManager>(
state: &ExecState<P>,
) -> super::native::AliasTargets {
unit_alias_targets(state, &active_unit_key(state))
}
impl<P: ProcessManager> super::native::ModuleGraphView for ExecState<P> {
fn const_exports(&self, file: &str) -> Option<&[String]> {
self.modules
.get(file)
.map(|record| record.exports.consts.as_slice())
}
fn alias_targets(&self, file: &str) -> super::native::AliasTargets {
unit_alias_targets(self, file)
}
fn binding(&self, file: &str, name: &str) -> super::native::BindingPresence {
use super::native::BindingPresence;
match self
.modules
.get(file)
.and_then(|record| record.init.as_ref())
{
Some(init) => match init.vars.get(name) {
Some(_) if init.const_vars.contains(name) => BindingPresence::Const,
Some(_) => BindingPresence::Let,
None => BindingPresence::Absent,
},
None => BindingPresence::Absent,
}
}
}
pub(crate) fn resolve_const_ref<P: ProcessManager>(
state: &ExecState<P>,
alias: &str,
name: &str,
) -> DiagnosticResult<Value> {
use super::native::{
ConstHolders, chase_const_forward, const_holder_files, missing_const_hint,
};
let qualified = oxdock_parser::qualify(alias, name);
let targets = active_unit_alias_targets(state);
let holders = match const_holder_files(state, &targets, alias, name) {
ConstHolders::Found(holders) => holders,
ConstHolders::NoAlias => {
return Err(import_diag::import_const_no_alias(&qualified, alias));
}
ConstHolders::Ambiguous { alias, base, files } => {
return Err(import_diag::import_const_ambiguous(&alias, &base, &files));
}
};
if holders.len() > 1 {
let files: std::collections::HashSet<String> = holders.into_iter().collect();
return Err(import_diag::import_const_ambiguous(alias, name, &files));
}
let Some(file) = holders.into_iter().next() else {
let hint = missing_const_hint(state, &targets, alias, name);
match hint {
Some(hint) => {
return Err(import_diag::import_const_hinted(&qualified, &hint));
}
None => {
return Err(import_diag::import_const_no_alias(&qualified, alias));
}
}
};
let mut terminals = chase_const_forward(state, &file, name, &qualified)?;
if terminals.len() > 1 {
let files: std::collections::HashSet<String> = terminals.drain(..).collect();
return Err(import_diag::import_const_ambiguous(alias, name, &files));
}
let Some(terminal) = terminals.into_iter().next() else {
return Err(import_diag::import_const_unknown(&qualified));
};
let Some(record) = state.modules.get(&terminal) else {
return Err(import_diag::import_const_unknown(&qualified));
};
let Some(init) = record.init.as_ref() else {
return Err(import_diag::import_const_uninitialized(&qualified));
};
if !init.const_vars.contains(name) {
return Err(import_diag::import_const_is_let(&qualified));
}
init.vars
.get(name)
.map(|(_, value)| value.clone())
.ok_or_else(|| import_diag::import_const_unknown(&qualified))
}
pub(crate) fn record_executed_alias<P: ProcessManager>(
state: &mut ExecState<P>,
alias: &str,
defining: Option<String>,
) {
let unit = active_unit_key(state);
let depth = state.scope_stack.len();
if let Some(frame) = state
.call_alias_frames
.iter_mut()
.rev()
.find(|frame| frame.unit == unit)
&& frame.depth == depth
{
frame
.targets
.entry(alias.to_string())
.or_default()
.push((defining, None));
return;
}
if !state.scope_stack.is_empty() && !state.init_scope_depths.contains(&depth) {
if let Some(frame) = state
.scope_alias_frames
.iter_mut()
.rev()
.find(|frame| frame.depth == depth && frame.unit == unit)
{
frame
.targets
.entry(alias.to_string())
.or_default()
.push((defining, None));
return;
}
let mut targets = super::native::AliasTargets::new();
targets
.entry(alias.to_string())
.or_default()
.push((defining, None));
state.scope_alias_frames.push(ScopeAliasFrame {
depth,
unit,
targets,
});
return;
}
let targets = state
.executed_alias_targets
.entry(unit)
.or_default()
.entry(alias.to_string())
.or_default();
targets.push((defining, None));
}
pub(crate) fn resolve_static_top_level(
entry_parent: Option<&GuardedPath>,
dir: &GuardedPath,
files: &[ClosureFile],
path: &str,
is_entry: bool,
) -> Option<String> {
if is_entry
&& let Some(eparent) = entry_parent
&& eparent != dir
&& let Ok(candidate) = eparent.join(path)
{
let key = candidate.display();
if files.iter().any(|f| f.key == key) {
return Some(key);
}
}
dir.join(path).ok().and_then(|resolved| {
let key = resolved.display();
files.iter().any(|f| f.key == key).then_some(key)
})
}
pub(crate) fn top_level_file_exists<P: ProcessManager>(
state: &ExecState<P>,
dir: &GuardedPath,
stack: &[GuardedPath],
path: &str,
) -> bool {
resolve_top_level(state, dir, stack, path)
.is_ok_and(|resolved| state.fs.entry_kind(&resolved).is_ok())
}