Skip to main content

harn_vm/vm/
modules.rs

1use std::cell::RefCell;
2use std::collections::{BTreeMap, HashSet};
3use std::future::Future;
4use std::path::{Path, PathBuf};
5use std::pin::Pin;
6use std::rc::Rc;
7
8use crate::value::{ModuleFunctionRegistry, VmClosure, VmEnv, VmError, VmValue};
9
10use super::{ScopeSpan, Vm};
11
12#[derive(Clone)]
13pub(crate) struct LoadedModule {
14    pub(crate) functions: BTreeMap<String, Rc<VmClosure>>,
15    pub(crate) public_names: HashSet<String>,
16}
17
18pub fn resolve_module_import_path(base: &Path, path: &str) -> PathBuf {
19    let synthetic_current_file = base.join("__harn_import_base__.harn");
20    if let Some(resolved) = harn_modules::resolve_import_path(&synthetic_current_file, path) {
21        return resolved;
22    }
23
24    let mut file_path = base.join(path);
25
26    if !file_path.exists() && file_path.extension().is_none() {
27        file_path.set_extension("harn");
28    }
29
30    file_path
31}
32
33impl Vm {
34    async fn load_module_from_source(
35        &mut self,
36        synthetic: PathBuf,
37        source: &str,
38    ) -> Result<LoadedModule, VmError> {
39        if let Some(loaded) = self.module_cache.get(&synthetic).cloned() {
40            return Ok(loaded);
41        }
42
43        let mut lexer = harn_lexer::Lexer::new(source);
44        let tokens = lexer.tokenize().map_err(|e| {
45            VmError::Runtime(format!("Import lex error in {}: {e}", synthetic.display()))
46        })?;
47        let mut parser = harn_parser::Parser::new(tokens);
48        let program = parser.parse().map_err(|e| {
49            VmError::Runtime(format!(
50                "Import parse error in {}: {e}",
51                synthetic.display()
52            ))
53        })?;
54
55        self.imported_paths.push(synthetic.clone());
56        let loaded = self.import_declarations(&program, None).await?;
57        self.imported_paths.pop();
58        self.module_cache.insert(synthetic, loaded.clone());
59        Ok(loaded)
60    }
61
62    fn export_loaded_module(
63        &mut self,
64        module_path: &Path,
65        loaded: &LoadedModule,
66        selected_names: Option<&[String]>,
67    ) -> Result<(), VmError> {
68        let export_names: Vec<String> = if let Some(names) = selected_names {
69            names.to_vec()
70        } else if !loaded.public_names.is_empty() {
71            loaded.public_names.iter().cloned().collect()
72        } else {
73            loaded.functions.keys().cloned().collect()
74        };
75
76        let module_name = module_path.display().to_string();
77        for name in export_names {
78            let Some(closure) = loaded.functions.get(&name) else {
79                return Err(VmError::Runtime(format!(
80                    "Import error: '{name}' is not defined in {module_name}"
81                )));
82            };
83            if let Some(VmValue::Closure(_)) = self.env.get(&name) {
84                return Err(VmError::Runtime(format!(
85                    "Import collision: '{name}' is already defined when importing {module_name}. \
86                     Use selective imports to disambiguate: import {{ {name} }} from \"...\""
87                )));
88            }
89            self.env
90                .define(&name, VmValue::Closure(Rc::clone(closure)), false)?;
91        }
92        Ok(())
93    }
94
95    /// Execute an import, reading and running the file's declarations.
96    pub(super) fn execute_import<'a>(
97        &'a mut self,
98        path: &'a str,
99        selected_names: Option<&'a [String]>,
100    ) -> Pin<Box<dyn Future<Output = Result<(), VmError>> + 'a>> {
101        Box::pin(async move {
102            let _import_span = ScopeSpan::new(crate::tracing::SpanKind::Import, path.to_string());
103
104            if let Some(module) = path.strip_prefix("std/") {
105                if let Some(source) = crate::stdlib_modules::get_stdlib_source(module) {
106                    let synthetic = PathBuf::from(format!("<stdlib>/{module}.harn"));
107                    if self.imported_paths.contains(&synthetic) {
108                        return Ok(());
109                    }
110                    let loaded = self
111                        .load_module_from_source(synthetic.clone(), source)
112                        .await?;
113                    self.export_loaded_module(&synthetic, &loaded, selected_names)?;
114                    return Ok(());
115                }
116                return Err(VmError::Runtime(format!(
117                    "Unknown stdlib module: std/{module}"
118                )));
119            }
120
121            let base = self
122                .source_dir
123                .clone()
124                .unwrap_or_else(|| PathBuf::from("."));
125            let file_path = resolve_module_import_path(&base, path);
126
127            let canonical = file_path
128                .canonicalize()
129                .unwrap_or_else(|_| file_path.clone());
130            if self.imported_paths.contains(&canonical) {
131                return Ok(());
132            }
133            if let Some(loaded) = self.module_cache.get(&canonical).cloned() {
134                return self.export_loaded_module(&canonical, &loaded, selected_names);
135            }
136            self.imported_paths.push(canonical.clone());
137
138            let source = std::fs::read_to_string(&file_path).map_err(|e| {
139                VmError::Runtime(format!(
140                    "Import error: cannot read '{}': {e}",
141                    file_path.display()
142                ))
143            })?;
144
145            let mut lexer = harn_lexer::Lexer::new(&source);
146            let tokens = lexer
147                .tokenize()
148                .map_err(|e| VmError::Runtime(format!("Import lex error: {e}")))?;
149            let mut parser = harn_parser::Parser::new(tokens);
150            let program = parser
151                .parse()
152                .map_err(|e| VmError::Runtime(format!("Import parse error: {e}")))?;
153
154            let loaded = self.import_declarations(&program, Some(&file_path)).await?;
155            self.imported_paths.pop();
156            self.module_cache.insert(canonical.clone(), loaded.clone());
157            self.export_loaded_module(&canonical, &loaded, selected_names)?;
158
159            Ok(())
160        })
161    }
162
163    /// Process top-level declarations from an imported module.
164    fn import_declarations<'a>(
165        &'a mut self,
166        program: &'a [harn_parser::SNode],
167        file_path: Option<&'a Path>,
168    ) -> Pin<Box<dyn Future<Output = Result<LoadedModule, VmError>> + 'a>> {
169        Box::pin(async move {
170            let caller_env = self.env.clone();
171            let old_source_dir = self.source_dir.clone();
172            self.env = VmEnv::new();
173            if let Some(fp) = file_path {
174                if let Some(parent) = fp.parent() {
175                    self.source_dir = Some(parent.to_path_buf());
176                }
177            }
178
179            for node in program {
180                match &node.node {
181                    harn_parser::Node::ImportDecl { path: sub_path } => {
182                        self.execute_import(sub_path, None).await?;
183                    }
184                    harn_parser::Node::SelectiveImport {
185                        names,
186                        path: sub_path,
187                    } => {
188                        self.execute_import(sub_path, Some(names)).await?;
189                    }
190                    _ => {}
191                }
192            }
193
194            // Route top-level `var`/`let` bindings into a shared
195            // `module_state` rather than `module_env`. If they appeared in
196            // `module_env` (captured by each closure's lexical snapshot),
197            // every call's per-invocation env clone would shadow them and
198            // writes would land in a per-call copy discarded on return.
199            let module_state: crate::value::ModuleState = {
200                let mut init_env = self.env.clone();
201                let init_nodes: Vec<harn_parser::SNode> = program
202                    .iter()
203                    .filter(|sn| {
204                        matches!(
205                            &sn.node,
206                            harn_parser::Node::VarBinding { .. }
207                                | harn_parser::Node::LetBinding { .. }
208                        )
209                    })
210                    .cloned()
211                    .collect();
212                if !init_nodes.is_empty() {
213                    let init_compiler = crate::Compiler::new();
214                    let init_chunk = init_compiler
215                        .compile(&init_nodes)
216                        .map_err(|e| VmError::Runtime(format!("Import init compile error: {e}")))?;
217                    // Save frame state so run_chunk_entry's top-level
218                    // frame-pop doesn't restore self.env.
219                    let saved_env = std::mem::replace(&mut self.env, init_env);
220                    let saved_frames = std::mem::take(&mut self.frames);
221                    let saved_handlers = std::mem::take(&mut self.exception_handlers);
222                    let saved_iterators = std::mem::take(&mut self.iterators);
223                    let saved_deadlines = std::mem::take(&mut self.deadlines);
224                    let init_result = self.run_chunk(&init_chunk).await;
225                    init_env = std::mem::replace(&mut self.env, saved_env);
226                    self.frames = saved_frames;
227                    self.exception_handlers = saved_handlers;
228                    self.iterators = saved_iterators;
229                    self.deadlines = saved_deadlines;
230                    init_result?;
231                }
232                Rc::new(RefCell::new(init_env))
233            };
234
235            let module_env = self.env.clone();
236            let registry: ModuleFunctionRegistry = Rc::new(RefCell::new(BTreeMap::new()));
237            let source_dir = file_path.and_then(|fp| fp.parent().map(|p| p.to_path_buf()));
238            let mut functions: BTreeMap<String, Rc<VmClosure>> = BTreeMap::new();
239            let mut public_names: HashSet<String> = HashSet::new();
240
241            for node in program {
242                // Imports may carry `@deprecated` / `@test` etc. on top-level
243                // fn decls; transparently peel the wrapper before pattern
244                // matching the FnDecl shape.
245                let inner = match &node.node {
246                    harn_parser::Node::AttributedDecl { inner, .. } => inner.as_ref(),
247                    _ => node,
248                };
249                let harn_parser::Node::FnDecl {
250                    name,
251                    params,
252                    body,
253                    is_pub,
254                    ..
255                } = &inner.node
256                else {
257                    continue;
258                };
259
260                let mut compiler = crate::Compiler::new();
261                let module_source_file = file_path.map(|p| p.display().to_string());
262                let func_chunk = compiler
263                    .compile_fn_body(params, body, module_source_file)
264                    .map_err(|e| VmError::Runtime(format!("Import compile error: {e}")))?;
265                let closure = Rc::new(VmClosure {
266                    func: Rc::new(func_chunk),
267                    env: module_env.clone(),
268                    source_dir: source_dir.clone(),
269                    module_functions: Some(Rc::clone(&registry)),
270                    module_state: Some(Rc::clone(&module_state)),
271                });
272                registry
273                    .borrow_mut()
274                    .insert(name.clone(), Rc::clone(&closure));
275                self.env
276                    .define(name, VmValue::Closure(Rc::clone(&closure)), false)?;
277                // Publish into module_state so sibling fns can be read
278                // as VALUES (e.g. `{handler: other_fn}` or as callbacks).
279                // Closures captured module_env BEFORE fn decls were added,
280                // so their static env alone can't resolve sibling fns.
281                // Direct calls use the module_functions late-binding path;
282                // value reads rely on this module_state entry.
283                module_state.borrow_mut().define(
284                    name,
285                    VmValue::Closure(Rc::clone(&closure)),
286                    false,
287                )?;
288                functions.insert(name.clone(), Rc::clone(&closure));
289                if *is_pub {
290                    public_names.insert(name.clone());
291                }
292            }
293
294            self.env = caller_env;
295            self.source_dir = old_source_dir;
296
297            Ok(LoadedModule {
298                functions,
299                public_names,
300            })
301        })
302    }
303
304    /// Load a module file and return the exported function closures that
305    /// would be visible to a wildcard import.
306    pub async fn load_module_exports(
307        &mut self,
308        path: &Path,
309    ) -> Result<BTreeMap<String, Rc<VmClosure>>, VmError> {
310        let path_str = path.to_string_lossy().into_owned();
311        self.execute_import(&path_str, None).await?;
312
313        let mut file_path = if path.is_absolute() {
314            path.to_path_buf()
315        } else {
316            self.source_dir
317                .clone()
318                .unwrap_or_else(|| PathBuf::from("."))
319                .join(path)
320        };
321        if !file_path.exists() && file_path.extension().is_none() {
322            file_path.set_extension("harn");
323        }
324
325        let canonical = file_path
326            .canonicalize()
327            .unwrap_or_else(|_| file_path.clone());
328        let loaded = self.module_cache.get(&canonical).cloned().ok_or_else(|| {
329            VmError::Runtime(format!(
330                "Import error: failed to cache loaded module '{}'",
331                canonical.display()
332            ))
333        })?;
334
335        let export_names: Vec<String> = if loaded.public_names.is_empty() {
336            loaded.functions.keys().cloned().collect()
337        } else {
338            loaded.public_names.iter().cloned().collect()
339        };
340
341        let mut exports = BTreeMap::new();
342        for name in export_names {
343            let Some(closure) = loaded.functions.get(&name) else {
344                return Err(VmError::Runtime(format!(
345                    "Import error: exported function '{name}' is missing from {}",
346                    canonical.display()
347                )));
348            };
349            exports.insert(name, Rc::clone(closure));
350        }
351
352        Ok(exports)
353    }
354
355    /// Load synthetic source keyed by a synthetic module path and return
356    /// the exported function closures that a wildcard import would expose.
357    pub async fn load_module_exports_from_source(
358        &mut self,
359        source_key: impl Into<PathBuf>,
360        source: &str,
361    ) -> Result<BTreeMap<String, Rc<VmClosure>>, VmError> {
362        let synthetic = source_key.into();
363        let loaded = self
364            .load_module_from_source(synthetic.clone(), source)
365            .await?;
366        let export_names: Vec<String> = if loaded.public_names.is_empty() {
367            loaded.functions.keys().cloned().collect()
368        } else {
369            loaded.public_names.iter().cloned().collect()
370        };
371
372        let mut exports = BTreeMap::new();
373        for name in export_names {
374            let Some(closure) = loaded.functions.get(&name) else {
375                return Err(VmError::Runtime(format!(
376                    "Import error: exported function '{name}' is missing from {}",
377                    synthetic.display()
378                )));
379            };
380            exports.insert(name, Rc::clone(closure));
381        }
382
383        Ok(exports)
384    }
385
386    /// Load a module by import path (`std/foo`, relative module path, or
387    /// package import) and return the exported function closures that a
388    /// wildcard import would expose.
389    pub async fn load_module_exports_from_import(
390        &mut self,
391        import_path: &str,
392    ) -> Result<BTreeMap<String, Rc<VmClosure>>, VmError> {
393        self.execute_import(import_path, None).await?;
394
395        if let Some(module) = import_path.strip_prefix("std/") {
396            let synthetic = PathBuf::from(format!("<stdlib>/{module}.harn"));
397            let loaded = self.module_cache.get(&synthetic).cloned().ok_or_else(|| {
398                VmError::Runtime(format!(
399                    "Import error: failed to cache loaded module '{}'",
400                    synthetic.display()
401                ))
402            })?;
403            let mut exports = BTreeMap::new();
404            let export_names: Vec<String> = if loaded.public_names.is_empty() {
405                loaded.functions.keys().cloned().collect()
406            } else {
407                loaded.public_names.iter().cloned().collect()
408            };
409            for name in export_names {
410                let Some(closure) = loaded.functions.get(&name) else {
411                    return Err(VmError::Runtime(format!(
412                        "Import error: exported function '{name}' is missing from {}",
413                        synthetic.display()
414                    )));
415                };
416                exports.insert(name, Rc::clone(closure));
417            }
418            return Ok(exports);
419        }
420
421        let base = self
422            .source_dir
423            .clone()
424            .unwrap_or_else(|| PathBuf::from("."));
425        let file_path = resolve_module_import_path(&base, import_path);
426        self.load_module_exports(&file_path).await
427    }
428}