Skip to main content

xur_resolve/
loader.rs

1//! Loading every module reachable from the root file.
2//!
3//! `std::import(path)` is an ordinary function returning a module value, so
4//! it can be called anywhere with any string. Calls whose path is a string
5//! literal are found here and their files loaded ahead of time: missing
6//! files are reported before the program runs, and the module's names can
7//! be resolved statically. Other calls load their module at runtime.
8//!
9//! Paths are relative to the importing file, and each file is loaded once
10//! however often it is imported, so import cycles are fine.
11
12use std::collections::HashMap;
13use std::io;
14use std::path::{Component, Path, PathBuf};
15
16use xur_ast::visit::{self, Visitor};
17use xur_ast::{Expr, ExprKind, Lit, LitKind, Module, NodeId, NodeIdGen};
18use xur_errors::Diag;
19use xur_parser::parse_file;
20use xur_span::{FileLoader, SourceMap, Span, Symbol};
21
22/// Index of a module in [`Crate::modules`].
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub struct ModuleIdx(pub usize);
25
26/// Every module of a program, parsed.
27pub struct Crate {
28    pub source_map: SourceMap,
29    pub modules: Vec<LoadedModule>,
30    /// The file the program was started from.
31    pub root: ModuleIdx,
32    /// The built-in prelude, whose public items are in scope everywhere.
33    pub prelude: ModuleIdx,
34}
35
36impl Crate {
37    /// A crate containing only the prelude, ready for its root module to be
38    /// added next. The prelude source is provided by the caller (typically
39    /// from `xur_std::PRELUDE`).
40    pub(crate) fn with_prelude(
41        loader: &mut Loader,
42        diags: &mut Vec<Diag>,
43        prelude: &str,
44    ) -> Self {
45        let mut krate = Self {
46            source_map: SourceMap::new(),
47            modules: Vec::new(),
48            prelude: ModuleIdx(0),
49            root: ModuleIdx(1),
50        };
51        let path = PathBuf::from("<prelude>");
52        let idx = loader.add_tree(&mut krate, path, prelude.to_owned(), diags);
53        debug_assert_eq!(idx, krate.prelude);
54        krate.modules[idx.0].name = Symbol::intern("prelude");
55        krate
56    }
57
58    /// A crate with no prelude — the root module will be module 0.
59    pub(crate) fn without_prelude() -> Self {
60        Self {
61            source_map: SourceMap::new(),
62            modules: Vec::new(),
63            prelude: ModuleIdx(0),
64            root: ModuleIdx(0),
65        }
66    }
67
68    pub fn module(&self, idx: ModuleIdx) -> &LoadedModule {
69        &self.modules[idx.0]
70    }
71}
72
73pub struct LoadedModule {
74    /// The file stem, e.g. `math` for `math.xur`.
75    pub name: Symbol,
76    pub path: PathBuf,
77    pub ast: &'static Module,
78    /// The module loaded by each `std::import` call with a literal path,
79    /// keyed by the node id of the call's `std::import` path.
80    pub imports: HashMap<NodeId, ModuleIdx>,
81}
82
83/// A `std::import("path")` call with a literal path.
84struct Import {
85    /// The node id of the call's `std::import` path.
86    callee: NodeId,
87    path: PathBuf,
88    /// The span of the path literal.
89    span: Span,
90}
91
92/// If `expr` is `std::import("path")` with a literal path, returns the node
93/// id of its `std::import` path, the path and the literal's span.
94///
95/// Imports are recognised by their syntax, since files must be loaded
96/// before names can be resolved.
97pub(crate) fn static_import(expr: &Expr) -> Option<(NodeId, Symbol, Span)> {
98    let ExprKind::Call(callee, args) = &expr.kind else {
99        return None;
100    };
101    let ExprKind::Path(path) = &callee.kind else {
102        return None;
103    };
104    let is_std_import = matches!(
105        path.segments.as_slice(),
106        [std, import]
107            if std.ident.name.as_str() == "std"
108                && import.ident.name.as_str() == "import"
109                && std.args.is_none()
110                && import.args.is_none()
111    );
112    match args.as_slice() {
113        [
114            Expr {
115                kind:
116                    ExprKind::Lit(Lit {
117                        kind: LitKind::Str(relative),
118                        span,
119                    }),
120                ..
121            },
122        ] if is_std_import => Some((path.id, *relative, *span)),
123        _ => None,
124    }
125}
126
127/// Collects the literal-path imports in a module, with paths as written.
128struct ImportFinder(Vec<Import>);
129
130impl<'ast> Visitor<'ast> for ImportFinder {
131    fn visit_expr(&mut self, expr: &'ast Expr) {
132        if let Some((callee, path, span)) = static_import(expr) {
133            self.0.push(Import {
134                callee,
135                path: PathBuf::from(path.as_str()),
136                span,
137            });
138        }
139        visit::walk_expr(self, expr);
140    }
141}
142
143/// Loads files into a [`Crate`], remembering which are already loaded.
144pub(crate) struct Loader {
145    file_loader: Box<dyn FileLoader>,
146    by_path: HashMap<PathBuf, ModuleIdx>,
147    ids: NodeIdGen,
148}
149
150impl Loader {
151    pub(crate) fn new(file_loader: Box<dyn FileLoader>) -> Self {
152        Self {
153            file_loader,
154            by_path: HashMap::new(),
155            ids: NodeIdGen::default(),
156        }
157    }
158
159    pub(crate) fn read(&self, path: &Path) -> io::Result<String> {
160        self.file_loader.read_file(path)
161    }
162
163    /// The module already loaded from `path`, which must be normalised.
164    pub(crate) fn loaded(&self, path: &Path) -> Option<ModuleIdx> {
165        self.by_path.get(path).copied()
166    }
167
168    /// Adds the module at `path` with source `src` and, transitively, every
169    /// not yet loaded module it imports with a literal path.
170    pub(crate) fn add_tree(
171        &mut self,
172        krate: &mut Crate,
173        path: PathBuf,
174        src: String,
175        diags: &mut Vec<Diag>,
176    ) -> ModuleIdx {
177        let first = self.add_module(krate, path, src, diags);
178        let mut pending = vec![first];
179        while let Some(idx) = pending.pop() {
180            for mut import in find_imports(krate.module(idx)) {
181                if import.path.is_dir() {
182                    import.path = import.path.join("lib.xur");
183                }
184                let target = match self.loaded(&import.path) {
185                    Some(loaded) => loaded,
186                    None => match self.read(&import.path) {
187                        Ok(src) => {
188                            let loaded = self.add_module(krate, import.path, src, diags);
189                            pending.push(loaded);
190                            loaded
191                        }
192                        Err(error) => {
193                            let message =
194                                format!("couldn't read `{}`: {error}", import.path.display());
195                            diags.push(
196                                Diag::error(message, import.span)
197                                    .with_label(import.span, "imported here"),
198                            );
199                            continue;
200                        }
201                    },
202                };
203                krate.modules[idx.0].imports.insert(import.callee, target);
204            }
205        }
206        first
207    }
208
209    /// Parses `src` as the module at `path`. The AST is allocated for the
210    /// rest of the process, as rustc arena-allocates its ASTs, so that later
211    /// stages can hold references into it while more modules are loaded.
212    fn add_module(
213        &mut self,
214        krate: &mut Crate,
215        path: PathBuf,
216        src: String,
217        diags: &mut Vec<Diag>,
218    ) -> ModuleIdx {
219        let file = krate.source_map.add_file(path.display().to_string(), src);
220        let (ast, parse_diags) = parse_file(&file, &mut self.ids);
221        diags.extend(parse_diags);
222
223        let idx = ModuleIdx(krate.modules.len());
224        krate.modules.push(LoadedModule {
225            name: module_name(&path),
226            path: path.clone(),
227            ast: Box::leak(Box::new(ast)),
228            imports: HashMap::new(),
229        });
230        self.by_path.insert(path, idx);
231        idx
232    }
233}
234
235/// The literal-path `std::import` calls anywhere in `module`, with paths
236/// relative to the working directory.
237fn find_imports(module: &LoadedModule) -> Vec<Import> {
238    let dir = module.path.parent().unwrap_or(Path::new(""));
239    let mut finder = ImportFinder(Vec::new());
240    finder.visit_module(module.ast);
241    finder
242        .0
243        .into_iter()
244        .map(|import| Import {
245            path: normalize(&dir.join(&import.path)),
246            ..import
247        })
248        .collect()
249}
250
251/// A module is named after its file: `math` for `lib/math.xur`.
252/// A `lib.xur` is named after its parent folder: `my_plugin` for
253/// `my_plugin/lib.xur`.
254pub(crate) fn module_name(path: &Path) -> Symbol {
255    let stem = path.file_stem().unwrap_or(path.as_os_str());
256    if stem == "lib"
257        && let Some(parent) = path.parent().and_then(|p| p.file_name())
258    {
259        return Symbol::intern(&parent.to_string_lossy());
260    }
261    Symbol::intern(&stem.to_string_lossy())
262}
263
264/// Removes `.` and `..` components without touching the file system, so
265/// the same file imported by different relative paths is loaded once.
266pub(crate) fn normalize(path: &Path) -> PathBuf {
267    let mut normalized = PathBuf::new();
268    for component in path.components() {
269        match component {
270            Component::CurDir => {}
271            Component::ParentDir
272                if matches!(
273                    normalized.components().next_back(),
274                    Some(Component::Normal(_))
275                ) =>
276            {
277                normalized.pop();
278            }
279            other => normalized.push(other),
280        }
281    }
282    normalized
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use crate::Program;
289    use xur_span::MemoryFileLoader;
290
291    fn load(files: &[(&str, &str)]) -> (Crate, Vec<String>) {
292        let loader = Box::new(MemoryFileLoader::new(files.iter().copied()));
293        let (program, diags) = Program::load(
294            Path::new(files[0].0),
295            loader,
296            Box::new(crate::tests::natives()),
297            Some(xur_std::PRELUDE),
298        )
299        .unwrap();
300        (
301            program.krate,
302            diags.into_iter().map(|d| d.message).collect(),
303        )
304    }
305
306    fn names(krate: &Crate) -> Vec<&str> {
307        krate.modules.iter().map(|m| m.name.as_str()).collect()
308    }
309
310    #[test]
311    fn loads_imports_transitively() {
312        let (krate, diags) = load(&[
313            (
314                "src/main.xur",
315                r#"const math = std::import("./lib/math.xur");"#,
316            ),
317            (
318                "src/lib/math.xur",
319                r#"const util = std::import("../util.xur");"#,
320            ),
321            ("src/util.xur", "fn helper() {}"),
322        ]);
323        assert_eq!(diags, Vec::<String>::new());
324        assert_eq!(names(&krate), ["prelude", "main", "math", "util"]);
325        assert_eq!(krate.module(krate.root).path, Path::new("src/main.xur"));
326        assert_eq!(krate.modules[2].path, Path::new("src/lib/math.xur"));
327        assert_eq!(krate.modules[3].path, Path::new("src/util.xur"));
328    }
329
330    #[test]
331    fn each_file_is_loaded_once() {
332        let (krate, diags) = load(&[
333            (
334                "a.xur",
335                r#"const b = std::import("b.xur"); const b2 = std::import("./b.xur");"#,
336            ),
337            ("b.xur", r#"const a = std::import("a.xur");"#),
338        ]);
339        assert_eq!(diags, Vec::<String>::new());
340        assert_eq!(names(&krate), ["prelude", "a", "b"]);
341        let a = krate.module(krate.root);
342        assert!(a.imports.values().all(|&target| target == ModuleIdx(2)));
343        assert_eq!(krate.modules[2].imports.values().next(), Some(&krate.root));
344    }
345
346    #[test]
347    fn missing_import_is_reported() {
348        let (krate, diags) = load(&[("main.xur", r#"const m = std::import("missing.xur");"#)]);
349        assert_eq!(diags, ["couldn't read `missing.xur`: file not found"]);
350        assert!(krate.module(krate.root).imports.is_empty());
351    }
352
353    #[test]
354    fn literal_imports_anywhere_are_loaded() {
355        let (krate, diags) = load(&[
356            (
357                "main.xur",
358                r#"fn f() { let mods = [std::import("m.xur")]; }"#,
359            ),
360            ("m.xur", ""),
361        ]);
362        assert_eq!(diags, Vec::<String>::new());
363        assert_eq!(names(&krate), ["prelude", "main", "m"]);
364    }
365
366    #[test]
367    fn dynamic_imports_are_left_for_runtime() {
368        let (krate, diags) = load(&[("main.xur", "fn f(path: str) { std::import(path); }")]);
369        assert_eq!(diags, Vec::<String>::new());
370        assert!(krate.module(krate.root).imports.is_empty());
371    }
372
373    #[test]
374    fn syntax_errors_in_imported_files_are_reported() {
375        let (_, diags) = load(&[
376            ("main.xur", r#"const m = std::import("m.xur");"#),
377            ("m.xur", "fn f( {}"),
378        ]);
379        assert_eq!(diags.len(), 1);
380    }
381
382    #[test]
383    fn normalize_paths() {
384        assert_eq!(normalize(Path::new("a/./b/../c.xur")), Path::new("a/c.xur"));
385        assert_eq!(normalize(Path::new("../x.xur")), Path::new("../x.xur"));
386    }
387}