Skip to main content

raf_source/
code.rs

1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! Code-head lookup from an actual indexed source owner.
5
6mod aliases;
7mod library;
8mod syntax;
9pub use library::{ExternLibrary, ExternRouteKind};
10
11use std::error::Error;
12use std::fmt;
13
14use purrdf_lex::allocation::Memory;
15
16use crate::index::{Index, UseKind};
17use crate::meter::{ItemAdmission, Meter};
18use crate::reach::{Home, fill_homes};
19use crate::resolve::Heads;
20use crate::{
21    ImplId, ItemId, LoadError, LoadOptions, Namespace, Reach, RelPath, Resolution, ResolveError,
22    SymbolKind, TargetId, TestRole, Usage, Workspace,
23};
24
25/// Failure to establish a reading context or resolve its module-level code path.
26#[derive(Debug)]
27#[non_exhaustive]
28pub enum CodeResolveError {
29    /// The load-local owner is absent from this workspace.
30    UnknownItem(ItemId),
31    /// The load-local impl is absent from this workspace.
32    UnknownImpl(ImplId),
33    /// The byte is outside the selected item's source span.
34    OutsideItem(ItemId, usize),
35    /// An indexed owner has no source-owned reading module.
36    MissingContext(ItemId),
37    /// A definition-scope query names an item that is not a module.
38    ExpectedModule(ItemId),
39    /// Macro definition tokens require invocation context before name resolution.
40    MacroDefinition(ItemId),
41    /// The shared resolver refused the path; its original cause is retained.
42    Resolve(ResolveError),
43    /// The library's public surface refused its original resource or resolution query.
44    Exports(Box<crate::ExportError>),
45    /// Configured syntax selection preserves its original parser/load refusal.
46    ConfiguredSyntax(Box<LoadError>),
47    /// The bounded code query preserves its original resource refusal.
48    Query(Box<LoadError>),
49    /// Generic applicability of this inherent method is not established.
50    MethodApplicability(ItemId),
51    /// Alias-member applicability is outside the explicitly supported syntax.
52    AliasMember {
53        /// The actual alias definition needing additional evidence.
54        alias: ItemId,
55        /// The requested associated member.
56        member: String,
57        /// The missing applicability evidence.
58        reason: &'static str,
59    },
60    /// A configured syntax query lacks an actual admitted target/file context.
61    SyntaxContext {
62        /// The requested actual target.
63        target: TargetId,
64        /// The requested source file.
65        file: RelPath,
66        /// The missing context that the caller must supply.
67        reason: &'static str,
68    },
69    /// A definition exists but is not exported by the selected library.
70    NotExported {
71        /// The selected actual library root.
72        root: ItemId,
73        /// The requested relative API path.
74        path: String,
75    },
76}
77
78impl fmt::Display for CodeResolveError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            Self::UnknownItem(id) => write!(f, "source owner {id:?} is absent from this workspace"),
82            Self::UnknownImpl(id) => write!(f, "source impl {id:?} is absent from this workspace"),
83            Self::OutsideItem(id, byte) => write!(f, "byte {byte} is outside source owner {id:?}"),
84            Self::MissingContext(id) => write!(f, "source owner {id:?} has no reading module"),
85            Self::ExpectedModule(id) => write!(f, "source scope {id:?} is not a module"),
86            Self::MacroDefinition(id) => write!(
87                f,
88                "source owner {id:?} is a macro definition; code lookup requires an actual invocation context"
89            ),
90            Self::Resolve(error) => error.fmt(f),
91            Self::Exports(error) => error.fmt(f),
92            Self::ConfiguredSyntax(error) | Self::Query(error) => error.fmt(f),
93            Self::MethodApplicability(id) => write!(
94                f,
95                "inherent method {id:?} needs generic applicability evidence beyond plain nominal types and unconstrained forwarded const parameters"
96            ),
97            Self::AliasMember {
98                alias,
99                member,
100                reason,
101            } => write!(f, "alias {alias:?} member {member:?}: {reason}"),
102            Self::SyntaxContext {
103                target,
104                file,
105                reason,
106            } => write!(
107                f,
108                "configured syntax for {file} in target {target:?}: {reason}"
109            ),
110            Self::NotExported { root, path } => write!(
111                f,
112                "library root {root:?} does not export the definition of {path:?}"
113            ),
114        }
115    }
116}
117
118impl Error for CodeResolveError {
119    fn source(&self) -> Option<&(dyn Error + 'static)> {
120        match self {
121            Self::Resolve(error) => Some(error),
122            Self::Exports(error) => Some(error.as_ref()),
123            Self::ConfiguredSyntax(error) | Self::Query(error) => Some(error.as_ref()),
124            _ => None,
125        }
126    }
127}
128
129/// Module-level code lookup with source-owned item/module/target association.
130///
131/// A lookup uses code-head edition and dev/test rules, rather than `use` rules.
132/// The caller must first classify lexical locals, parameters, generic bindings
133/// and block imports. This query does not infer those scopes, expand macros,
134/// resolve `Self` or authenticate an unindexed dependency from its spelling.
135/// Item identities belong to the workspace that constructed this query.
136pub struct CodeResolver<'a> {
137    workspace: &'a Workspace,
138    options: &'a LoadOptions,
139    index: &'a Index,
140    homes: Vec<Home>,
141    usage: Usage,
142}
143
144/// One import in the module index, with its exact target and reading context.
145pub struct IndexedImport<'query, 'workspace> {
146    code: &'query CodeResolver<'workspace>,
147    position: usize,
148}
149
150impl IndexedImport<'_, '_> {
151    /// The target and location where this flattened import was written.
152    #[must_use]
153    pub fn site(&self) -> (TargetId, &RelPath, usize) {
154        let declaration = &self.code.index.uses[self.position];
155        (
156            self.code.index.modules[declaration.module].target,
157            &declaration.file,
158            declaration.line,
159        )
160    }
161
162    /// The imported path segments, whether they start with `::`, whether
163    /// the declaration imports a glob from that path, and the namespaces
164    /// in which the full path is read.
165    #[must_use]
166    pub fn path(&self) -> (&[String], bool, bool, &'static [Namespace]) {
167        let declaration = &self.code.index.uses[self.position];
168        let (segments, glob) = match &declaration.kind {
169            UseKind::Named { segs, .. } => (segs, false),
170            UseKind::Glob { segs } => (segs, true),
171        };
172        (
173            segments,
174            declaration.leading_colon,
175            glob,
176            declaration.kind.terminal_namespaces(),
177        )
178    }
179
180    /// Resolve the whole import path or a prefix of it in its own use context.
181    ///
182    /// # Errors
183    /// Preserves shared resolver errors, including invalid prefixes.
184    pub fn resolve(
185        &self,
186        path: &str,
187        namespace: Namespace,
188    ) -> Result<Resolution, CodeResolveError> {
189        let declaration = &self.code.index.uses[self.position];
190        self.code
191            .resolve_code_at(
192                declaration.module,
193                path,
194                namespace,
195                declaration.heads(self.position),
196            )
197            .map(|(resolution, _)| resolution)
198    }
199}
200
201impl<'a> CodeResolver<'a> {
202    pub(crate) fn new(
203        workspace: &'a Workspace,
204        index: &'a Index,
205        options: &'a LoadOptions,
206        usage: Usage,
207    ) -> Result<Self, LoadError> {
208        let meter = Meter::new(options);
209        let root = RelPath::root();
210        meter.items(usage.item_bytes, &root, None)?;
211        meter.items(
212            size_of::<&Workspace>() + size_of::<&LoadOptions>(),
213            &root,
214            None,
215        )?;
216        let mut homes = Vec::new();
217        {
218            let mut admission = ItemAdmission::new(&meter, &root);
219            Memory::new(&mut admission)
220                .reserve(&mut homes, index.items.len())
221                .map_err(|error| admission.error(error))?;
222        }
223        homes.resize(index.items.len(), Home::default());
224        fill_homes(index, &mut homes, true);
225        let mut usage = usage;
226        usage.item_bytes = meter.usage().item_bytes;
227        Ok(Self {
228            workspace,
229            options,
230            index,
231            homes,
232            usage,
233        })
234    }
235
236    /// The original load plus this query's retained reading-table allowance.
237    #[must_use]
238    pub const fn usage(&self) -> Usage {
239        self.usage
240    }
241
242    /// Every flattened module import in its exact admitted reading context.
243    pub fn indexed_imports(&self) -> impl Iterator<Item = IndexedImport<'_, 'a>> {
244        (0..self.index.uses.len()).map(|position| IndexedImport {
245            code: self,
246            position,
247        })
248    }
249
250    /// Resolve a name at the file's own module, as reached by this workspace.
251    /// Use this for file-level syntax that has no named item of its own.
252    ///
253    /// # Errors
254    /// Refuses a reach whose target or module is absent from this index.
255    /// Preserves every shared resolver error.
256    pub fn resolve_from_file_reach(
257        &self,
258        reach: &Reach,
259        path: &str,
260        namespace: Namespace,
261    ) -> Result<Resolution, CodeResolveError> {
262        let (module, heads) = self.file_context(reach, false)?;
263        self.resolve_code_at(module, path, namespace, heads)
264            .map(|(resolution, _)| resolution)
265    }
266
267    /// Resolve an import spelling in a file's own module and target.
268    ///
269    /// # Errors
270    /// Refuses an absent reach and preserves the shared resolver errors.
271    pub fn resolve_import_from_file_reach(
272        &self,
273        reach: &Reach,
274        path: &str,
275        namespace: Namespace,
276    ) -> Result<Resolution, CodeResolveError> {
277        let (module, heads) = self.file_context(reach, true)?;
278        self.resolve_code_at(module, path, namespace, heads)
279            .map(|(resolution, _)| resolution)
280    }
281
282    fn file_context(
283        &self,
284        reach: &Reach,
285        import: bool,
286    ) -> Result<(usize, Heads), CodeResolveError> {
287        let module = self
288            .index
289            .target_roots
290            .get(reach.target.index())
291            .and_then(|&root| {
292                self.index
293                    .module_by_path
294                    .get(&(root, reach.module_path.clone()))
295            })
296            .copied()
297            .ok_or_else(|| {
298                CodeResolveError::Resolve(ResolveError::UnknownModule(
299                    reach.module_path.to_string(),
300                ))
301            })?;
302        Ok((module, reading_heads(reach.test, import)))
303    }
304
305    /// Read a module-level path in the lexical module of an indexed impl.
306    /// Use this for the impl header, which has no named item of its own.
307    ///
308    /// # Errors
309    /// Refuses an unknown impl and preserves every shared resolver error.
310    pub fn resolve_from_impl(
311        &self,
312        implementation: ImplId,
313        path: &str,
314        namespace: Namespace,
315        import: bool,
316    ) -> Result<Resolution, CodeResolveError> {
317        let block = self
318            .workspace
319            .impl_block(implementation)
320            .ok_or(CodeResolveError::UnknownImpl(implementation))?;
321        let test = block.test != TestRole::None;
322        let heads = if import {
323            Heads::Use { test, own: None }
324        } else {
325            Heads::Code { test }
326        };
327        self.resolve_code_at(block.module_index, path, namespace, heads)
328            .map(|(resolution, _)| resolution)
329    }
330
331    fn module(&self, owner: ItemId, byte: usize) -> Result<usize, CodeResolveError> {
332        let item = self
333            .index
334            .items
335            .get(owner.index())
336            .ok_or(CodeResolveError::UnknownItem(owner))?;
337        if !(item.span.start_byte..item.span.end_byte).contains(&byte) {
338            return Err(CodeResolveError::OutsideItem(owner, byte));
339        }
340        if item.kind == SymbolKind::Mod
341            && item
342                .body
343                .as_ref()
344                .is_some_and(|body| (body.start_byte..body.end_byte).contains(&byte))
345        {
346            return self
347                .index
348                .module_of
349                .get(&owner)
350                .copied()
351                .ok_or(CodeResolveError::MissingContext(owner));
352        }
353        self.homes[owner.index()]
354            .module()
355            .ok_or(CodeResolveError::MissingContext(owner))
356    }
357
358    /// The actual reading module of a byte within an indexed owner.
359    /// Inline module bodies read their own module; their declaration headers
360    /// read the containing module. Method and trait ownership comes from Source.
361    ///
362    /// # Errors
363    /// Refuses an absent owner, outside byte or missing reading context.
364    pub fn reading_module(&self, owner: ItemId, byte: usize) -> Result<&str, CodeResolveError> {
365        Ok(self.index.modules[self.module(owner, byte)?].path.as_str())
366    }
367
368    /// Whether an owner's reading module and its ancestors have no indexed
369    /// configuration-dependent declarations or file reaches.
370    ///
371    /// This classifies the module route. The caller still checks the syntax
372    /// of the occurrence and its enclosing items.
373    ///
374    /// # Errors
375    /// Refuses an absent owner, outside byte, missing context or exceeded query grant.
376    pub fn has_unconditional_reading_module(
377        &self,
378        owner: ItemId,
379        byte: usize,
380    ) -> Result<bool, CodeResolveError> {
381        let module = self.module(owner, byte)?;
382        self.owner_query(owner, |index, steps| {
383            index.module_is_unconditional(module, steps)
384        })
385    }
386
387    /// Check a file reach's module and ancestor declarations for configuration dependence.
388    ///
389    /// # Errors
390    /// Refuses an absent reach or an exceeded query grant.
391    pub fn has_unconditional_file_reach(&self, reach: &Reach) -> Result<bool, CodeResolveError> {
392        self.file_query(reach, false, |index, module, _, steps| {
393            index.module_is_unconditional(module, steps)
394        })
395    }
396
397    /// Whether an indexed item is defined in this actual module or a descendant.
398    /// A relocated export and an impl member keep their lexical defining module.
399    /// Distinct targets never share scope merely because their paths agree.
400    ///
401    /// # Errors
402    /// Refuses absent identities, a non-module scope or missing reading context.
403    pub fn is_defined_in(&self, owner: ItemId, scope: ItemId) -> Result<bool, CodeResolveError> {
404        let item = self
405            .index
406            .items
407            .get(owner.index())
408            .ok_or(CodeResolveError::UnknownItem(owner))?;
409        let module = self
410            .index
411            .items
412            .get(scope.index())
413            .ok_or(CodeResolveError::UnknownItem(scope))?;
414        if module.kind != SymbolKind::Mod {
415            return Err(CodeResolveError::ExpectedModule(scope));
416        }
417        if item.target != module.target {
418            return Ok(false);
419        }
420        if owner == scope {
421            return Ok(true);
422        }
423        let wanted = self
424            .index
425            .module_of
426            .get(&scope)
427            .copied()
428            .or_else(|| {
429                self.index
430                    .root_items
431                    .get(&self.index.target_roots[module.target.index()])
432                    .filter(|id| **id == scope)
433                    .and_then(|_| self.homes[scope.index()].module())
434            })
435            .ok_or(CodeResolveError::MissingContext(scope))?;
436        let mut actual = self.homes[owner.index()]
437            .module()
438            .ok_or(CodeResolveError::MissingContext(owner))?;
439        loop {
440            if actual == wanted {
441                return Ok(true);
442            }
443            let Some(parent) = self.index.modules[actual].parent else {
444                return Ok(false);
445            };
446            actual = parent;
447        }
448    }
449
450    /// Resolve a module-level code path in one namespace from its actual owner.
451    /// Lexical shadow classification is a separate prerequisite; successful
452    /// module lookup alone is not proof that an occurrence names that item.
453    ///
454    /// # Errors
455    /// Refuses missing reading context and preserves every shared resolver error.
456    pub fn resolve_from_item_at(
457        &self,
458        owner: ItemId,
459        byte: usize,
460        path: &str,
461        namespace: Namespace,
462    ) -> Result<Resolution, CodeResolveError> {
463        self.resolve_owned(owner, byte, path, namespace, false)
464    }
465
466    /// Resolve an import spelling from an actual source owner's reading module.
467    /// This preserves edition-specific `use` roots for block import observations;
468    /// it does not register a lexical import or infer a missing external namespace.
469    ///
470    /// # Errors
471    /// The owner, macro-body and shared resolver refusals of code lookup.
472    pub fn resolve_import_from_item_at(
473        &self,
474        owner: ItemId,
475        byte: usize,
476        path: &str,
477        namespace: Namespace,
478    ) -> Result<Resolution, CodeResolveError> {
479        self.resolve_owned(owner, byte, path, namespace, true)
480    }
481
482    /// Follow visible imports to candidate members of indexed enums.
483    ///
484    /// Each candidate carries an enum identity and the terminal spelling in
485    /// the import. The caller validates the declaration and constructor form
486    /// and requires a unique surviving definition. Classify lexical shadowing before
487    /// asking this module-level query. Set `import` when the spelling was
488    /// written in an import declaration, to preserve its edition rules.
489    ///
490    /// An empty candidate list means the inspected routes supply no variants.
491    /// An existing definition or an inconclusive or conditional route returns
492    /// `None`, so the caller cannot infer the name is available to another route.
493    ///
494    /// # Errors
495    /// Refuses missing owner context, invalid paths and native
496    /// resource exhaustion.
497    pub fn enum_member_imports_from_item_at(
498        &self,
499        owner: ItemId,
500        byte: usize,
501        path: &str,
502        namespace: Namespace,
503        import: bool,
504    ) -> Result<Option<Vec<(ItemId, String)>>, CodeResolveError> {
505        let (module, heads) = self.owned_context(owner, byte, import)?;
506        self.owner_query(owner, |index, steps| {
507            index.enum_member_import(module, path, namespace, heads, steps)
508        })
509    }
510
511    /// Follow visible enum member imports from a file's own module and target.
512    ///
513    /// As [`Self::enum_member_imports_from_item_at`], validate candidates against the
514    /// enum declaration and set `import` for a spelling read in an import.
515    ///
516    /// # Errors
517    /// Refuses an absent reach, invalid path or exhausted query resources.
518    pub fn enum_member_imports_from_file_reach(
519        &self,
520        reach: &Reach,
521        path: &str,
522        namespace: Namespace,
523        import: bool,
524    ) -> Result<Option<Vec<(ItemId, String)>>, CodeResolveError> {
525        self.file_query(reach, import, |index, module, heads, steps| {
526            index.enum_member_import(module, path, namespace, heads, steps)
527        })
528    }
529
530    /// Find a single named type whose module and import route is unconditional.
531    /// Lexical bindings inside blocks and type alias substitution belong to the caller.
532    ///
533    /// # Errors
534    /// Refuses an invalid reading context or path and native resource exhaustion.
535    pub fn unconditional_type_from_item_at(
536        &self,
537        owner: ItemId,
538        byte: usize,
539        path: &str,
540        import: bool,
541    ) -> Result<Option<ItemId>, CodeResolveError> {
542        let (module, heads) = self.owned_context(owner, byte, import)?;
543        self.owner_query(owner, |index, steps| {
544            index.unconditional_type_path(module, path, heads, steps)
545        })
546    }
547
548    /// Find a single named type by an unconditional route from a file's own module.
549    ///
550    /// # Errors
551    /// Refuses an absent reach, invalid path or exhausted query resources.
552    pub fn unconditional_type_from_file_reach(
553        &self,
554        reach: &Reach,
555        path: &str,
556        import: bool,
557    ) -> Result<Option<ItemId>, CodeResolveError> {
558        self.file_query(reach, import, |index, module, heads, steps| {
559            index.unconditional_type_path(module, path, heads, steps)
560        })
561    }
562
563    fn file_query<T>(
564        &self,
565        reach: &Reach,
566        import: bool,
567        query: impl FnOnce(&'a Index, usize, Heads, crate::meter::Steps<'_>) -> Result<T, ResolveError>,
568    ) -> Result<T, CodeResolveError> {
569        let (module, heads) = self.file_context(reach, import)?;
570        let (file, line) = self.index.module_site(module);
571        self.query_at((&file, line), |index, steps| {
572            query(index, module, heads, steps)
573        })
574    }
575
576    fn owner_query<T>(
577        &self,
578        owner: ItemId,
579        query: impl FnOnce(&'a Index, crate::meter::Steps<'_>) -> Result<T, ResolveError>,
580    ) -> Result<T, CodeResolveError> {
581        let item = &self.index.items[owner.index()];
582        self.query_at((&item.file, Some(item.name_line)), query)
583    }
584
585    fn query_at<T>(
586        &self,
587        (file, line): (&RelPath, Option<usize>),
588        query: impl FnOnce(&'a Index, crate::meter::Steps<'_>) -> Result<T, ResolveError>,
589    ) -> Result<T, CodeResolveError> {
590        let meter = Meter::resume_query(
591            self.options,
592            Usage {
593                item_bytes: self.usage.item_bytes,
594                ..Usage::default()
595            },
596        );
597        let steps = crate::meter::Steps::QueryItems {
598            meter: &meter,
599            file,
600            line,
601        };
602        let answer = query(self.index, steps);
603        Index::query_refusal(steps)
604            .map_err(|refused| CodeResolveError::Resolve(self.index.refused(refused)))?;
605        answer.map_err(CodeResolveError::Resolve)
606    }
607
608    fn resolve_owned(
609        &self,
610        owner: ItemId,
611        byte: usize,
612        path: &str,
613        namespace: Namespace,
614        import: bool,
615    ) -> Result<Resolution, CodeResolveError> {
616        let (module, heads) = self.owned_context(owner, byte, import)?;
617        self.resolve_code_at(module, path, namespace, heads)
618            .map(|(resolution, _)| resolution)
619    }
620
621    fn owned_context(
622        &self,
623        owner: ItemId,
624        byte: usize,
625        import: bool,
626    ) -> Result<(usize, Heads), CodeResolveError> {
627        let module = self.module(owner, byte)?;
628        let item = &self.index.items[owner.index()];
629        if item.kind == SymbolKind::MacroRules
630            && item
631                .body
632                .as_ref()
633                .is_some_and(|body| (body.start_byte..body.end_byte).contains(&byte))
634        {
635            return Err(CodeResolveError::MacroDefinition(owner));
636        }
637        let test = self.index.items[owner.index()].test != TestRole::None;
638        Ok((module, reading_heads(test, import)))
639    }
640}
641
642fn reading_heads(test: bool, import: bool) -> Heads {
643    if import {
644        Heads::Use { test, own: None }
645    } else {
646        Heads::Code { test }
647    }
648}