Skip to main content

raf_source/
workspace.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//! The loaded workspace: packages, targets and the files of every module tree.
5
6mod locked;
7mod module_paths;
8mod selected;
9pub use locked::{
10    LockedBinding, LockedEdge, LockedManifest, LockedPackageRoots, LockedTree, ReferenceBinding,
11    ReferenceObservation, ReferencePackageRoots, ReferenceRequest, ReferenceTree,
12};
13pub use module_paths::ForeignModulePath;
14
15use std::cmp::Ordering;
16use std::collections::{BTreeMap, BTreeSet};
17use std::convert::Infallible;
18use std::rc::Rc;
19
20use purrdf_lex::allocation::Memory;
21use purrdf_lex::walk::{try_equal_range_by, try_sort_unstable_by};
22
23use crate::discovery::{Found, discover};
24use crate::error::{LoadError, LoadErrorKind, Origin};
25use crate::exports::{ExportError, ExportOptions, Exports, Surface};
26use crate::facts::{FileFacts, TestRole};
27use crate::index::{DependencyInfo, Index, LOAD_BASE_BYTES, PackageInfo};
28use crate::item::{ImplBlock, ImplId, Item, ItemId, Namespace, UnresolvedImpl};
29use crate::manifest::{
30    self, Dependency, DependencyDeclaration, EditionDecl, InheritedDependency, Manifest,
31    PackageDecl, PathSource, VersionDecl, WorkspaceDependency,
32};
33use crate::members::members;
34use crate::meter::{ItemAdmission, Meter, Usage};
35use crate::modtree::{Reach, TargetId, Visited, WalkConfiguration, Walked, Walker, tidy};
36use crate::options::LoadOptions;
37#[cfg(target_os = "linux")]
38use crate::parse::ConfigurationKey;
39use crate::path::{PathError, RelPath};
40use crate::reach::{self, Node, ReachError, Reachability};
41use crate::resolve::{Resolution, ResolutionAttempt, ResolveError};
42use crate::target::TargetKind;
43use crate::target::{Context, Package, PackageId, Target, check_crate_paths, derive_targets};
44use crate::tree::Tree;
45
46#[derive(Clone, Copy)]
47enum SyntaxLoad<'a> {
48    Ordinary(Option<&'a dyn crate::parse::Parser>),
49    ShippingMembers,
50    Configured(crate::DeclaredConfiguration<'a>),
51    #[cfg(target_os = "linux")]
52    ConfiguredParallel(crate::DeclaredConfiguration<'a>, &'a crate::ParallelOptions),
53    #[cfg(target_os = "linux")]
54    LockedParallel(&'a crate::ParallelOptions),
55}
56
57impl<'a> SyntaxLoad<'a> {
58    fn declared(self) -> Option<crate::DeclaredConfiguration<'a>> {
59        match self {
60            Self::Ordinary(_) | Self::ShippingMembers => None,
61            Self::Configured(configuration) => Some(configuration),
62            #[cfg(target_os = "linux")]
63            Self::ConfiguredParallel(configuration, _) => Some(configuration),
64            #[cfg(target_os = "linux")]
65            Self::LockedParallel(_) => None,
66        }
67    }
68}
69
70struct SourceWalk {
71    walked: Walked,
72    #[cfg(target_os = "linux")]
73    parallel_usage: Option<crate::ParallelUsage>,
74}
75
76/// A source file of the workspace, parsed once.
77///
78/// The facts the index is built from stay inside the crate; the items of a
79/// file are read through [`Workspace::items_in`] and the other accessors.
80///
81/// The struct is `#[non_exhaustive]`: adding a field is not a breaking change,
82/// so a pattern names the fields it reads and ends in `..`.
83///
84/// ```compile_fail,E0638
85/// # fn names(file: &raf_source::SourceFile) {
86/// let raf_source::SourceFile { path, package, shipping, test, text, reached } = file;
87/// # }
88/// ```
89#[derive(Debug, PartialEq, Eq)]
90#[non_exhaustive]
91pub struct SourceFile {
92    /// The path, relative to the tree root.
93    pub path: RelPath,
94    /// The name of the package of the first target that reaches the file.
95    pub package: String,
96    /// True when some target that ships (library, binary, build script)
97    /// reaches the file other than through test code.
98    pub shipping: bool,
99    /// True when every way of reaching the file goes through test code.
100    pub test: bool,
101    /// The exact text that was parsed.
102    pub text: String,
103    /// The facts read from it.
104    pub(crate) facts: FileFacts,
105    /// Every way a module tree reaches the file, in the order the walk
106    /// found them.
107    pub reached: Vec<Reach>,
108}
109
110impl SourceFile {
111    /// True when every way of reaching the file goes through test code. The
112    /// items of such a file are test code whatever their own attributes say.
113    #[must_use]
114    pub fn reached_only_through_tests(&self) -> bool {
115        self.reached.iter().all(|reach| reach.test)
116    }
117}
118
119/// The packages, targets and source files found under a set of roots.
120///
121/// Two workspaces are equal when their packages, targets, files and index are;
122/// what the loads spent ([`Workspace::usage`]) can differ between backends
123/// that hold the same files, as a disk identity holds no text.
124#[derive(Debug)]
125pub struct Workspace {
126    packages: Vec<Package>,
127    dependencies: Vec<Vec<DependencyDeclaration>>,
128    /// The version each package declares, retained from the load's own read.
129    versions: Vec<DeclaredVersion>,
130    locked: Vec<LockedBinding>,
131    references: Vec<LockedBinding>,
132    selected_configuration: Option<crate::ActiveConfiguration>,
133    /// Package IDs sorted by display name, then by their exact load-local ID.
134    package_names: Vec<PackageId>,
135    targets: Vec<Target>,
136    files: BTreeMap<RelPath, SourceFile>,
137    index: Index,
138    usage: Usage,
139    #[cfg(target_os = "linux")]
140    parallel_usage: Option<crate::ParallelUsage>,
141    /// The options of the load, whose item-bytes budget also bounds what a
142    /// query such as [`Workspace::exported_items`] holds.
143    options: LoadOptions,
144}
145
146impl PartialEq for Workspace {
147    fn eq(&self, other: &Self) -> bool {
148        self.packages == other.packages
149            && self.dependencies == other.dependencies
150            && self.versions == other.versions
151            && self.locked == other.locked
152            && self.references == other.references
153            && self.selected_configuration == other.selected_configuration
154            && self.package_names == other.package_names
155            && self.targets == other.targets
156            && self.files == other.files
157            && self.index == other.index
158    }
159}
160
161impl Eq for Workspace {}
162
163impl Workspace {
164    /// The separately retained declaration of an exact-target load.
165    pub(crate) fn selected_configuration(&self) -> Option<&crate::ActiveConfiguration> {
166        self.selected_configuration.as_ref()
167    }
168
169    /// Prepare module-level code lookup from actual source owner identities.
170    /// The retained reading table is admitted under this load's original limit.
171    /// This does not classify lexical shadows or prove provider delegation.
172    ///
173    /// # Errors
174    /// Refuses exhausted original item allowance or native storage admission.
175    pub fn code_resolver(&self) -> Result<crate::CodeResolver<'_>, LoadError> {
176        crate::CodeResolver::new(self, &self.index, &self.options, self.usage)
177    }
178
179    /// Load the packages under `roots` with the default [`LoadOptions`].
180    ///
181    /// A root is a directory path relative to the tree root; `"."` is the tree
182    /// root itself. There are no default roots: each caller names its own, and
183    /// an empty list is a [`LoadErrorKind::NoRoots`] error.
184    ///
185    /// # Errors
186    ///
187    /// Returns the first [`LoadError`] the walk meets; see
188    /// [`Workspace::load_with`].
189    pub fn load(tree: &dyn Tree, roots: &[&str]) -> Result<Self, LoadError> {
190        Self::load_with(tree, roots, &LoadOptions::default())
191    }
192
193    /// Load the packages under `roots`.
194    ///
195    /// Discovery finds every package, then each package's targets are derived
196    /// and each target's module tree is followed. The load returns the first
197    /// error, in the order discovery, targets, module walk, index, and does not
198    /// collect errors; the error names the file, the line when there is one,
199    /// and the module, attribute or manifest key that led to it.
200    ///
201    /// # Errors
202    ///
203    /// Returns a [`LoadError`] for an empty `roots` list, a root that is missing or
204    /// not a directory, a manifest that cannot be read, a target problem, an
205    /// unresolved or ambiguous `mod`, a path that leaves the tree, a module cycle,
206    /// a file over `max_file_bytes`, a load over a [`Budget`](crate::Budget) (the
207    /// byte budgets as `options` sets them), or a syntax error.
208    ///
209    /// Of the items that syn has no node for, a `use` group with a member that
210    /// starts with `::`, a function with no body and a type with no definition
211    /// are indexed. Other opaque module or associated declarations qualify
212    /// for [`Self::disabled_syntax`] when an outer `cfg(any())` proves them
213    /// disabled. Otherwise they return [`LoadErrorKind::UnsupportedItem`]
214    /// with the file and the first line of the item.
215    pub fn load_with(
216        tree: &dyn Tree,
217        roots: &[&str],
218        options: &LoadOptions,
219    ) -> Result<Self, LoadError> {
220        let mut root_paths = Vec::new();
221        for root in roots {
222            let path = RelPath::new(root).map_err(|error| {
223                LoadError::tree(
224                    &RelPath::root(),
225                    None,
226                    &Origin::Discovery,
227                    crate::error::TreeError::from(error),
228                )
229            })?;
230            root_paths.push(path);
231        }
232        Self::load_from(tree, &root_paths, options)
233    }
234
235    /// Load a stable native Linux Tree with bounded parallel parsing.
236    ///
237    /// The coordinator retains Tree access and canonical fact/index admission.
238    /// Source observations and failures must be independent of read order.
239    /// Native ASTs and spans stay on fresh 64 MiB parser threads; the additional
240    /// scheduler ownership grant is not a complete native parser heap bound.
241    ///
242    /// # Errors
243    /// Returns the canonical input errors of [`Self::load_with`], or actionable
244    /// scheduler-storage and worker-start failures. All workers are joined.
245    ///
246    /// # Panics
247    /// Resumes the first canonically reached parser panic after worker cleanup.
248    #[cfg(target_os = "linux")]
249    pub fn par_load(
250        tree: &dyn crate::ParallelTree,
251        roots: &[&str],
252        options: &LoadOptions,
253        parallel: &crate::ParallelOptions,
254    ) -> Result<Self, LoadError> {
255        let mut root_paths = Vec::new();
256        for root in roots {
257            root_paths.push(RelPath::new(root).map_err(|error| {
258                LoadError::tree(&RelPath::root(), None, &Origin::Discovery, error.into())
259            })?);
260        }
261        let resources = crate::parse::parallel::Resources::new(parallel)?;
262        std::thread::scope(|scope| {
263            let parser = crate::parse::parallel::Executor::new(scope, &resources, parallel, None)?;
264            let meter = Meter::new(options);
265            let result = Self::load_meter_with_syntax(
266                tree,
267                &root_paths,
268                options,
269                &meter,
270                None,
271                SyntaxLoad::Ordinary(Some(&parser)),
272            );
273            let usage = parser.finish();
274            result.map(|mut workspace| {
275                workspace.parallel_usage = Some(usage);
276                workspace
277            })
278        })
279    }
280
281    /// Load explicit roots, retaining each path's selected source authority.
282    ///
283    /// [`crate::SourceTrees`] dispatches independently rooted sources. This is
284    /// physical source selection, not locked dependency or configuration proof.
285    /// Ordinary [`Workspace::load_with`] calls this same loader with first-party
286    /// roots. Paths returned on packages, targets and items retain their source.
287    ///
288    /// # Errors
289    ///
290    /// As [`Workspace::load_with`], including an unavailable source authority.
291    pub fn load_from(
292        tree: &dyn Tree,
293        roots: &[RelPath],
294        options: &LoadOptions,
295    ) -> Result<Self, LoadError> {
296        let meter = Meter::new(options);
297        Self::load_meter(tree, roots, options, &meter, None)
298    }
299
300    /// Load the declared members at one selected Cargo workspace root.
301    ///
302    /// The membership walk applies Cargo's members, exclusions and local path
303    /// dependency membership rules. A standalone package selects itself.
304    ///
305    /// # Errors
306    /// Refuses missing or malformed member manifests and the ordinary
307    /// workspace load's source, resolution and resource failures.
308    pub fn load_members(
309        tree: &dyn Tree,
310        root: &RelPath,
311        options: &LoadOptions,
312    ) -> Result<Self, LoadError> {
313        Self::members_with_syntax(tree, root, options, SyntaxLoad::Ordinary(None))
314    }
315
316    /// Load the workspace members' libraries, binaries and build scripts.
317    ///
318    /// Uses the membership rules of [`Self::load_members`]. Selects the shipping
319    /// target roots before parsing their module trees. Test, example and bench
320    /// targets do not contribute roots to this load.
321    ///
322    /// # Errors
323    /// Refuses member discovery, target declaration and selected source errors.
324    pub fn load_shipping_members(
325        tree: &dyn Tree,
326        root: &RelPath,
327        options: &LoadOptions,
328    ) -> Result<Self, LoadError> {
329        Self::members_with_syntax(tree, root, options, SyntaxLoad::ShippingMembers)
330    }
331
332    fn members_with_syntax(
333        tree: &dyn Tree,
334        root: &RelPath,
335        options: &LoadOptions,
336        syntax: SyntaxLoad<'_>,
337    ) -> Result<Self, LoadError> {
338        let meter = Meter::new(options);
339        meter.items(LOAD_BASE_BYTES, root, None)?;
340        let selected = crate::discovery::workspace_members(tree, root, &meter)?;
341        Self::build_discovered_with_syntax(tree, options, &meter, None, &selected, syntax)
342    }
343
344    fn load_meter(
345        tree: &dyn Tree,
346        roots: &[RelPath],
347        options: &LoadOptions,
348        meter: &Meter,
349        binding: Option<&locked::BindingLoad<'_>>,
350    ) -> Result<Self, LoadError> {
351        Self::load_meter_with_syntax(
352            tree,
353            roots,
354            options,
355            meter,
356            binding,
357            SyntaxLoad::Ordinary(None),
358        )
359    }
360
361    fn load_meter_with_syntax(
362        tree: &dyn Tree,
363        roots: &[RelPath],
364        options: &LoadOptions,
365        meter: &Meter,
366        binding: Option<&locked::BindingLoad<'_>>,
367        syntax: SyntaxLoad<'_>,
368    ) -> Result<Self, LoadError> {
369        let root = RelPath::root();
370        if roots.is_empty() {
371            return Err(LoadError::new(&root, None, LoadErrorKind::NoRoots));
372        }
373        meter.items(LOAD_BASE_BYTES, &root, None)?;
374        let discovered = discover(tree, roots, meter)?;
375        Self::build_discovered_with_syntax(tree, options, meter, binding, &discovered, syntax)
376    }
377
378    fn build_discovered(
379        tree: &dyn Tree,
380        options: &LoadOptions,
381        meter: &Meter,
382        binding: Option<&locked::BindingLoad<'_>>,
383        discovered: &crate::discovery::Discovered,
384    ) -> Result<Self, LoadError> {
385        Self::build_discovered_with_syntax(
386            tree,
387            options,
388            meter,
389            binding,
390            discovered,
391            SyntaxLoad::Ordinary(None),
392        )
393    }
394
395    fn build_discovered_with_syntax(
396        tree: &dyn Tree,
397        options: &LoadOptions,
398        meter: &Meter,
399        binding: Option<&locked::BindingLoad<'_>>,
400        discovered: &crate::discovery::Discovered,
401        syntax: SyntaxLoad<'_>,
402    ) -> Result<Self, LoadError> {
403        let root = RelPath::root();
404        let found = &discovered.packages;
405        let dirs = package_directory_index(found, meter)?;
406        let mut infos = Vec::new();
407        let mut admission = ItemAdmission::new(meter, &root);
408        Memory::new(&mut admission)
409            .reserve(&mut infos, found.len())
410            .map_err(|error| admission.error(error))?;
411        let mut caches = Caches::default();
412        let reader = Reader {
413            tree,
414            meter,
415            dirs: &dirs,
416            found,
417        };
418        let mut locked = binding.map_or_else(
419            || Ok(Vec::new()),
420            |binding| locked::bind_found(binding, &reader, &mut caches),
421        )?;
422        let (mut packages, mut derived) = (Vec::new(), Vec::new());
423        let mut dependencies = Vec::new();
424        let mut dependency_admission = ItemAdmission::new(meter, &root);
425        Memory::new(&mut dependency_admission)
426            .reserve(&mut dependencies, found.len())
427            .map_err(|error| dependency_admission.error(error))?;
428        for (package_index, entry) in found.iter().enumerate() {
429            let context = Context {
430                package_id: PackageId(package_index),
431                tree,
432                manifest_path: &entry.package.manifest,
433                dir: &entry.package.dir,
434                manifest: &entry.manifest,
435                package: &entry.declared,
436            };
437            for target in derive_targets(&context)? {
438                derived.push((&entry.package.manifest, target));
439            }
440            infos.push(package_info(
441                &reader,
442                &entry.package,
443                &entry.declared,
444                &entry.manifest,
445                &mut caches,
446            )?);
447            dependencies.push(dependency_declarations(
448                &reader,
449                &entry.package,
450                &entry.manifest,
451                &mut caches,
452            )?);
453            packages.push(entry.package.clone());
454        }
455        let selected = configure_targets(
456            &reader,
457            &dependencies,
458            binding,
459            &mut locked,
460            &mut infos,
461            &mut derived,
462            syntax,
463        )?;
464        let versions = declared_versions(&reader, found, &mut caches)?;
465        let package_names = package_name_index(&packages, meter)?;
466        let (targets, origins) = selected_targets(derived)?;
467        let source = walk_source_syntax(
468            tree,
469            &targets,
470            &origins,
471            &locked,
472            selected.as_ref(),
473            meter,
474            syntax,
475        )?;
476        let files = source_files(source.walked.files, &targets)?;
477        reader.install_edges(binding, &dependencies, &locked, &targets, &mut infos)?;
478        let index = Index::build(
479            &targets,
480            &files,
481            &source.walked.visits,
482            &infos,
483            source.walked.paths,
484            meter,
485        )?;
486        let (locked, references) = binding_sets(binding, locked);
487        Ok(Self {
488            packages,
489            dependencies,
490            versions,
491            locked,
492            references,
493            selected_configuration: selected,
494            package_names,
495            targets,
496            files,
497            index,
498            usage: meter.usage(),
499            #[cfg(target_os = "linux")]
500            parallel_usage: source.parallel_usage,
501            options: options.clone(),
502        })
503    }
504
505    /// The index, for the tests of the crate.
506    #[cfg(test)]
507    pub(crate) fn index(&self) -> &Index {
508        &self.index
509    }
510
511    /// What the load spent against its budgets: the bytes it read, kept in the
512    /// index and in the facts of its files, the most tokens of one file and
513    /// the deepest directory it entered.
514    #[must_use]
515    pub fn usage(&self) -> Usage {
516        self.usage
517    }
518
519    /// Scheduler high-water counts after all parallel workers have joined.
520    ///
521    /// Serial loads return `None`. These counts are separate from semantic
522    /// [`Usage`] and are excluded from workspace structural equality.
523    #[cfg(target_os = "linux")]
524    #[must_use]
525    pub fn parallel_usage(&self) -> Option<crate::ParallelUsage> {
526        self.parallel_usage
527    }
528
529    /// The packages, sorted by manifest path.
530    #[must_use]
531    pub fn packages(&self) -> &[Package] {
532        &self.packages
533    }
534
535    /// Written dependency constraints for an exact load-local package.
536    ///
537    /// Includes normal, development and build dependencies under all target
538    /// conditions. Inheritance retains both declarations and their manifest base;
539    /// this does not establish active features, a lock edge or source provenance.
540    /// An unknown package identity returns `None` rather than another package's data.
541    #[must_use]
542    pub fn dependency_declarations(&self, package: PackageId) -> Option<&[DependencyDeclaration]> {
543        self.dependencies.get(package.index()).map(Vec::as_slice)
544    }
545
546    /// Checked source/manifest identity of a package admitted by a locked load.
547    /// This records provenance, not active cfg/features or provider-policy acceptance.
548    #[must_use]
549    pub fn locked_binding(&self, package: PackageId) -> Option<&LockedBinding> {
550        self.locked.get(package.index())
551    }
552
553    /// A package by its load-local identity.
554    #[must_use]
555    pub fn package(&self, id: PackageId) -> Option<&Package> {
556        self.packages.get(id.index())
557    }
558
559    /// The version that package `id` declares, explicit or inherited from its
560    /// workspace, read once by the load that built this workspace. `None` is a
561    /// manifest that sets no version, which Cargo reads as `0.0.0`.
562    ///
563    /// # Errors
564    /// Refuses a package whose inherited version the nearest workspace manifest
565    /// does not supply, and an identity this workspace does not hold.
566    pub fn package_version(&self, id: PackageId) -> Result<Option<&str>, LoadError> {
567        match self.versions.get(id.index()) {
568            Some(DeclaredVersion::Value(version)) => Ok(Some(version)),
569            Some(DeclaredVersion::Unset) => Ok(None),
570            Some(DeclaredVersion::Unresolved) | None => {
571                let manifest = self
572                    .packages
573                    .get(id.index())
574                    .map_or_else(RelPath::root, |package| package.manifest.clone());
575                Err(manifest_error(
576                    &manifest,
577                    "package.version",
578                    "the package inherits its version and the nearest workspace manifest supplies none".to_owned(),
579                ))
580            }
581        }
582    }
583
584    /// Package identities in the manifest order of [`Workspace::packages`].
585    pub fn package_ids(&self) -> impl Iterator<Item = PackageId> {
586        (0..self.packages.len()).map(PackageId)
587    }
588
589    /// The targets, grouped by package: library, binaries, tests, benches,
590    /// examples and build script of each.
591    pub fn targets(&self) -> impl Iterator<Item = &Target> {
592        self.targets.iter()
593    }
594
595    /// A target by id.
596    #[must_use]
597    pub fn target(&self, id: TargetId) -> Option<&Target> {
598        self.targets.get(id.index())
599    }
600
601    /// The target's declared package edition, including workspace inheritance
602    /// and Cargo's 2015 default when the manifest omits it.
603    ///
604    /// This observes the loaded manifest, not a compiler or standard library.
605    /// IDs are load-local, as with [`Self::target`]. Missing target slots return
606    /// `None`. A manifest can declare a year
607    /// this consumer does not support; the consumer must validate its profile.
608    #[must_use]
609    pub fn target_edition(&self, id: TargetId) -> Option<u16> {
610        self.index.target_editions.get(id.index()).copied()
611    }
612
613    /// The ids of the targets, in the order of [`Workspace::targets`].
614    pub fn target_ids(&self) -> impl Iterator<Item = TargetId> {
615        (0..self.targets.len()).map(TargetId)
616    }
617
618    /// Borrow the indexed dependencies in a library's non-test extern prelude.
619    ///
620    /// An ordinary structural load exposes its normal dependency edges.
621    /// A configured load uses its admitted target context. A package can appear
622    /// under multiple aliases. An unknown or nonlibrary target returns `None`.
623    pub fn library_prelude_dependencies(
624        &self,
625        library: TargetId,
626    ) -> Option<impl Iterator<Item = PackageId> + '_> {
627        self.target(library)
628            .filter(|target| target.kind == TargetKind::Lib)?;
629        Some(
630            self.index.preludes[library.index()]
631                .values()
632                .flat_map(|name| name.roots(false))
633                .map(move |module| {
634                    self.targets[self.index.modules[module].target.index()].package_id
635                }),
636        )
637    }
638
639    /// Every source file, once, sorted by path.
640    pub fn files(&self) -> impl Iterator<Item = &SourceFile> {
641        self.files.values()
642    }
643
644    /// One source file.
645    #[must_use]
646    pub fn file(&self, path: &RelPath) -> Option<&SourceFile> {
647        self.files.get(path)
648    }
649
650    /// The exact text that was parsed for `path`.
651    #[must_use]
652    pub fn source(&self, path: &RelPath) -> Option<&str> {
653        self.files.get(path).map(|file| file.text.as_str())
654    }
655
656    /// Every item, sorted by path, then name space, file and position.
657    pub fn items(&self) -> impl Iterator<Item = &Item> {
658        self.index
659            .order
660            .iter()
661            .map(|id| &self.index.items[id.index()])
662    }
663
664    /// Unexpanded module-level macro occurrences in the selected syntax, sorted
665    /// by file, byte position, module and target. These define no index names.
666    #[must_use]
667    pub fn unexpanded(&self) -> &[crate::Unexpanded] {
668        &self.index.unexpanded
669    }
670
671    /// Opaque declarations under an outer `cfg(any())`, sorted by file,
672    /// byte position, module and target. These observations bind no names.
673    #[must_use]
674    pub fn disabled_syntax(&self) -> &[crate::DisabledSyntax] {
675        &self.index.disabled_syntax
676    }
677
678    /// The items at `prefix` or below it, in the order of [`Workspace::items`].
679    /// The prefix matches whole path segments: `demo::a` selects `demo::a` and
680    /// `demo::a::b`, not `demo::ab`. An empty prefix selects every item.
681    pub fn items_under<'a>(&'a self, prefix: &'a str) -> impl Iterator<Item = &'a Item> {
682        let order = &self.index.order;
683        let start = order.partition_point(|id| self.index.items[id.index()].path.as_str() < prefix);
684        order[start..]
685            .iter()
686            .map(|id| &self.index.items[id.index()])
687            .take_while(move |item| item.path.starts_with(prefix))
688            .filter(move |item| {
689                prefix.is_empty()
690                    || item
691                        .path
692                        .strip_prefix(prefix)
693                        .is_some_and(|rest| rest.is_empty() || rest.starts_with("::"))
694            })
695    }
696
697    /// One item by id.
698    #[must_use]
699    pub fn item(&self, id: ItemId) -> Option<&Item> {
700        self.index.items.get(id.index())
701    }
702
703    /// A conservative platform guard for one indexed item's retained source site.
704    ///
705    /// This observes source facts without filtering the index or assuming the
706    /// compiler's host. Unsupported owner/path ancestry remains unknown.
707    ///
708    /// # Errors
709    /// Returns a typed load error for an invalid item, inconsistent retained
710    /// source context, malformed cfg metadata, or the original storage/work limit.
711    pub fn test_platform_guard(
712        &self,
713        id: ItemId,
714    ) -> Result<crate::TestPlatformGuard<'_>, LoadError> {
715        crate::platform::guard(self, id, &self.index, &self.options, self.usage.item_bytes)
716    }
717
718    /// The items defined in `file`, ordered by the byte offset of their span.
719    pub fn items_in<'a>(&'a self, file: &RelPath) -> impl Iterator<Item = &'a Item> {
720        self.index
721            .by_file
722            .get(file)
723            .into_iter()
724            .flatten()
725            .map(|id| &self.index.items[id.index()])
726    }
727
728    /// The number of indexed items in `file`, without scanning their spans.
729    ///
730    /// Includes crate roots and every distinct source reach, as
731    /// [`Workspace::items_in`] does. An unindexed file has zero items.
732    #[must_use]
733    pub fn item_count_in(&self, file: &RelPath) -> usize {
734        self.index.by_file.get(file).map_or(0, Vec::len)
735    }
736
737    /// The innermost items of `file` whose span holds the byte `offset`. More
738    /// than one item is returned when the file is reached under several paths.
739    #[must_use]
740    pub fn item_at(&self, file: &RelPath, offset: usize) -> Vec<&Item> {
741        let holding: Vec<&Item> = self
742            .items_in(file)
743            .filter(|item| item.span.start_byte <= offset && offset < item.span.end_byte)
744            .collect();
745        let smallest = holding
746            .iter()
747            .map(|item| item.span.end_byte - item.span.start_byte)
748            .min();
749        holding
750            .into_iter()
751            .filter(|item| Some(item.span.end_byte - item.span.start_byte) == smallest)
752            .collect()
753    }
754
755    /// True when the item is in a shipping target and is not test code.
756    #[must_use]
757    pub fn is_shipping(&self, item: &Item) -> bool {
758        item.test == TestRole::None
759            && self
760                .targets
761                .get(item.target.index())
762                .is_some_and(|target| target.shipping)
763    }
764
765    /// Resolve a canonical path such as `demo::inner::go`, trying the type,
766    /// value and macro name spaces in that order.
767    ///
768    /// # Errors
769    ///
770    /// Returns [`ResolveError::NotFound`] when the workspace defines nothing at
771    /// the path (a dependency item and a macro-generated item both end here),
772    /// [`ResolveError::UnresolvedSelf`] when it defines nothing there and the
773    /// path goes through the self type of an inherent impl that the index
774    /// cannot see, [`ResolveError::Ambiguous`] when it names several symbols
775    /// or starts with a crate path that targets of several packages share
776    /// (see [`Workspace::resolve_in_package`]), [`ResolveError::Cyclic`] when
777    /// the imports on the way form a cycle,
778    /// [`ResolveError::UnresolvedGlob`] when a lookup on the way reads a glob
779    /// whose path names nothing past its first segment, and
780    /// [`ResolveError::Invalid`] when the text is not a path, a path keyword
781    /// among its segments included.
782    pub fn resolve(&self, path: &str) -> Result<Resolution, ResolveError> {
783        self.index
784            .resolve(path, None, None, &Meter::query(&self.options))
785    }
786
787    /// Resolve a canonical path in one name space.
788    ///
789    /// # Errors
790    ///
791    /// As [`Workspace::resolve`].
792    pub fn resolve_in(&self, path: &str, namespace: Namespace) -> Result<Resolution, ResolveError> {
793        self.index
794            .resolve(path, Some(namespace), None, &Meter::query(&self.options))
795    }
796
797    /// Resolve once while observing the native indexed targets of missing routes.
798    ///
799    /// Private aliases participate. Missing dependency items and generated items
800    /// remain unresolved; their attempted routes never establish a definition or
801    /// provider identity. Ordinary [`Self::resolve_in`] behavior is unchanged.
802    /// Observation storage and work share this lookup's original query budgets.
803    ///
804    /// # Errors
805    /// Preserves ambiguity, cycles, broken globs, invalid paths and resource
806    /// refusals. Only ordinary not-found results become observations.
807    pub fn resolve_in_observed(
808        &self,
809        path: &str,
810        namespace: Namespace,
811    ) -> Result<ResolutionAttempt, ResolveError> {
812        self.index
813            .resolve_observed(path, namespace, &Meter::query(&self.options))
814    }
815
816    /// Resolve a canonical path among the crates of one package, named by its
817    /// Cargo package name: the path starts with the crate path of one of the
818    /// package's targets. Two packages whose libraries share a crate name
819    /// are told apart this way.
820    ///
821    /// # Errors
822    ///
823    /// Returns [`ResolveError::UnknownPackage`] when no package of the
824    /// workspace has that name, [`ResolveError::AmbiguousPackageName`] when
825    /// several have it, and otherwise as [`Workspace::resolve`].
826    pub fn resolve_in_package(
827        &self,
828        package: &str,
829        path: &str,
830    ) -> Result<Resolution, ResolveError> {
831        let matching = try_equal_range_by(&self.package_names, |id| {
832            Ok::<_, Infallible>(self.packages[id.index()].name.as_str().cmp(package))
833        })
834        .unwrap_or_else(|never| match never {});
835        if matching.is_empty() {
836            return Err(ResolveError::UnknownPackage(package.to_owned()));
837        }
838        if matching.len() > 1 {
839            return Err(ResolveError::AmbiguousPackageName(package.to_owned()));
840        }
841        self.resolve_in_package_id(self.package_names[matching.start], path)
842    }
843
844    /// Resolve a canonical path among the crates of an exact load-local package.
845    ///
846    /// Displayed crate and symbol paths are unchanged; the identity chooses
847    /// which package's roots the ordinary resolver walks.
848    ///
849    /// # Errors
850    ///
851    /// Returns [`ResolveError::UnknownPackageId`] for an identity absent from
852    /// this workspace, and otherwise as [`Workspace::resolve`].
853    pub fn resolve_in_package_id(
854        &self,
855        package: PackageId,
856        path: &str,
857    ) -> Result<Resolution, ResolveError> {
858        if self.package(package).is_none() {
859            return Err(ResolveError::UnknownPackageId(package));
860        }
861        self.index
862            .resolve(path, None, Some(package), &Meter::query(&self.options))
863    }
864
865    /// Resolve the path of a `use` declaration written in the module `module`
866    /// (a canonical module path such as `demo::inner`), trying the type, value
867    /// and macro name spaces in that order. The reading module is the viewer:
868    /// the path starts as code of that module starts it (`crate`, `self`,
869    /// `super`, a name the module binds, or a crate of the extern prelude)
870    /// and each segment counts only the bindings the module can access, as
871    /// rustc settles an import.
872    ///
873    /// # Errors
874    ///
875    /// Returns [`ResolveError::UnknownModule`] when `module` is not a module
876    /// of the workspace, and otherwise as [`Workspace::resolve`]: a path
877    /// that names nothing the module can access is
878    /// [`ResolveError::NotFound`], and one that names several symbols is
879    /// [`ResolveError::Ambiguous`]. So is a `module` that starts with a
880    /// crate path that targets of several packages share (two libraries with
881    /// one crate name), as for [`Workspace::resolve`]: the answer lists the
882    /// crate roots of those packages, and a module of any other crate reads
883    /// as before. Nothing names the package here, so such a module cannot be
884    /// read from.
885    ///
886    /// # Examples
887    ///
888    /// ```
889    /// use raf_source::{MemoryTree, Workspace};
890    ///
891    /// let tree: MemoryTree = [
892    ///     ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
893    ///     ("src/lib.rs", "mod a { pub fn go() {} fn hidden() {} }\nmod b {}\n"),
894    /// ]
895    /// .into_iter()
896    /// .collect();
897    /// let ws = Workspace::load(&tree, &["."])?;
898    /// assert_eq!(ws.resolve_from("demo::b", "crate::a::go")?.path, "demo::a::go");
899    /// assert!(ws.resolve_from("demo::b", "crate::a::hidden").is_err());
900    /// # Ok::<(), Box<dyn std::error::Error>>(())
901    /// ```
902    pub fn resolve_from(&self, module: &str, path: &str) -> Result<Resolution, ResolveError> {
903        self.index
904            .resolve_from(module, path, None, None, &Meter::query(&self.options))
905    }
906
907    /// [`Workspace::resolve_from`] in one name space.
908    ///
909    /// # Errors
910    ///
911    /// As [`Workspace::resolve_from`].
912    pub fn resolve_from_in(
913        &self,
914        module: &str,
915        path: &str,
916        namespace: Namespace,
917    ) -> Result<Resolution, ResolveError> {
918        self.index.resolve_from(
919            module,
920            path,
921            Some(namespace),
922            None,
923            &Meter::query(&self.options),
924        )
925    }
926
927    /// Resolve a relative import path from a module of an exact load-local package.
928    ///
929    /// The package selects the reading module's crate roots, even when another
930    /// package has the same displayed crate and module paths. Resolution then
931    /// uses the ordinary import traversal and the reading module's visibility.
932    /// The result can name a dependency of that package; it is not restricted
933    /// to definitions in the reading package.
934    ///
935    /// # Errors
936    ///
937    /// Returns [`ResolveError::UnknownPackageId`] for an identity absent from
938    /// this workspace, [`ResolveError::UnknownModule`] when the module is absent
939    /// from the selected package, and otherwise as [`Self::resolve_from`].
940    pub fn resolve_from_package_id(
941        &self,
942        package: PackageId,
943        module: &str,
944        path: &str,
945    ) -> Result<Resolution, ResolveError> {
946        if self.package(package).is_none() {
947            return Err(ResolveError::UnknownPackageId(package));
948        }
949        self.index.resolve_from(
950            module,
951            path,
952            None,
953            Some(package),
954            &Meter::query(&self.options),
955        )
956    }
957
958    /// [`Self::resolve_from_package_id`] in one name space.
959    ///
960    /// # Errors
961    ///
962    /// As [`Self::resolve_from_package_id`].
963    pub fn resolve_from_package_id_in(
964        &self,
965        package: PackageId,
966        module: &str,
967        path: &str,
968        namespace: Namespace,
969    ) -> Result<Resolution, ResolveError> {
970        if self.package(package).is_none() {
971            return Err(ResolveError::UnknownPackageId(package));
972        }
973        self.index.resolve_from(
974            module,
975            path,
976            Some(namespace),
977            Some(package),
978            &Meter::query(&self.options),
979        )
980    }
981
982    /// Resolve a definition only through a declared, cfg-filtered locked load.
983    ///
984    /// Every returned definition belongs to an actual admitted package with its
985    /// retained compilation context. This does not expand macros, observe a
986    /// Cargo invocation or decide preferred-provider policy.
987    /// Filtering selects modeled declaration headers, not function-body
988    /// expressions/statements, fields or enum variants; source bytes are intact.
989    ///
990    /// # Errors
991    /// Refuses an absent package, structural-only context or unconfigured site;
992    /// missing/inactive names and ordinary resolver failures remain hard errors.
993    pub fn resolve_active_from_package_id_in(
994        &self,
995        package: PackageId,
996        module: &str,
997        path: &str,
998        namespace: Namespace,
999    ) -> Result<Resolution, ResolveError> {
1000        if self.package(package).is_none() {
1001            return Err(ResolveError::UnknownPackageId(package));
1002        }
1003        if self
1004            .locked_binding(package)
1005            .is_none_or(|binding| binding.configurations().is_empty())
1006        {
1007            return Err(ResolveError::UnconfiguredPackage(package));
1008        }
1009        let resolved = self.resolve_from_package_id_in(package, module, path, namespace)?;
1010        if resolved.sites.is_empty() {
1011            return Err(ResolveError::NotFound(path.to_owned()));
1012        }
1013        for site in &resolved.sites {
1014            let valid = self
1015                .item(*site)
1016                .and_then(|item| self.target(item.target))
1017                .and_then(|target| {
1018                    self.locked_binding(target.package_id)?
1019                        .configuration_for(target.kind, &target.name)
1020                })
1021                .is_some();
1022            if !valid {
1023                return Err(ResolveError::UnconfiguredDefinition(*site));
1024            }
1025        }
1026        Ok(resolved)
1027    }
1028
1029    /// The inherent impl blocks whose self type names no struct, enum or
1030    /// union the index can see, once for each module path their file is
1031    /// reached under, sorted by path, file and position. Their members are
1032    /// items marked [`SelfType::Unresolved`](crate::SelfType::Unresolved), so a
1033    /// consumer that needs every impl placed can refuse them.
1034    pub fn unresolved_impls(&self) -> impl Iterator<Item = &UnresolvedImpl> {
1035        self.index.unresolved.iter()
1036    }
1037
1038    /// Every `impl` block of every target, inherent and of a trait alike, once
1039    /// for each module path its file is reached under, in file order: sorted
1040    /// by file, the byte offset where the block starts, module path and
1041    /// target. A block's [`ImplId`] is its place in this order. Each carries
1042    /// its span from its first attribute or the `impl` keyword to its closing
1043    /// brace, the module that holds it, its written self type and trait, the
1044    /// key of its self type (the struct, enum or union the self type path
1045    /// names from that module, none when it names nothing of the workspace or
1046    /// a type the index cannot place) and its members; a negative impl keeps
1047    /// its `!` in its trait path. An impl block inside a
1048    /// function body or any other block expression, such as
1049    /// `const _: () = { .. };`, is not an item of a module and is not listed,
1050    /// nor is one that a macro invocation would generate.
1051    ///
1052    /// ```
1053    /// use raf_source::{MemoryTree, Workspace};
1054    ///
1055    /// let tree = MemoryTree::from([
1056    ///     ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"),
1057    ///     ("src/lib.rs", "pub struct S;\nimpl S { pub fn new() {} }\nimpl Clone for S { fn clone(&self) -> S { S } }\n"),
1058    /// ]);
1059    /// let ws = Workspace::load(&tree, &["."])?;
1060    /// let blocks: Vec<_> = ws.impls().collect();
1061    /// assert_eq!(blocks.len(), 2);
1062    /// assert_eq!((blocks[0].line, blocks[1].line), (2, 3));
1063    /// let s = ws.resolve("demo::S")?.sites[0];
1064    /// assert!(blocks.iter().all(|block| block.self_items == [s]));
1065    /// assert_eq!(blocks[1].trait_path.as_deref(), Some("Clone"));
1066    /// # Ok::<(), Box<dyn std::error::Error>>(())
1067    /// ```
1068    pub fn impls(&self) -> impl Iterator<Item = &ImplBlock> {
1069        self.index.impl_blocks.iter()
1070    }
1071
1072    /// The impl blocks of this file in source order, once per reading context.
1073    #[must_use]
1074    pub fn impls_in(&self, file: &RelPath) -> &[ImplBlock] {
1075        let blocks = &self.index.impl_blocks;
1076        let start = blocks.partition_point(|block| &block.file < file);
1077        let end = blocks.partition_point(|block| &block.file <= file);
1078        &blocks[start..end]
1079    }
1080
1081    /// One impl block by id.
1082    #[must_use]
1083    pub fn impl_block(&self, id: ImplId) -> Option<&ImplBlock> {
1084        self.index.impl_blocks.get(id.index())
1085    }
1086
1087    /// The items and impl blocks of every target that `roots` reach over
1088    /// three edges: contains (a struct, enum or union to its methods and
1089    /// associated items, a trait to its members, a module to its items and
1090    /// impl blocks, a crate root to nothing), impl-of (a struct, enum or
1091    /// union to the impl blocks whose self type it is, and a block to its
1092    /// members) and references (an item or a block to each item that a path
1093    /// in its own tokens names from its module). A module is opened only
1094    /// when it is a root or is reached by contains from one that is opened:
1095    /// a module that a path names reaches nothing below it.
1096    ///
1097    /// A path is an `Ident (:: Ident)*` run of the tokens that no `.`
1098    /// precedes, read as code of the module reads it: each proper prefix in
1099    /// the type name space and the whole run in each name space, each walked
1100    /// as the resolver walks a path, as code reads it where
1101    /// [`Workspace::resolve_from_in`] reads a `use` path (without the reading
1102    /// module's visibility, and in edition 2015 from the module), naming the
1103    /// sites it reaches when they are one symbol; a path that names nothing
1104    /// of the workspace (a local, a generic, an item of a dependency or one
1105    /// that a macro generates) reaches nothing. Keywords are those of the
1106    /// edition of the package of the reached item. A path that `Self` starts
1107    /// in an impl block or a trait, and a method called on `self` there,
1108    /// name the members of that name of the block's self type, of the block
1109    /// and of its trait, or of the trait. The own tokens of an item are those
1110    /// of its span outside the items and blocks below it; a module's are its
1111    /// declaration before its body. The tokens of test code are read as test
1112    /// code, which names the dev-dependencies too.
1113    ///
1114    /// Each reached node is listed once, with the edge it was first reached
1115    /// by, breadth first from the roots in the order of their nodes, so the
1116    /// answer does not depend on the order of `roots`. Each file is lexed
1117    /// once per package edition, and each path is resolved at most once for
1118    /// each module it is read from. What the walk holds is charged to the
1119    /// item-bytes budget of the load, on from what the load holds.
1120    ///
1121    /// ```
1122    /// use raf_source::{MemoryTree, Node, Workspace};
1123    ///
1124    /// let tree = MemoryTree::from([
1125    ///     ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
1126    ///     ("src/lib.rs", "pub fn run() { helper() }\nfn helper() {}\nfn unused() {}\n"),
1127    /// ]);
1128    /// let ws = Workspace::load(&tree, &["."])?;
1129    /// let site = |path: &str| ws.resolve(path).map(|found| found.sites[0]);
1130    /// let reached = ws.reachable(&[Node::Item(site("demo::run")?)])?;
1131    /// assert!(reached.contains(Node::Item(site("demo::helper")?)));
1132    /// assert!(!reached.contains(Node::Item(site("demo::unused")?)));
1133    /// # Ok::<(), Box<dyn std::error::Error>>(())
1134    /// ```
1135    ///
1136    /// # Errors
1137    ///
1138    /// Returns [`ReachError::UnknownItem`] or [`ReachError::UnknownImpl`] for
1139    /// a root past the items or the impl blocks of this workspace (an id is
1140    /// a place, so an id of another workspace that is in range reads as the
1141    /// node of this one at that place), [`ReachError::Source`] when a file
1142    /// does not lex, which a file the load parsed does not do, or the thread
1143    /// that lexes it cannot start, and [`ReachError::Budget`] when what the
1144    /// walk holds passes the item-bytes budget.
1145    pub fn reachable(&self, roots: &[Node]) -> Result<Reachability, ReachError> {
1146        reach::reachable(
1147            &self.index,
1148            &self.files,
1149            (&self.options, self.usage.item_bytes),
1150            roots,
1151        )
1152    }
1153
1154    /// The items that share a source item, grouped by its identity: the file
1155    /// and the byte offset where its span starts. A source item that several
1156    /// module paths reach appears as several items, and the group holds them
1157    /// all, sorted by path. Groups come in the order of file and offset. Crate
1158    /// roots represent whole files and are excluded from these source groups.
1159    pub fn items_by_source(&self) -> impl Iterator<Item = (&RelPath, usize, &[ItemId])> {
1160        self.index
1161            .by_source
1162            .iter()
1163            .map(|((file, offset), ids)| (file, *offset, ids.as_slice()))
1164    }
1165
1166    /// The items that share a source item with `item`, itself included. A crate
1167    /// root represents a whole file rather than a source item and returns an
1168    /// empty slice, including when its first written item also starts at byte 0.
1169    #[must_use]
1170    pub fn same_source(&self, item: &Item) -> &[ItemId] {
1171        if self.index.is_root(item.id) {
1172            return &[];
1173        }
1174        self.index
1175            .by_source
1176            .get(&(item.file.clone(), item.span.start_byte))
1177            .map_or(&[][..], Vec::as_slice)
1178    }
1179
1180    /// The public surface of a library or binary target, with the items that
1181    /// `#[doc(hidden)]` hides left out: see [`Workspace::exported_items_with`].
1182    ///
1183    /// ```rust
1184    /// use raf_source::{MemoryTree, Workspace};
1185    ///
1186    /// let tree = MemoryTree::from([
1187    ///     ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"),
1188    ///     ("src/lib.rs", "mod inner;\npub use inner::go as run;\npub(crate) fn helper() {}\n"),
1189    ///     ("src/inner.rs", "pub fn go() {}\npub fn unused() {}\n"),
1190    /// ]);
1191    /// let ws = Workspace::load(&tree, &["."])?;
1192    /// let lib = ws.target_ids().next().expect("the library");
1193    /// let exports = ws.exported_items(lib)?;
1194    /// let paths: Vec<(&str, &str)> = exports
1195    ///     .items
1196    ///     .iter()
1197    ///     .map(|export| (export.path.as_str(), ws.item(export.item).map_or("", |item| item.path.as_str())))
1198    ///     .collect();
1199    /// assert_eq!(paths, [("demo::run", "demo::inner::go")]);
1200    /// # Ok::<(), Box<dyn std::error::Error>>(())
1201    /// ```
1202    ///
1203    /// # Errors
1204    ///
1205    /// As [`Workspace::exported_items_with`].
1206    pub fn exported_items(&self, target: TargetId) -> Result<Exports, ExportError> {
1207        self.exported_items_with(target, &ExportOptions::default())
1208    }
1209
1210    /// The public surface of a library or binary target: the items another
1211    /// crate can name through its crate root, each under the path it is
1212    /// named by, and the public re-exports that name nothing the target
1213    /// defines.
1214    ///
1215    /// An item is exported when a chain of `pub` declarations reaches it from
1216    /// the crate root: `pub` modules, and `pub use` re-exports, named or glob,
1217    /// renamed or not, through modules of any visibility. A `pub` item of a
1218    /// private module is exported only through such a re-export, and a
1219    /// `pub(crate)`, `pub(super)`, `pub(in path)` or private item never is,
1220    /// nor is one that a re-export that is not `pub` carries on the way.
1221    /// Test code is never exported. The members of an exported type or trait
1222    /// are listed under its path: each member of a trait, and each `pub`
1223    /// member of an inherent impl of a type; the members of trait impls are
1224    /// not. A binary's surface is read the same way from its crate root; no
1225    /// other crate can name it. A re-export of another crate, of an enum
1226    /// variant or of a path the index cannot follow is a
1227    /// [`Reexport`](crate::Reexport) and not an item, also where a `pub` glob
1228    /// carries it from a module it reaches.
1229    ///
1230    /// # Errors
1231    ///
1232    /// Returns [`ExportError::NotLibraryOrBinary`] for a target id that names
1233    /// no library or binary of the workspace, [`ExportError::Resolve`] when a
1234    /// public name is ambiguous, goes through a cycle of imports or reads a
1235    /// glob whose path names nothing in the workspace, and
1236    /// [`ExportError::Budget`] when what the surface holds passes the
1237    /// item-bytes budget left after the load, and
1238    /// [`ExportError::CarryBudget`], naming the re-export, when the work of
1239    /// deciding whether the public globs carry a re-export passes it.
1240    pub fn exported_items_with(
1241        &self,
1242        target: TargetId,
1243        options: &ExportOptions,
1244    ) -> Result<Exports, ExportError> {
1245        self.exports_after(
1246            target,
1247            options,
1248            Usage {
1249                item_bytes: self.usage.item_bytes,
1250                ..Usage::default()
1251            },
1252        )
1253        .map(|(exports, _)| exports)
1254    }
1255
1256    pub(crate) fn exports_after(
1257        &self,
1258        target: TargetId,
1259        options: &ExportOptions,
1260        retained: Usage,
1261    ) -> Result<(Exports, Usage), ExportError> {
1262        let Some(found) = self
1263            .targets
1264            .get(target.index())
1265            .filter(|found| matches!(found.kind, TargetKind::Lib | TargetKind::Bin))
1266        else {
1267            return Err(ExportError::NotLibraryOrBinary(target));
1268        };
1269        let meter = Meter::resume_query(&self.options, retained);
1270        // The modules of the target whose own file has `#![doc(hidden)]`.
1271        let hidden_files: BTreeSet<&str> = self
1272            .files
1273            .values()
1274            .filter(|file| file.facts.doc_hidden)
1275            .flat_map(|file| &file.reached)
1276            .filter(|reach| reach.target == target)
1277            .map(|reach| reach.module_path.as_str())
1278            .collect();
1279        let exports = Surface::new(
1280            &self.index,
1281            target,
1282            &found.crate_path,
1283            options,
1284            &meter,
1285            &hidden_files,
1286        )
1287        .list()?;
1288        Ok((exports, meter.usage()))
1289    }
1290
1291    /// The test functions: the data a caller needs to run one with
1292    /// `cargo test -p <package> --test <target> <name>`, `--bin <target>` or
1293    /// `--lib`.
1294    ///
1295    /// # Errors
1296    ///
1297    /// Returns a [`LoadError`] of kind `Internal` if a test function's path
1298    /// does not start with the crate path of its target, which the index
1299    /// guarantees it does.
1300    pub fn test_fns(&self) -> Result<Vec<TestFn>, LoadError> {
1301        self.items()
1302            .filter(|item| item.test == TestRole::TestFn)
1303            // The test harness collects no test inside a block, and the path
1304            // of one names no filter that cargo accepts.
1305            .filter(|item| !item.path.contains("::{"))
1306            .map(|item| test_fn_of(item, &self.targets))
1307            .collect()
1308    }
1309}
1310
1311/// What is computed once per workspace manifest during a load.
1312#[derive(Default)]
1313struct Caches {
1314    workspaces: BTreeMap<RelPath, WorkspaceOf>,
1315    members: BTreeMap<RelPath, BTreeSet<RelPath>>,
1316}
1317
1318/// Separate selected dependency bindings from structural reference observations.
1319fn binding_sets(
1320    binding: Option<&locked::BindingLoad<'_>>,
1321    bindings: Vec<LockedBinding>,
1322) -> (Vec<LockedBinding>, Vec<LockedBinding>) {
1323    if binding.is_some_and(locked::BindingLoad::structural) {
1324        (Vec::new(), bindings)
1325    } else {
1326        (bindings, Vec::new())
1327    }
1328}
1329
1330/// Build the name selector without retaining another copy of package names.
1331fn package_name_index(packages: &[Package], meter: &Meter) -> Result<Vec<PackageId>, LoadError> {
1332    package_index_by(packages.len(), meter, |left, right| {
1333        packages[left.index()]
1334            .name
1335            .cmp(&packages[right.index()].name)
1336    })
1337}
1338
1339fn package_directory_index(found: &[Found], meter: &Meter) -> Result<Vec<PackageId>, LoadError> {
1340    package_index_by(found.len(), meter, |left, right| {
1341        found[left.index()]
1342            .package
1343            .dir
1344            .cmp(&found[right.index()].package.dir)
1345    })
1346}
1347
1348/// Sort borrowed package keys through native admitted identity storage.
1349fn package_index_by(
1350    len: usize,
1351    meter: &Meter,
1352    compare: impl Fn(PackageId, PackageId) -> Ordering,
1353) -> Result<Vec<PackageId>, LoadError> {
1354    let file = RelPath::root();
1355    meter.items(size_of::<Vec<PackageId>>(), &file, None)?;
1356    let mut names = Vec::new();
1357    let mut admission = ItemAdmission::new(meter, &file);
1358    Memory::new(&mut admission)
1359        .reserve(&mut names, len)
1360        .map_err(|error| admission.error(error))?;
1361    for index in 0..len {
1362        names.push(PackageId(index));
1363    }
1364    try_sort_unstable_by(&mut names, |left, right| {
1365        Ok::<_, Infallible>(compare(*left, *right).then_with(|| left.cmp(right)))
1366    })
1367    .unwrap_or_else(|never| match never {});
1368    Ok(names)
1369}
1370
1371/// What reading a package's manifest needs: the tree, the meter of the load
1372/// and the directory of every package discovery found.
1373struct Reader<'a> {
1374    tree: &'a dyn Tree,
1375    meter: &'a Meter,
1376    dirs: &'a [PackageId],
1377    found: &'a [Found],
1378}
1379
1380impl Reader<'_> {
1381    fn install_edges(
1382        &self,
1383        binding: Option<&locked::BindingLoad<'_>>,
1384        dependencies: &[Vec<DependencyDeclaration>],
1385        locked: &[LockedBinding],
1386        targets: &[Target],
1387        infos: &mut [PackageInfo],
1388    ) -> Result<(), LoadError> {
1389        if let Some(binding) = binding {
1390            locked::install_edges(binding, self, dependencies, locked, targets, infos)?;
1391        }
1392        Ok(())
1393    }
1394}
1395
1396/// The version one package declares, as its load read it.
1397#[derive(Debug, Clone, PartialEq, Eq)]
1398enum DeclaredVersion {
1399    Value(String),
1400    Unset,
1401    Unresolved,
1402}
1403
1404/// The declared version of every discovered package, in discovery order.
1405fn declared_versions(
1406    reader: &Reader<'_>,
1407    found: &[Found],
1408    caches: &mut Caches,
1409) -> Result<Vec<DeclaredVersion>, LoadError> {
1410    let mut versions = Vec::new();
1411    let root = RelPath::root();
1412    let mut admission = ItemAdmission::new(reader.meter, &root);
1413    Memory::new(&mut admission)
1414        .reserve(&mut versions, found.len())
1415        .map_err(|error| admission.error(error))?;
1416    for entry in found {
1417        versions.push(declared_version(
1418            reader,
1419            &entry.package,
1420            &entry.declared,
1421            caches,
1422        )?);
1423    }
1424    Ok(versions)
1425}
1426
1427/// Read a package's declared version under the load's item allowance.
1428fn declared_version(
1429    reader: &Reader<'_>,
1430    package: &Package,
1431    declared: &PackageDecl,
1432    caches: &mut Caches,
1433) -> Result<DeclaredVersion, LoadError> {
1434    let version = match &declared.version {
1435        VersionDecl::Explicit(version) => version.clone(),
1436        VersionDecl::Unset => return Ok(DeclaredVersion::Unset),
1437        VersionDecl::Inherited => match workspace_of(reader, &package.dir, caches)? {
1438            WorkspaceOf::Member {
1439                version: Some(version),
1440                ..
1441            } => version.as_str().to_owned(),
1442            _ => return Ok(DeclaredVersion::Unresolved),
1443        },
1444    };
1445    reader.meter.items(
1446        version.len().saturating_add(size_of::<DeclaredVersion>()),
1447        &package.manifest,
1448        None,
1449    )?;
1450    Ok(DeclaredVersion::Value(version))
1451}
1452
1453/// The nearest workspace manifest above a package, as far as the package can
1454/// inherit from it.
1455#[derive(Debug, Clone, PartialEq, Eq)]
1456enum WorkspaceOf {
1457    /// The package is a member of the workspace in `dir`.
1458    Member {
1459        dir: RelPath,
1460        /// `[workspace.package] edition`, if it is set.
1461        edition: Option<u16>,
1462        version: Option<Rc<String>>,
1463        /// `[workspace.dependencies]`.
1464        dependencies: Rc<BTreeMap<String, WorkspaceDependency>>,
1465    },
1466    /// The nearest workspace manifest does not have the package as a member.
1467    NotMember(RelPath),
1468    /// There is no workspace manifest above the package.
1469    Absent,
1470}
1471
1472fn manifest_error(path: &RelPath, key: &str, message: String) -> LoadError {
1473    LoadError::new(
1474        path,
1475        None,
1476        LoadErrorKind::Manifest {
1477            message,
1478            source: None,
1479        },
1480    )
1481    .reached_by(&Origin::ManifestKey {
1482        key: key.to_owned(),
1483    })
1484}
1485
1486/// The workspace that a package directory belongs to: the nearest manifest at
1487/// or above it that has a `[workspace]` table, found the way cargo finds it,
1488/// by walking up through the ancestors within the tree. A missing ancestor
1489/// manifest is skipped; one that cannot be read or parsed is an error. The
1490/// manifest is not added to the packages that discovery found.
1491fn workspace_of(
1492    reader: &Reader<'_>,
1493    dir: &RelPath,
1494    caches: &mut Caches,
1495) -> Result<WorkspaceOf, LoadError> {
1496    let (tree, meter) = (reader.tree, reader.meter);
1497    if let Some(known) = caches.workspaces.get(dir) {
1498        return Ok(known.clone());
1499    }
1500    let origin = Origin::Discovery;
1501    let mut at = Some(dir.clone());
1502    let mut found = WorkspaceOf::Absent;
1503    while let Some(current) = at {
1504        let path = current
1505            .join("Cargo.toml")
1506            .map_err(|error| LoadError::tree(&current, None, &origin, error.into()))?;
1507        let present = tree
1508            .entry(&path)
1509            .map_err(|error| LoadError::tree(&path, None, &origin, error))?;
1510        if present.is_some() {
1511            let text = tree
1512                .read(&path, meter.options().max_file_bytes)
1513                .map_err(|error| LoadError::tree(&path, None, &origin, error))?;
1514            meter
1515                .read(&path, &text)
1516                .map_err(|error| error.reached_by(&origin))?;
1517            let parsed = manifest::parse(&text).map_err(|problem| {
1518                let origin = problem
1519                    .key
1520                    .map_or(Origin::Discovery, |key| Origin::ManifestKey { key });
1521                LoadError::new(
1522                    &path,
1523                    None,
1524                    LoadErrorKind::Manifest {
1525                        message: problem.message,
1526                        source: problem.source,
1527                    },
1528                )
1529                .reached_by(&origin)
1530            })?;
1531            if parsed.has_workspace {
1532                let set = match caches.members.entry(current.clone()) {
1533                    std::collections::btree_map::Entry::Occupied(known) => known.into_mut(),
1534                    std::collections::btree_map::Entry::Vacant(slot) => {
1535                        slot.insert(members(tree, meter, &current, &path, &parsed)?)
1536                    }
1537                };
1538                found = if set.contains(dir) {
1539                    let version = parsed
1540                        .workspace_version
1541                        .map(|version| {
1542                            meter.items(
1543                                version
1544                                    .len()
1545                                    .saturating_add(size_of::<String>())
1546                                    .saturating_add(2 * size_of::<usize>()),
1547                                &path,
1548                                None,
1549                            )?;
1550                            Ok::<_, LoadError>(Rc::new(version))
1551                        })
1552                        .transpose()?;
1553                    WorkspaceOf::Member {
1554                        dir: current,
1555                        edition: parsed.workspace_edition,
1556                        version,
1557                        dependencies: Rc::new(parsed.workspace_dependencies),
1558                    }
1559                } else {
1560                    WorkspaceOf::NotMember(path)
1561                };
1562                break;
1563            }
1564        }
1565        at = current.parent();
1566    }
1567    caches.workspaces.insert(dir.clone(), found.clone());
1568    Ok(found)
1569}
1570
1571/// What the index needs to know about a package's manifest.
1572///
1573/// # Errors
1574///
1575/// Returns a manifest error naming `package.edition` when the package inherits
1576/// its edition and the nearest workspace manifest above it does not have the
1577/// package as a member or does not set an edition, which cargo rejects as well,
1578/// and one naming a dependency whose `path` cannot be a path here.
1579fn package_info(
1580    reader: &Reader<'_>,
1581    package: &Package,
1582    declared: &PackageDecl,
1583    manifest: &Manifest,
1584    caches: &mut Caches,
1585) -> Result<PackageInfo, LoadError> {
1586    let edition = match &declared.edition {
1587        EditionDecl::Explicit(edition) => *edition,
1588        EditionDecl::Unset => 2015,
1589        EditionDecl::Inherited => match workspace_of(reader, &package.dir, caches)? {
1590            WorkspaceOf::Member {
1591                edition: Some(edition),
1592                ..
1593            } => edition,
1594            WorkspaceOf::Member { edition: None, .. } | WorkspaceOf::Absent => {
1595                return Err(manifest_error(
1596                        &package.manifest,
1597                        "package.edition",
1598                        "`edition.workspace = true` but no `[workspace.package] edition` is set by the nearest workspace manifest above the package"
1599                            .to_owned(),
1600                    ));
1601            }
1602            WorkspaceOf::NotMember(workspace) => {
1603                return Err(manifest_error(
1604                    &package.manifest,
1605                    "package.edition",
1606                    format!(
1607                        "`edition.workspace = true` but the package is not a member of the workspace {workspace} (it is not listed in `workspace.members`, or is excluded)"
1608                    ),
1609                ));
1610            }
1611        },
1612    };
1613    let mut dependencies = Vec::new();
1614    for dependency in &manifest.dependencies {
1615        dependencies.push(dependency_info(reader, package, dependency, caches)?);
1616    }
1617    Ok(PackageInfo {
1618        configured: false,
1619        edition,
1620        dependencies,
1621    })
1622}
1623
1624/// Retain package and inherited declarations under the original item allowance.
1625/// Membership and inherited keys have already been checked by `package_info`.
1626fn dependency_declarations(
1627    reader: &Reader<'_>,
1628    package: &Package,
1629    manifest: &Manifest,
1630    caches: &mut Caches,
1631) -> Result<Vec<DependencyDeclaration>, LoadError> {
1632    let mut declarations = Vec::new();
1633    let mut admission = ItemAdmission::new(reader.meter, &package.manifest);
1634    Memory::new(&mut admission)
1635        .reserve(&mut declarations, manifest.dependencies.len())
1636        .map_err(|error| admission.error(error))?;
1637    for dependency in &manifest.dependencies {
1638        let inherited = if dependency.declaration.specification.workspace {
1639            // package_info has already validated membership and the inherited key.
1640            let WorkspaceOf::Member {
1641                dir, dependencies, ..
1642            } = workspace_of(reader, &package.dir, caches)?
1643            else {
1644                return Err(internal(
1645                    &package.manifest,
1646                    None,
1647                    "validated workspace dependency lost its workspace".to_owned(),
1648                ));
1649            };
1650            let entry = dependencies.get(&dependency.name).ok_or_else(|| {
1651                internal(
1652                    &package.manifest,
1653                    None,
1654                    "validated workspace dependency lost its declaration".to_owned(),
1655                )
1656            })?;
1657            let manifest = dir
1658                .join("Cargo.toml")
1659                .map_err(|error| internal(&package.manifest, None, error.to_string()))?;
1660            reader.meter.items(
1661                manifest
1662                    .as_str()
1663                    .len()
1664                    .saturating_add(entry.specification.heap_bytes()),
1665                &package.manifest,
1666                None,
1667            )?;
1668            Some(InheritedDependency {
1669                manifest,
1670                specification: entry.specification.clone(),
1671            })
1672        } else {
1673            None
1674        };
1675        let original = &dependency.declaration;
1676        let bytes = original
1677            .key
1678            .len()
1679            .saturating_add(original.name.len())
1680            .saturating_add(original.condition.as_ref().map_or(0, String::len))
1681            .saturating_add(original.specification.heap_bytes());
1682        reader.meter.items(bytes, &package.manifest, None)?;
1683        let mut declaration = original.clone();
1684        declaration.inherited = inherited;
1685        declarations.push(declaration);
1686    }
1687    Ok(declarations)
1688}
1689
1690/// What the extern prelude needs, including an inherited path's workspace base.
1691/// Refuses invalid inheritance and malformed paths; external sources remain
1692/// unbound until a verified lock/source join supplies their package identity.
1693fn dependency_info(
1694    reader: &Reader<'_>,
1695    package: &Package,
1696    dependency: &Dependency,
1697    caches: &mut Caches,
1698) -> Result<DependencyInfo, LoadError> {
1699    let mut renamed = dependency.package.is_some();
1700    let place = match &dependency.path {
1701        None => None,
1702        Some(PathSource::Own(path)) => Some((package.dir.clone(), path.clone())),
1703        Some(PathSource::Workspace(name)) => match workspace_of(reader, &package.dir, caches)? {
1704            WorkspaceOf::Member {
1705                dir, dependencies, ..
1706            } => {
1707                let Some(entry) = dependencies.get(name) else {
1708                    return Err(manifest_error(
1709                        &package.manifest,
1710                        &dependency.key,
1711                        format!(
1712                            "`workspace = true` but the workspace in {dir} has no `[workspace.dependencies]` entry `{name}`"
1713                        ),
1714                    ));
1715                };
1716                renamed |= entry.package.is_some();
1717                entry.path.clone().map(|path| (dir, path))
1718            }
1719            WorkspaceOf::NotMember(workspace) => {
1720                return Err(manifest_error(
1721                    &package.manifest,
1722                    &dependency.key,
1723                    format!(
1724                        "`workspace = true` but the package is not a member of the workspace {workspace} (it is not listed in `workspace.members`, or is excluded)"
1725                    ),
1726                ));
1727            }
1728            WorkspaceOf::Absent => {
1729                return Err(manifest_error(
1730                    &package.manifest,
1731                    &dependency.key,
1732                    "`workspace = true` but there is no workspace manifest above the package"
1733                        .to_owned(),
1734                ));
1735            }
1736        },
1737    };
1738    let named = match place {
1739        None => None,
1740        Some((base, relative)) => match base.join(&relative) {
1741            Ok(joined) => {
1742                let target = tidy(reader.tree, &joined).map_err(|error| {
1743                    LoadError::tree(&package.manifest, None, &Origin::Discovery, error)
1744                })?;
1745                let matching = try_equal_range_by(reader.dirs, |id| {
1746                    Ok::<_, Infallible>(reader.found[id.index()].package.dir.cmp(&target))
1747                })
1748                .unwrap_or_else(|never| match never {});
1749                reader
1750                    .dirs
1751                    .get(matching.start)
1752                    .copied()
1753                    .filter(|_| !matching.is_empty())
1754            }
1755            // A path that leaves the tree, or is absolute, names no package
1756            // of the workspace.
1757            Err(PathError::AboveRoot { .. } | PathError::Absolute { .. }) => None,
1758            Err(other) => {
1759                return Err(manifest_error(
1760                    &package.manifest,
1761                    &dependency.key,
1762                    other.to_string(),
1763                ));
1764            }
1765        },
1766    };
1767    Ok(DependencyInfo {
1768        kind: dependency.kind,
1769        name: dependency.name.replace('-', "_"),
1770        renamed,
1771        package: named,
1772        active_targets: None,
1773    })
1774}
1775
1776fn source_files(
1777    visited: BTreeMap<RelPath, Visited>,
1778    targets: &[Target],
1779) -> Result<BTreeMap<RelPath, SourceFile>, LoadError> {
1780    visited
1781        .into_iter()
1782        .map(|(path, visited)| source_file(&path, visited, targets).map(|file| (path, file)))
1783        .collect()
1784}
1785
1786fn selected_targets(
1787    derived: Vec<(&RelPath, crate::target::Derived)>,
1788) -> Result<(Vec<Target>, Vec<Origin>), LoadError> {
1789    check_crate_paths(&derived)?;
1790    Ok(derived
1791        .into_iter()
1792        .map(|(_, item)| (item.target, item.origin))
1793        .unzip())
1794}
1795
1796fn configure_targets(
1797    reader: &Reader<'_>,
1798    dependencies: &[Vec<DependencyDeclaration>],
1799    binding: Option<&locked::BindingLoad<'_>>,
1800    locked: &mut [LockedBinding],
1801    infos: &mut [PackageInfo],
1802    derived: &mut Vec<(&RelPath, crate::target::Derived)>,
1803    syntax: SyntaxLoad<'_>,
1804) -> Result<Option<crate::ActiveConfiguration>, LoadError> {
1805    if matches!(syntax, SyntaxLoad::ShippingMembers) {
1806        derived.retain(|(_, entry)| entry.target.shipping);
1807    }
1808    if let Some(binding) = binding
1809        && locked::configure(binding, reader.found, dependencies, locked, reader.meter)?
1810    {
1811        locked::select_targets(locked, derived, reader.meter)?;
1812    }
1813    syntax
1814        .declared()
1815        .map(|configuration| {
1816            selected::configure(reader, dependencies, infos, derived, configuration)
1817        })
1818        .transpose()
1819}
1820
1821fn walk_source_syntax(
1822    tree: &dyn Tree,
1823    targets: &[Target],
1824    origins: &[Origin],
1825    bindings: &[LockedBinding],
1826    selected: Option<&crate::ActiveConfiguration>,
1827    meter: &Meter,
1828    syntax: SyntaxLoad<'_>,
1829) -> Result<SourceWalk, LoadError> {
1830    #[cfg(target_os = "linux")]
1831    if let Some((parallel, configurations)) = match syntax {
1832        SyntaxLoad::ConfiguredParallel(_, parallel) => {
1833            let active = selected.ok_or_else(|| {
1834                internal(
1835                    &RelPath::root(),
1836                    None,
1837                    "parallel target configuration was not admitted".to_owned(),
1838                )
1839            })?;
1840            Some((
1841                parallel,
1842                crate::parse::parallel::ExtractionConfigurations::Selected(active),
1843            ))
1844        }
1845        SyntaxLoad::LockedParallel(parallel) => Some((
1846            parallel,
1847            crate::parse::parallel::ExtractionConfigurations::Locked(bindings),
1848        )),
1849        _ => None,
1850    } {
1851        let resources = crate::parse::parallel::Resources::new(parallel)?;
1852        return std::thread::scope(|scope| {
1853            let parser = crate::parse::parallel::Executor::new(
1854                scope,
1855                &resources,
1856                parallel,
1857                Some((meter.options(), configurations)),
1858            )?;
1859            let walked = walk_sources(
1860                tree,
1861                targets,
1862                origins,
1863                bindings,
1864                selected,
1865                meter,
1866                Some(&parser),
1867            );
1868            let parallel_usage = Some(parser.finish());
1869            walked.map(|walked| SourceWalk {
1870                walked,
1871                parallel_usage,
1872            })
1873        });
1874    }
1875    let parser = match syntax {
1876        SyntaxLoad::Ordinary(parser) => parser,
1877        _ => None,
1878    };
1879    let walked = walk_sources(tree, targets, origins, bindings, selected, meter, parser)?;
1880    Ok(SourceWalk {
1881        walked,
1882        #[cfg(target_os = "linux")]
1883        parallel_usage: None,
1884    })
1885}
1886
1887fn walk_sources(
1888    tree: &dyn Tree,
1889    targets: &[Target],
1890    origins: &[Origin],
1891    bindings: &[LockedBinding],
1892    selected: Option<&crate::ActiveConfiguration>,
1893    meter: &Meter,
1894    parser: Option<&dyn crate::parse::Parser>,
1895) -> Result<Walked, LoadError> {
1896    let mut walker = Walker::with_parser(tree, meter, parser);
1897    let mut frontier = 1;
1898    for (index, (target, origin)) in targets.iter().zip(origins).enumerate() {
1899        frontier = frontier.max(index + 1);
1900        if let Some(parser) = parser {
1901            while parser.has_capacity() && frontier < targets.len() {
1902                if !walker.speculate(&targets[frontier].root) {
1903                    break;
1904                }
1905                frontier += 1;
1906            }
1907        }
1908        let locked = bindings
1909            .get(target.package_id.index())
1910            .map(|proof| {
1911                proof.admitted_configuration_for_under(
1912                    target.kind,
1913                    &target.name,
1914                    meter,
1915                    &target.root,
1916                )
1917            })
1918            .transpose()?
1919            .flatten();
1920        let configuration = selected
1921            .map(|active| WalkConfiguration {
1922                package: target.package_id,
1923                active,
1924                #[cfg(target_os = "linux")]
1925                key: ConfigurationKey::Selected,
1926            })
1927            .or_else(|| {
1928                locked.map(|configuration| WalkConfiguration {
1929                    package: target.package_id,
1930                    active: configuration.active,
1931                    #[cfg(target_os = "linux")]
1932                    key: ConfigurationKey::Locked(target.package_id, configuration.ordinal),
1933                })
1934            });
1935        walker.configure(configuration);
1936        walker.root(TargetId(index), &target.root, &target.crate_path, origin)?;
1937    }
1938    walker.finish()
1939}
1940
1941fn internal(file: &RelPath, line: Option<usize>, what: String) -> LoadError {
1942    LoadError::new(file, line, LoadErrorKind::Internal { what })
1943}
1944
1945/// The cargo selection data of one test function.
1946fn test_fn_of(item: &Item, targets: &[Target]) -> Result<TestFn, LoadError> {
1947    let target = targets.get(item.target.index()).ok_or_else(|| {
1948        internal(
1949            &item.file,
1950            Some(item.name_line),
1951            format!(
1952                "the target {} of `{}` does not exist",
1953                item.target.index(),
1954                item.path
1955            ),
1956        )
1957    })?;
1958    let name = item
1959        .path
1960        .strip_prefix(&target.crate_path)
1961        .and_then(|rest| rest.strip_prefix("::"))
1962        .ok_or_else(|| {
1963            internal(
1964                &item.file,
1965                Some(item.name_line),
1966                format!(
1967                    "the path `{}` does not start with the crate path `{}`",
1968                    item.path, target.crate_path
1969                ),
1970            )
1971        })?;
1972    Ok(TestFn {
1973        id: item.id,
1974        package: target.package.clone(),
1975        kind: target.kind,
1976        target: target.name.clone(),
1977        name: name.to_owned(),
1978    })
1979}
1980
1981/// A parsed file and the ways it was reached, as a source file.
1982fn source_file(
1983    path: &RelPath,
1984    visited: Visited,
1985    targets: &[Target],
1986) -> Result<SourceFile, LoadError> {
1987    let target_of = |reach: &Reach| {
1988        targets.get(reach.target.index()).ok_or_else(|| {
1989            internal(
1990                path,
1991                None,
1992                format!(
1993                    "the target {} of a module path does not exist",
1994                    reach.target.index()
1995                ),
1996            )
1997        })
1998    };
1999    let Some(first) = visited.reached.first() else {
2000        return Err(internal(
2001            path,
2002            None,
2003            "a loaded file has no module path".to_owned(),
2004        ));
2005    };
2006    let package = target_of(first)?.package.clone();
2007    let mut shipping = false;
2008    let mut test = true;
2009    for reach in &visited.reached {
2010        let target = target_of(reach)?;
2011        if !reach.test {
2012            test = false;
2013            shipping |= target.shipping;
2014        }
2015    }
2016    let parsed = Rc::unwrap_or_clone(visited.parsed);
2017    Ok(SourceFile {
2018        path: path.clone(),
2019        package,
2020        shipping,
2021        test,
2022        text: parsed.text,
2023        facts: parsed.facts,
2024        reached: visited.reached,
2025    })
2026}
2027
2028/// A function marked `#[test]`, with what cargo needs to select it.
2029#[derive(Debug, Clone, PartialEq, Eq)]
2030#[non_exhaustive]
2031pub struct TestFn {
2032    /// The item.
2033    pub id: ItemId,
2034    /// The package name (`-p`).
2035    pub package: String,
2036    /// The kind of the target that holds it: `Test` for `--test`, `Bin` for
2037    /// `--bin`, `Lib` for `--lib`.
2038    pub kind: TargetKind,
2039    /// The Cargo name of the target.
2040    pub target: String,
2041    /// The path of the function inside its crate, such as `inner::case`.
2042    pub name: String,
2043}
2044
2045#[cfg(test)]
2046mod tests {
2047    use super::*;
2048    use crate::budget::Budget;
2049    use crate::tree::MemoryTree;
2050
2051    #[test]
2052    fn native_package_name_index_keeps_identity_and_enforces_its_exact_grant() {
2053        let packages: Vec<_> = (0..24)
2054            .map(|index| Package {
2055                name: format!("package-{:02}", 23 - index),
2056                manifest: RelPath::new(&format!("p{index}/Cargo.toml")).expect("manifest"),
2057                dir: RelPath::new(&format!("p{index}")).expect("directory"),
2058            })
2059            .collect();
2060        let meter = Meter::new(&LoadOptions::default());
2061        let names = package_name_index(&packages, &meter).expect("native index");
2062        assert_eq!(names, (0..24).rev().map(PackageId).collect::<Vec<_>>());
2063        let charged = meter.usage().item_bytes;
2064        let exact = Meter::new(&LoadOptions {
2065            max_item_bytes: charged,
2066            ..LoadOptions::default()
2067        });
2068        assert_eq!(
2069            package_name_index(&packages, &exact).expect("exact grant"),
2070            names
2071        );
2072        let insufficient = Meter::new(&LoadOptions {
2073            max_item_bytes: charged - 1,
2074            ..LoadOptions::default()
2075        });
2076        let error = package_name_index(&packages, &insufficient).expect_err("one byte short");
2077        assert!(matches!(error.kind, LoadErrorKind::Budget {
2078            budget: Budget::ItemBytes,
2079            limit,
2080        } if limit == charged - 1));
2081        assert_eq!(error.file, RelPath::root());
2082    }
2083
2084    #[test]
2085    fn a_test_function_whose_path_leaves_its_crate_path_is_a_typed_error() {
2086        let tree = MemoryTree::from([
2087            ("Cargo.toml", "[package]\nname = \"demo\"\n"),
2088            ("src/lib.rs", "#[test]\nfn case() {}\n"),
2089        ]);
2090        let ws = Workspace::load(&tree, &["."]).expect("loads");
2091        let fns = ws.test_fns().expect("the invariant holds");
2092        assert_eq!(fns.len(), 1);
2093        let mut item = ws.item(fns[0].id).expect("item").clone();
2094        assert!(test_fn_of(&item, &ws.targets).is_ok());
2095        item.path = "other::case".into();
2096        let error = test_fn_of(&item, &ws.targets).expect_err("the path leaves the crate");
2097        assert!(
2098            matches!(error.kind, LoadErrorKind::Internal { .. }),
2099            "{error}"
2100        );
2101        assert_eq!(error.line, Some(2));
2102        item.path = "demo::case".into();
2103        item.target = TargetId(9);
2104        assert!(test_fn_of(&item, &ws.targets).is_err());
2105    }
2106}