use std::collections::HashMap;
use anyhow::{Result, bail};
use oxdock_fs::{GuardedPath, WorkspaceFs};
use oxdock_parser::{ModuleTable, Step, StepKind, Value};
use oxdock_process::ProcessManager;
use super::state::ExecState;
use super::steps::{Flow, StepCtx, execute_steps};
#[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,
) -> Result<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>,
) -> Result<()> {
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>>,
) -> Result<(String, Vec<Step>, GuardedPath)> {
let resolved = dir
.join(path)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` cannot be resolved: {e}"))?;
let key = resolved.display();
if stack.iter().any(|p| p == &key) {
let mut chain = stack.to_vec();
chain.push(key);
bail!("IMPORT cycle detected: {}", chain.join(" -> "));
}
if stack.len() >= MAX_IMPORT_DEPTH {
bail!(
"IMPORT depth limit exceeded ({}): `{}`",
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))
}
#[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>,
) -> Result<()> {
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>,
) -> Result<()> {
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,
) -> Result<Vec<Step>> {
let bytes = fs
.read_file(resolved)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` cannot be read: {e}"))?;
let text = std::str::from_utf8(&bytes)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` is not valid UTF-8: {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| anyhow::anyhow!("IMPORT `{path}` failed to parse: {e}"))
}
pub(crate) fn import_funcs<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path: &str,
alias: Option<&str>,
func_names: &[String],
type_names: &[String],
) -> Result<()> {
if func_names.is_empty() && !type_names.is_empty() {
let base = import_base(cx.state);
let resolved_opt = base.join(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(path) {
for name in type_names {
cx.state.resolve_tag(name).map_err(|e| {
anyhow::anyhow!("IMPORT `{path}` has no such TYPE `{name}`: {e:#}")
})?;
}
if let Some(alias) = alias {
let _ = enter_alias_frame(cx.state);
let _ = alias;
}
return Ok(());
}
}
let LoadedFile {
resolved,
steps,
func_exports,
type_exports,
} = load_import(cx.state, path)?;
let key = resolved.display();
let alias_frame = enter_alias_frame(cx.state);
cx.state.import_stack.push(resolved);
let saved_aliases = cx.state.type_aliases.clone();
let outcome: Result<()> = (|| {
let aliases = super::typing::collect_type_aliases(&steps, cx.state)?;
for (name, target) in aliases {
cx.state.type_aliases.insert(name, target);
}
super::static_check::validate_import_body_types(&steps, cx.state, &key)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` failed validation: {e}"))?;
if let Some(offender) =
super::static_check::harvest_touches_module(cx.state, &key, &steps, func_names)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` failed validation: {e}"))?
{
bail!("IMPORT `{path}` cannot harvest stateful function `{offender}`: import the file");
}
for name in func_names {
if !func_exports.iter().any(|e| e == name) {
bail!("IMPORT `{path}` does not export `{name}`");
}
let Some(def) = steps.iter().find_map(|step| match &step.kind {
StepKind::FuncDef {
name: def_name,
params,
body,
..
} if def_name == name => Some((params.clone(), body.clone())),
_ => None,
}) else {
bail!("IMPORT `{path}` has no such function `{name}`");
};
let mut resolved_params = Vec::with_capacity(def.0.len());
for (pname, ptype) in &def.0 {
resolved_params.push((pname.clone(), cx.state.resolve_tag(ptype)?));
}
match alias {
Some(alias) => {
let qualified = oxdock_parser::qualify(alias, name);
if cx.state.functions.get(&qualified).is_none() {
cx.state.functions.define_aliased_in(
alias_frame,
alias,
name,
&resolved_params,
&def.1,
Some(&key),
)?;
}
}
None => {
if cx.state.functions.get(name).is_none() {
cx.state.functions.define_script(
name,
&resolved_params,
&def.1,
Some(&key),
)?;
}
}
}
}
{
let file_aliases = super::typing::collect_type_aliases(&steps, cx.state)?;
for name in type_names {
if !type_exports.iter().any(|e| e == name) {
bail!("IMPORT `{path}` does not export TYPE `{name}`");
}
let Some(target) = file_aliases.get(name) else {
bail!("IMPORT `{path}` has no such TYPE `{name}`");
};
insert_imported_type(cx.state, name, target, alias, path)?;
}
}
for step in &steps {
match &step.kind {
StepKind::ImportFile { path, alias } => {
import_file(cx, path, alias)?;
}
StepKind::ImportFuncs {
path,
alias,
func_names,
type_names: nested_types,
} => {
import_funcs(cx, path, alias.as_deref(), func_names, nested_types)?;
}
_ => {}
}
}
Ok(())
})();
let _ = cx.state.import_stack.pop();
if cx.state.import_stack.is_empty() {
cx.state.import_alias_frame = None;
}
{
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.type_aliases = saved_aliases;
for (name, target) in persisted {
if let Some(existing) = cx.state.type_aliases.get(&name) {
if existing != &target {
anyhow::bail!(
"IMPORT `{path}` TYPE `{name}` collides: already defined with a different target"
);
}
} else {
cx.state.type_aliases.insert(name, target);
}
}
}
outcome
}
pub(crate) fn insert_imported_type<P: ProcessManager>(
state: &mut ExecState<P>,
name: &str,
target: &str,
alias: Option<&str>,
path: &str,
) -> Result<()> {
let key = match alias {
Some(alias) => format!("{alias}::{name}"),
None => name.to_string(),
};
if let Some(existing) = state.type_aliases.get(&key) {
if existing != target {
anyhow::bail!(
"IMPORT `{path}` TYPE `{name}` collides: already defined with target `{existing}`, new target `{target}`"
);
}
} else {
state.type_aliases.insert(key, target.to_string());
}
Ok(())
}
fn enter_alias_frame<P: ProcessManager>(state: &mut ExecState<P>) -> usize {
if state.import_stack.is_empty() {
let depth = state.functions.scope_depth().saturating_sub(1);
state.import_alias_frame = Some(depth);
}
state
.import_alias_frame
.unwrap_or_else(|| state.functions.scope_depth().saturating_sub(1))
}
fn resolve_own_type_harvests<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
steps: &[Step],
resolved: &GuardedPath,
) -> Result<()> {
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],
) -> Result<()> {
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| {
anyhow::anyhow!("IMPORT `{harvest_path}` has no such TYPE `{name}`: {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 {
if !harvested.type_exports.iter().any(|e| e == name) {
anyhow::bail!("IMPORT `{harvest_path}` does not export TYPE `{name}`");
}
let Some(target) = file_aliases.get(name) else {
anyhow::bail!("IMPORT `{harvest_path}` has no such TYPE `{name}`");
};
insert_imported_type(
cx.state,
name,
target,
harvest_alias.as_deref(),
harvest_path,
)?;
}
}
Ok(())
}
pub(crate) fn import_file<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
path: &str,
alias: &str,
) -> Result<Value> {
let LoadedFile {
resolved,
steps,
func_exports,
type_exports,
} = load_import(cx.state, path)?;
let key = resolved.display();
let alias_frame = enter_alias_frame(cx.state);
let saved_aliases = cx.state.type_aliases.clone();
let phase_one: Result<Option<Value>> = (|| {
let aliases = super::typing::collect_type_aliases(&steps, cx.state)?;
for (name, target) in &aliases {
cx.state.type_aliases.insert(name.clone(), target.clone());
}
resolve_own_type_harvests(cx, &steps, &resolved)?;
super::static_check::validate_import_body_types(&steps, cx.state, &key)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` failed validation: {e}"))?;
let func_exported: std::collections::HashSet<&str> =
func_exports.iter().map(|e| e.as_str()).collect();
for step in &steps {
if let StepKind::FuncDef {
name, params, body, ..
} = &step.kind
&& func_exported.contains(name.as_str())
{
let qualified = oxdock_parser::qualify(alias, name);
if cx.state.functions.get(&qualified).is_none() {
let mut resolved_params = Vec::with_capacity(params.len());
for (pname, ptype) in params {
resolved_params.push((pname.clone(), cx.state.resolve_tag(ptype)?));
}
cx.state.functions.define_aliased_in(
alias_frame,
alias,
name,
&resolved_params,
body,
Some(&key),
)?;
}
}
}
{
let type_exported: std::collections::HashSet<&str> =
type_exports.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.type_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.type_aliases.insert(name.clone(), target.clone());
}
let type_exported: std::collections::HashSet<&str> =
type_exports.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.type_aliases = saved_aliases.clone();
for (name, target) in to_persist {
insert_imported_type(cx.state, &name, &target, Some(alias), path)?;
}
} else {
cx.state.type_aliases = saved_aliases.clone();
}
}
if let Some(value) = cached {
return Ok(value);
}
let saved_vars = std::mem::take(&mut cx.state.var_scopes);
let saved_aliases = cx.state.type_aliases.clone();
let outcome: Result<Value> = (|| {
let aliases = super::typing::collect_type_aliases(&steps, cx.state)?;
for (name, target) in aliases {
cx.state.type_aliases.insert(name, target);
}
cx.state.import_stack.push(resolved.clone());
cx.state.push_scope();
let env_before: std::collections::HashMap<String, String> = (*cx.state.envs).clone();
cx.state.module_stack.push(Some(key.clone()));
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 flow = flow?;
let drained = std::mem::take(
cx.state
.var_scopes
.last_mut()
.expect("import pushed exactly one var scope"),
);
let value = match flow {
Flow::Done => Value::string(String::new()),
Flow::Return { value, .. } => value,
Flow::Break { idx } => {
bail!(
"step {}: BREAK cannot cross import boundary (in IMPORT `{}`)",
idx + 1,
path
);
}
Flow::Continue { idx } => {
bail!(
"step {}: CONTINUE cannot cross import boundary (in IMPORT `{}`)",
idx + 1,
path
);
}
};
let record = cx.state.modules.entry(key.clone()).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);
}
}
let mut inherit_names = Vec::new();
for step in &steps {
if let StepKind::InheritEnv { keys } = &step.kind {
inherit_names.extend(keys.iter().cloned());
}
}
record.init = Some(super::state::ModuleInit {
vars: drained,
return_value: value.clone(),
envs: module_env,
inherit_names,
});
Ok(value)
})();
let pop_res = cx.state.pop_scope();
cx.state.var_scopes = saved_vars;
let _ = cx.state.import_stack.pop();
if cx.state.import_stack.is_empty() {
cx.state.import_alias_frame = None;
}
cx.state.type_aliases = saved_aliases;
if outcome.is_ok() {
resolve_own_type_harvests(cx, &steps, &resolved)?;
}
match (outcome, pop_res) {
(Ok(value), Ok(())) => Ok(value),
(Err(e), _) => Err(e),
(Ok(_), Err(e)) => Err(e),
}
}
#[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 func_exports: Vec<String>,
pub type_exports: Vec<String>,
pub sites: Vec<ClosureSite>,
}
pub(crate) fn expand_import_closure<P: ProcessManager>(
state: &mut ExecState<P>,
steps: &[Step],
) -> Result<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>,
) -> Result<()> {
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 resolved_opt = dir.join(path).ok();
let file_exists = resolved_opt
.as_ref()
.is_some_and(|r| state.fs.entry_kind(r).is_ok());
if !file_exists && state.module_table.modules.contains_key(path) {
for name in type_names {
state.resolve_tag(name).map_err(|e| {
anyhow::anyhow!("IMPORT `{path}` has no such TYPE `{name}`: {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>,
) -> Result<()> {
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 resolved_opt = dir.join(path).ok();
let file_exists = resolved_opt
.as_ref()
.is_some_and(|r| state.fs.entry_kind(r).is_ok());
if !file_exists && state.module_table.modules.contains_key(path) {
for name in type_names {
state.resolve_tag(name).map_err(|e| {
anyhow::anyhow!("IMPORT `{path}` has no such TYPE `{name}`: {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>,
) -> Result<()> {
for body in child_bodies(kind) {
expand_walk(state, body, dir, stack, files)?;
}
Ok(())
}
pub(crate) fn child_bodies(kind: &StepKind) -> Vec<&[Step]> {
match kind {
StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => child_bodies(cmd),
StepKind::For { body, .. }
| StepKind::While { body, .. }
| StepKind::FuncDef { body, .. }
| StepKind::Timeout { body, .. }
| StepKind::Isolated { body, .. }
| StepKind::AssignAsync { 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
}
_ => Vec::new(),
}
}
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(),
func_exports: target.func_exports.clone(),
type_exports: target.type_exports.clone(),
sites: vec![site],
}),
}
}
struct ExpandedImport {
resolved: GuardedPath,
body: Vec<Step>,
func_exports: Vec<String>,
type_exports: Vec<String>,
nested: GuardedPath,
}
fn expand_load<P: ProcessManager>(
state: &mut ExecState<P>,
dir: &GuardedPath,
stack: &[GuardedPath],
path: &str,
) -> Result<ExpandedImport> {
let resolved = dir
.join(path)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` cannot be resolved: {e}"))?;
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);
bail!("IMPORT cycle detected: {}", chain.join(" -> "));
}
if stack.len() >= MAX_IMPORT_DEPTH {
bail!(
"IMPORT depth limit exceeded ({}): `{}`",
MAX_IMPORT_DEPTH,
path
);
}
if state.fs.entry_kind(&resolved).is_err() {
bail!(
"IMPORT `{path}` not found: the file must exist when the run starts (generated imports are not supported)"
);
}
let LoadedFile {
resolved,
steps: body,
func_exports,
type_exports,
} = load_file(state, dir, stack, path)?;
let nested = resolved.parent().unwrap_or_else(|| dir.clone());
Ok(ExpandedImport {
resolved,
body,
func_exports,
type_exports,
nested,
})
}
fn load_import<P: ProcessManager>(state: &mut ExecState<P>, path: &str) -> Result<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>,
func_exports: Vec<String>,
type_exports: Vec<String>,
}
fn load_file<P: ProcessManager>(
state: &mut ExecState<P>,
base: &GuardedPath,
stack: &[GuardedPath],
path: &str,
) -> Result<LoadedFile> {
let resolved = base
.join(path)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` cannot be resolved: {e}"))?;
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());
bail!("IMPORT cycle detected: {}", chain.join(" -> "));
}
if stack.len() >= MAX_IMPORT_DEPTH {
bail!(
"IMPORT depth limit exceeded ({}): `{}`",
MAX_IMPORT_DEPTH,
path
);
}
if let Some(record) = state.modules.get(&key) {
return Ok(LoadedFile {
resolved,
steps: record.steps.clone(),
func_exports: record.func_exports.clone(),
type_exports: record.type_exports.clone(),
});
}
let bytes = state
.fs
.read_file(&resolved)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` cannot be read: {e}"))?;
let text = std::str::from_utf8(&bytes)
.map_err(|e| anyhow::anyhow!("IMPORT `{path}` is not valid UTF-8: {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| anyhow::anyhow!("IMPORT `{path}` failed to parse: {e}"))?;
let dir = resolved.parent();
state.modules.insert(
key,
super::state::ModuleRecord {
steps: parsed.steps.clone(),
func_exports: parsed.func_exports.clone(),
type_exports: parsed.type_exports.clone(),
dir,
init: None,
},
);
Ok(LoadedFile {
resolved,
steps: parsed.steps,
func_exports: parsed.func_exports,
type_exports: parsed.type_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 = state
.fs
.workspace_root()
.cloned()
.unwrap_or_else(|| state.fs.build_context().clone());
if !parent.as_path().starts_with(base.as_path()) {
return base;
}
return parent;
}
if let Some(root) = state.fs.workspace_root() {
return root.clone();
}
state.fs.build_context().clone()
}