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 the standard library's
32    /// `PRELUDE` constant, 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        crate::expand::expand_macros(&mut krate, natives.as_ref(), &mut loader.ids, &mut diags);
53
54        let resolutions = Resolutions::new(&natives.modules());
55        let (resolutions, resolve_diags) = resolve_modules(
56            &krate,
57            natives.as_ref(),
58            resolutions,
59            0..krate.modules.len(),
60        );
61        diags.extend(resolve_diags);
62        let program = Self {
63            krate,
64            natives,
65            resolutions: Some(resolutions),
66            loader,
67        };
68        Ok((program, diags))
69    }
70
71    /// The prelude definitions the language itself relies on.
72    pub fn lang_items(&self) -> LangItems {
73        LangItems::new(self)
74    }
75
76    pub fn resolutions(&self) -> &Resolutions {
77        self.resolutions
78            .as_ref()
79            .expect("resolutions are only taken while resolving")
80    }
81
82    /// Loads and resolves the module at `path` (relative to the working
83    /// directory) and anything it imports, unless already loaded.
84    ///
85    /// Fails if `path` cannot be read. Diagnostics are for the newly loaded
86    /// modules only.
87    pub fn import(&mut self, path: &Path) -> io::Result<(ModuleIdx, Vec<Diag>)> {
88        let mut path = normalize(path);
89        if path.is_dir() {
90            path = path.join("lib.xur");
91        }
92        if let Some(loaded) = self.loader.loaded(&path) {
93            return Ok((loaded, Vec::new()));
94        }
95        let src = self.loader.read(&path)?;
96        let first_new = self.krate.modules.len();
97        let mut diags = Vec::new();
98        let idx = self.loader.add_tree(&mut self.krate, path, src, &mut diags);
99
100        crate::expand::expand_macros(
101            &mut self.krate,
102            self.natives.as_ref(),
103            &mut self.loader.ids,
104            &mut diags,
105        );
106
107        let resolutions = self
108            .resolutions
109            .take()
110            .expect("resolutions are only taken while resolving");
111        let (resolutions, resolve_diags) = resolve_modules(
112            &self.krate,
113            self.natives.as_ref(),
114            resolutions,
115            first_new..self.krate.modules.len(),
116        );
117        self.resolutions = Some(resolutions);
118        diags.extend(resolve_diags);
119        Ok((idx, diags))
120    }
121}