Skip to main content

xur_resolve/
lib.rs

1//! Loading modules and resolving names, after `rustc_resolve`.
2//!
3//! A [`Program`] is loaded from its root file and can grow at runtime as
4//! further modules are imported. Each batch of new modules is resolved in
5//! phases:
6//! 1. The modules reachable through literal-path `std::import`s are parsed.
7//! 2. Every module's items are declared in its [`Scope`](scope::Scope).
8//! 3. `use` declarations are resolved, repeatedly until no more make
9//!    progress, since one import may depend on another.
10//! 4. The functions of `impl` blocks are declared in their type's scope.
11//! 5. The names used inside items (bodies, types, patterns) are resolved
12//!    against local scopes and then the module.
13//!
14//! Names only ever resolve statically. Members reached through a value
15//! (`math.add`, `point.x`) are not names and are left for later stages.
16
17pub mod attributes;
18mod collect;
19mod def;
20pub(crate) mod expand;
21mod ident;
22mod imports;
23mod lang;
24mod late;
25mod loader;
26pub mod macros;
27mod names;
28mod native;
29mod natives;
30mod program;
31mod rt_type;
32mod scope;
33
34#[cfg(test)]
35mod tests;
36
37use std::any::Any;
38use std::collections::HashMap;
39use std::ops::Range;
40use std::sync::Arc;
41
42use xur_ast::NodeId;
43use xur_errors::Diag;
44use xur_span::{Ident, Symbol};
45
46pub use attributes::{AttrError, AttrInput, AttrLit, AttrTarget, AttributeKind};
47pub use def::{DefData, DefId, DefKind, Definitions, Namespace, PrimTy, Res};
48pub use lang::LangItems;
49pub use loader::{Crate, LoadedModule, ModuleIdx};
50pub use names::{NameRef, names};
51pub use native::{
52    NativeFnDecl, NativeFnId, NativeModule, NativeProvider, NativeTypeDecl, NativeTypeId,
53    NativeVariantDecl, NativeVariantKind,
54};
55pub use program::Program;
56pub use rt_type::RtType;
57
58use imports::Import;
59use scope::{Scope, Vis};
60
61/// The results of name resolution, keyed by AST node.
62#[derive(Debug)]
63pub struct Resolutions {
64    pub defs: Definitions,
65    /// What each path and each identifier pattern refers to. A pattern that
66    /// binds a variable resolves to [`Res::Local`] of itself.
67    pub res: HashMap<NodeId, Res>,
68    /// The name of each local variable, by the pattern that binds it.
69    pub locals: HashMap<NodeId, Ident>,
70    /// The definition created for each item, variant and generic parameter.
71    pub node_defs: HashMap<NodeId, DefId>,
72    /// The module definition of each loaded file, by [`ModuleIdx`].
73    pub module_defs: Vec<DefId>,
74    /// File modules whose name is left out of [`Resolutions::def_path`]: the
75    /// root module and the prelude.
76    unnamed_modules: Vec<DefId>,
77    /// The names declared in each module and enum.
78    scopes: HashMap<DefId, Scope>,
79    /// The top-level native modules, such as `std`, by name.
80    native_roots: HashMap<Symbol, DefId>,
81    /// Lazy native modules not yet expanded, with their paths.
82    lazy_natives: HashMap<DefId, Vec<String>>,
83    /// Repr enum variants (native and xur-defined), keyed by their DefId.
84    pub repr_values: HashMap<DefId, i64>,
85    /// Parsed values of registered attributes, keyed by the node they are on
86    /// and the attribute name. The value is the `#[derive(Facet)]` type the
87    /// attribute was registered with, type-erased (downcast via
88    /// [`Resolutions::attribute`]).
89    attributes: HashMap<AttrTarget, HashMap<Symbol, Arc<dyn Any + Send + Sync>>>,
90}
91
92impl Resolutions {
93    /// Resolutions with nothing but the native modules `natives`.
94    fn new(natives: &[NativeModule]) -> Self {
95        let mut defs = Definitions::default();
96        let mut scopes = HashMap::new();
97        let mut lazy_natives = HashMap::new();
98        let mut repr_values = HashMap::new();
99        let native_roots = natives::declare(
100            &mut defs,
101            &mut scopes,
102            &mut lazy_natives,
103            &mut repr_values,
104            natives,
105        );
106        Self {
107            defs,
108            res: HashMap::new(),
109            locals: HashMap::new(),
110            node_defs: HashMap::new(),
111            module_defs: Vec::new(),
112            unnamed_modules: Vec::new(),
113            scopes,
114            native_roots,
115            lazy_natives,
116            repr_values,
117            attributes: HashMap::new(),
118        }
119    }
120
121    /// Empty resolutions with no definitions. For lookups that only need
122    /// the registry (no xur-defined types).
123    pub fn empty() -> Self {
124        Self {
125            defs: Definitions::default(),
126            res: HashMap::new(),
127            locals: HashMap::new(),
128            node_defs: HashMap::new(),
129            module_defs: Vec::new(),
130            unnamed_modules: Vec::new(),
131            scopes: HashMap::new(),
132            native_roots: HashMap::new(),
133            lazy_natives: HashMap::new(),
134            repr_values: HashMap::new(),
135            attributes: HashMap::new(),
136        }
137    }
138
139    /// Records the parsed value of a registered attribute on `target`.
140    pub fn set_attribute(
141        &mut self,
142        target: AttrTarget,
143        name: Symbol,
144        value: Arc<dyn Any + Send + Sync>,
145    ) {
146        self.attributes
147            .entry(target)
148            .or_default()
149            .insert(name, value);
150    }
151
152    /// The parsed value of attribute `name` on `target`, as its registered
153    /// type `T` (the `#[derive(Facet)]` type it was registered with).
154    pub fn attribute<T: Any>(&self, target: AttrTarget, name: &str) -> Option<&T> {
155        self.attributes
156            .get(&target)?
157            .get(&Symbol::intern(name))?
158            .downcast_ref::<T>()
159    }
160
161    /// The path a definition is known by, e.g. `std::io::println`,
162    /// `math::div` or `Result::Ok`. Items of the root module and the prelude
163    /// are written without a module prefix.
164    pub fn def_path(&self, id: DefId) -> String {
165        format_def_path(&self.defs, &self.unnamed_modules, id)
166    }
167
168    /// The binding of `name` in namespace `ns` declared directly in the
169    /// module or type `scope`.
170    pub fn lookup(&self, scope: DefId, ns: Namespace, name: Symbol) -> Option<Res> {
171        Some(self.scopes.get(&scope)?.get(ns, name)?.res)
172    }
173
174    /// The function `name` of the struct, enum or native type `ty`: from an
175    /// `impl` block, or registered with a native type. For dispatching
176    /// `value.name()` at runtime.
177    pub fn assoc_fn(&self, ty: DefId, name: Symbol) -> Option<Res> {
178        match self.scopes.get(&ty)?.get(Namespace::Value, name)?.res {
179            res @ Res::Def(DefKind::Fn | DefKind::NativeFn(_), _) => Some(res),
180            _ => None,
181        }
182    }
183
184    /// Every name declared in `scope` in namespace `ns`.
185    pub fn scope_entries(&self, scope: DefId, ns: Namespace) -> Vec<(Symbol, Res)> {
186        let Some(s) = self.scopes.get(&scope) else {
187            return Vec::new();
188        };
189        s.iter(ns).map(|(name, b)| (name, b.res)).collect()
190    }
191
192    /// Every name declared in `scope` in namespace `ns` that may be named
193    /// from module `from`: all names when `scope` belongs to `from`, and
194    /// only the public ones otherwise. Mirrors the privacy check applied to
195    /// `scope::name` paths, so completion only offers reachable names.
196    pub fn accessible_entries(
197        &self,
198        scope: DefId,
199        ns: Namespace,
200        from: DefId,
201    ) -> Vec<(Symbol, Res)> {
202        let Some(s) = self.scopes.get(&scope) else {
203            return Vec::new();
204        };
205        let own_module = s.module == from;
206        s.iter(ns)
207            .filter(|(_, b)| own_module || b.vis == Vis::Public)
208            .map(|(name, b)| (name, b.res))
209            .collect()
210    }
211
212    /// The definition of a top-level root module by name (e.g. `std`).
213    pub fn root_module(&self, name: Symbol) -> Option<DefId> {
214        self.native_roots.get(&name).copied()
215    }
216
217    /// All top-level root modules (currently native; will include packages).
218    pub fn root_modules(&self) -> impl Iterator<Item = (Symbol, DefId)> + '_ {
219        self.native_roots.iter().map(|(&name, &def)| (name, def))
220    }
221
222    /// The DefId of a struct or enum with the given name (e.g. `Result`),
223    /// searching all definitions.
224    pub fn find_type(&self, name: &str) -> Option<DefId> {
225        self.defs.iter().find_map(|(id, data)| {
226            matches!(data.kind, DefKind::Struct | DefKind::Enum)
227                .then(|| (data.name.as_str() == name).then_some(id))
228                .flatten()
229        })
230    }
231
232    /// Every function of the struct, enum or native type `ty`, in the order
233    /// they were defined.
234    pub fn assoc_fns(&self, ty: DefId) -> Vec<(Symbol, DefId)> {
235        let Some(scope) = self.scopes.get(&ty) else {
236            return Vec::new();
237        };
238        let mut fns: Vec<_> = scope
239            .iter(Namespace::Value)
240            .filter_map(|(name, binding)| match binding.res {
241                Res::Def(DefKind::Fn | DefKind::NativeFn(_), def) => Some((name, def)),
242                _ => None,
243            })
244            .collect();
245        fns.sort_by_key(|&(_, def)| def);
246        fns
247    }
248}
249
250/// Resolves the modules `new` of `krate`, which were added since
251/// `resolutions` was last updated.
252fn resolve_modules(
253    krate: &Crate,
254    natives: &dyn NativeProvider,
255    resolutions: Resolutions,
256    new: Range<usize>,
257) -> (Resolutions, Vec<Diag>) {
258    let mut resolver = Resolver::resume(krate, natives, resolutions);
259    let new: Vec<_> = new.map(ModuleIdx).collect();
260    resolver.declare_modules(&new);
261    resolver.collect_items(&new);
262    resolver.resolve_imports();
263    resolver.collect_impls(&new);
264    resolver.inject_enum_builtins();
265    resolver.resolve_bodies(&new);
266    resolver.inject_enum_builtins();
267    resolver.suspend()
268}
269
270struct Resolver<'a> {
271    krate: &'a Crate,
272    natives: &'a dyn NativeProvider,
273    defs: Definitions,
274    /// The names declared in each module and enum.
275    scopes: HashMap<DefId, Scope>,
276    res: HashMap<NodeId, Res>,
277    locals: HashMap<NodeId, Ident>,
278    node_defs: HashMap<NodeId, DefId>,
279    module_defs: Vec<DefId>,
280    native_roots: HashMap<Symbol, DefId>,
281    lazy_natives: HashMap<DefId, Vec<String>>,
282    repr_values: HashMap<DefId, i64>,
283    attributes: HashMap<AttrTarget, HashMap<Symbol, Arc<dyn Any + Send + Sync>>>,
284    /// `use` declarations not yet resolved.
285    pending_imports: Vec<Import<'a>>,
286    /// What the type of each `impl` block resolved to, by the impl item.
287    impl_self_tys: HashMap<NodeId, Res>,
288    diags: Vec<Diag>,
289}
290
291impl<'a> Resolver<'a> {
292    /// Picks up resolution where `resolutions` left off.
293    fn resume(krate: &'a Crate, natives: &'a dyn NativeProvider, resolutions: Resolutions) -> Self {
294        let Resolutions {
295            defs,
296            res,
297            locals,
298            node_defs,
299            module_defs,
300            unnamed_modules: _,
301            scopes,
302            native_roots,
303            lazy_natives,
304            repr_values,
305            attributes,
306        } = resolutions;
307        Self {
308            krate,
309            natives,
310            defs,
311            scopes,
312            res,
313            locals,
314            node_defs,
315            module_defs,
316            native_roots,
317            lazy_natives,
318            repr_values,
319            attributes,
320            pending_imports: Vec::new(),
321            impl_self_tys: HashMap::new(),
322            diags: Vec::new(),
323        }
324    }
325
326    /// Creates the module definitions of the newly loaded modules `new`.
327    fn declare_modules(&mut self, new: &[ModuleIdx]) {
328        for &idx in new {
329            debug_assert_eq!(
330                idx.0,
331                self.module_defs.len(),
332                "modules are resolved in order"
333            );
334            let module = self.krate.module(idx);
335            let data = DefData {
336                kind: DefKind::Mod,
337                name: module.name,
338                parent: None,
339                span: Some(module.ast.span),
340            };
341            let def = create_scoped_def(&mut self.defs, &mut self.scopes, data, None);
342            self.module_defs.push(def);
343        }
344    }
345
346    fn module_def(&self, idx: ModuleIdx) -> DefId {
347        self.module_defs[idx.0]
348    }
349
350    fn prelude(&self) -> DefId {
351        self.module_def(self.krate.prelude)
352    }
353
354    fn report(&mut self, diag: Diag) {
355        self.diags.push(diag);
356    }
357
358    fn scope(&self, def: DefId) -> &Scope {
359        &self.scopes[&def]
360    }
361
362    /// Declares the contents of `scope` if it is a lazy native module not
363    /// yet expanded. Called before looking names up inside a scope.
364    fn expand_lazy(&mut self, scope: DefId) {
365        if let Some(path) = self.lazy_natives.remove(&scope) {
366            let contents = self.natives.expand(&path);
367            natives::populate(
368                &mut self.defs,
369                &mut self.scopes,
370                &mut self.lazy_natives,
371                &mut self.repr_values,
372                scope,
373                path,
374                &contents,
375            );
376        }
377    }
378
379    /// Hands the accumulated state back, with the diagnostics of this batch.
380    fn suspend(self) -> (Resolutions, Vec<Diag>) {
381        let unnamed_modules = [self.krate.root, self.krate.prelude]
382            .into_iter()
383            .filter_map(|idx| self.module_defs.get(idx.0).copied())
384            .collect();
385        let resolutions = Resolutions {
386            defs: self.defs,
387            res: self.res,
388            locals: self.locals,
389            node_defs: self.node_defs,
390            module_defs: self.module_defs,
391            unnamed_modules,
392            scopes: self.scopes,
393            native_roots: self.native_roots,
394            lazy_natives: self.lazy_natives,
395            repr_values: self.repr_values,
396            attributes: self.attributes,
397        };
398        (resolutions, self.diags)
399    }
400}
401
402/// Joins the names of `id` and its parents with `::`, leaving out the name
403/// of an `unnamed` outermost module unless it is `id` itself.
404fn format_def_path(defs: &Definitions, unnamed: &[DefId], id: DefId) -> String {
405    let lineage = defs.lineage(id);
406    let skip = usize::from(lineage.len() > 1 && unnamed.contains(&lineage[0]));
407    let names: Vec<_> = lineage[skip..]
408        .iter()
409        .map(|&id| defs.get(id).name.as_str())
410        .collect();
411    names.join("::")
412}
413
414/// Creates a module or enum definition along with its (empty) scope.
415/// `module` is the module an enum is declared in; `None` for a module
416/// itself.
417fn create_scoped_def(
418    defs: &mut Definitions,
419    scopes: &mut HashMap<DefId, Scope>,
420    data: DefData,
421    module: Option<DefId>,
422) -> DefId {
423    let def = defs.create(data);
424    scopes.insert(def, Scope::new(module.unwrap_or(def)));
425    def
426}