Skip to main content

xur_resolve/
program.rs

1use std::io;
2use std::path::Path;
3
4use xur_errors::Diag;
5use xur_span::FileLoader;
6
7use crate::NativeProvider;
8
9use crate::loader::{Loader, normalize};
10use crate::{Crate, LangItems, ModuleIdx, Resolutions, resolve_modules};
11
12/// A loaded, name-resolved program that can grow while it runs.
13///
14/// [`Program::load`] loads the root file and every module it imports with
15/// a literal path. [`Program::import`] adds more modules later, as a
16/// dynamic `std::import` does; existing definitions, node ids and spans stay
17/// valid.
18pub struct Program {
19    pub krate: Crate,
20    natives: Box<dyn NativeProvider>,
21    /// Only `None` while a batch of modules is being resolved.
22    resolutions: Option<Resolutions>,
23    loader: Loader,
24}
25
26impl Program {
27    /// Loads and resolves the program rooted at `root`, with the native
28    /// modules of `natives` (such as `std`) available by name.
29    ///
30    /// When `prelude` is `Some`, its source is loaded as module 0 and its
31    /// public items are in scope everywhere. Pass `xur_std::PRELUDE` for
32    /// the standard prelude, or your own source to replace it.
33    ///
34    /// Fails only if `root` itself cannot be read; everything else wrong
35    /// with the program is returned as diagnostics.
36    pub fn load(
37        root: &Path,
38        file_loader: Box<dyn FileLoader>,
39        natives: Box<dyn NativeProvider>,
40        prelude: Option<&str>,
41    ) -> io::Result<(Self, Vec<Diag>)> {
42        let src = file_loader.read_file(root)?;
43        let mut loader = Loader::new(file_loader);
44        let mut diags = Vec::new();
45        let mut krate = match prelude {
46            Some(prelude_src) => Crate::with_prelude(&mut loader, &mut diags, prelude_src),
47            None => Crate::without_prelude(),
48        };
49        let root = loader.add_tree(&mut krate, normalize(root), src, &mut diags);
50        debug_assert_eq!(root, krate.root);
51
52        let resolutions = Resolutions::new(&natives.modules());
53        let (resolutions, resolve_diags) = resolve_modules(
54            &krate,
55            natives.as_ref(),
56            resolutions,
57            0..krate.modules.len(),
58        );
59        diags.extend(resolve_diags);
60        let program = Self {
61            krate,
62            natives,
63            resolutions: Some(resolutions),
64            loader,
65        };
66        Ok((program, diags))
67    }
68
69    /// The prelude definitions the language itself relies on.
70    pub fn lang_items(&self) -> LangItems {
71        LangItems::new(self)
72    }
73
74    pub fn resolutions(&self) -> &Resolutions {
75        self.resolutions
76            .as_ref()
77            .expect("resolutions are only taken while resolving")
78    }
79
80    /// Loads and resolves the module at `path` (relative to the working
81    /// directory) and anything it imports, unless already loaded.
82    ///
83    /// Fails if `path` cannot be read. Diagnostics are for the newly loaded
84    /// modules only.
85    pub fn import(&mut self, path: &Path) -> io::Result<(ModuleIdx, Vec<Diag>)> {
86        let mut path = normalize(path);
87        if path.is_dir() {
88            path = path.join("lib.xur");
89        }
90        if let Some(loaded) = self.loader.loaded(&path) {
91            return Ok((loaded, Vec::new()));
92        }
93        let src = self.loader.read(&path)?;
94        let first_new = self.krate.modules.len();
95        let mut diags = Vec::new();
96        let idx = self.loader.add_tree(&mut self.krate, path, src, &mut diags);
97
98        let resolutions = self
99            .resolutions
100            .take()
101            .expect("resolutions are only taken while resolving");
102        let (resolutions, resolve_diags) = resolve_modules(
103            &self.krate,
104            self.natives.as_ref(),
105            resolutions,
106            first_new..self.krate.modules.len(),
107        );
108        self.resolutions = Some(resolutions);
109        diags.extend(resolve_diags);
110        Ok((idx, diags))
111    }
112}