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