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