Skip to main content

raf_source/workspace/
locked.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//! Checked source/manifest association and requested edges in the existing loader.
5
6mod observed;
7mod reference;
8pub use observed::{ReferenceBinding, ReferencePackageRoots, ReferenceTree};
9pub use reference::{ReferenceObservation, ReferenceRequest};
10
11use purrdf_lex::allocation::{Admission, Memory, StorageError};
12use purrdf_lex::walk::{try_equal_range_by, try_sort_unstable_by};
13
14use super::{
15    Caches, DependencyDeclaration, Found, ItemAdmission, LoadError, LoadErrorKind, LoadOptions,
16    Meter, PackageId, PackageInfo, Reader, RelPath, SyntaxLoad, Workspace, WorkspaceOf,
17    workspace_of,
18};
19use crate::configuration::{self, ActiveConfiguration, DeclaredConfiguration};
20use crate::manifest::{self, VersionDecl};
21#[cfg(target_os = "linux")]
22use crate::parse::ConfigurationOrdinal;
23use crate::{
24    CommittedGitTree, LockedCatalog, LockedPackageId, LockedSource, RegistryArchiveTree,
25    RegistryIndex, SourceAuthorityId, SourceTrees, Tree,
26};
27
28/// An exact declaration requested for source-qualified cross-package traversal.
29#[derive(Debug, Clone, Copy)]
30pub struct LockedEdge<'a> {
31    key: &'a str,
32    registry: Option<RegistryIndex<'a>>,
33}
34
35impl<'a> LockedEdge<'a> {
36    /// Select a retained manifest key and any explicitly observed registry mapping.
37    #[must_use]
38    pub const fn new(key: &'a str, registry: Option<RegistryIndex<'a>>) -> Self {
39        Self { key, registry }
40    }
41}
42
43/// A candidate manifest/row association, verified by the locked load before use.
44#[derive(Debug)]
45pub struct LockedManifest<'a> {
46    row: LockedPackageId,
47    manifest: RelPath,
48    edges: &'a [LockedEdge<'a>],
49    configuration: Option<Configurations<'a>>,
50}
51
52#[derive(Debug, Clone, Copy)]
53enum Configurations<'a> {
54    One(DeclaredConfiguration<'a>),
55    Many(&'a [DeclaredConfiguration<'a>]),
56}
57
58impl<'a> Configurations<'a> {
59    fn iter(&self) -> impl Iterator<Item = DeclaredConfiguration<'a>> + '_ {
60        let (one, many) = match self {
61            Self::One(input) => (Some(*input), &[][..]),
62            Self::Many(inputs) => (None, *inputs),
63        };
64        one.into_iter().chain(many.iter().copied())
65    }
66}
67
68impl<'a> LockedManifest<'a> {
69    /// Associate a local manifest spelling with a row and explicitly requested edges.
70    /// This input is a locator, not source or package identity proof.
71    #[must_use]
72    pub fn new(row: LockedPackageId, manifest: RelPath, edges: &'a [LockedEdge<'a>]) -> Self {
73        Self {
74            row,
75            manifest,
76            edges,
77            configuration: None,
78        }
79    }
80    /// Select a declared compilation context; every admitted package must supply one.
81    #[must_use]
82    pub const fn with_configuration(mut self, configuration: DeclaredConfiguration<'a>) -> Self {
83        self.configuration = Some(Configurations::One(configuration));
84        self
85    }
86    /// Select exact target contexts, including any own-library companion.
87    ///
88    /// Each target name/kind occurs once. Incompatible modes of the same target
89    /// must be loaded separately; no context is inferred from this host.
90    #[must_use]
91    pub const fn with_configurations(
92        mut self,
93        configurations: &'a [DeclaredConfiguration<'a>],
94    ) -> Self {
95        self.configuration = Some(Configurations::Many(configurations));
96        self
97    }
98}
99
100/// A sealed external source admitted to configured dependency resolution.
101#[derive(Clone, Copy)]
102pub enum LockedTree<'a> {
103    /// Exact native committed Git objects.
104    Git(&'a CommittedGitTree<'a>),
105    /// Checksum-authenticated registry archive files.
106    Registry(&'a RegistryArchiveTree<'a>),
107}
108impl<'a> LockedTree<'a> {
109    fn reference(self) -> ReferenceTree<'a> {
110        match self {
111            Self::Git(tree) => ReferenceTree::Git(tree),
112            Self::Registry(tree) => ReferenceTree::Registry(tree),
113        }
114    }
115}
116
117/// Candidate manifests beneath one sealed external source.
118pub struct LockedPackageRoots<'a> {
119    tree: LockedTree<'a>,
120    packages: &'a [LockedManifest<'a>],
121}
122
123#[derive(Clone, Copy)]
124enum Sources<'a> {
125    Configured(&'a [LockedPackageRoots<'a>]),
126    Observed(&'a [ReferencePackageRoots<'a>]),
127}
128
129impl<'a> Sources<'a> {
130    fn len(&self) -> usize {
131        match self {
132            Self::Configured(sources) => sources.len(),
133            Self::Observed(sources) => sources.len(),
134        }
135    }
136
137    fn iter(&self) -> impl Iterator<Item = ReferencePackageRoots<'a>> + Clone {
138        let (configured, observed) = match self {
139            Self::Configured(sources) => (*sources, &[][..]),
140            Self::Observed(sources) => (&[][..], *sources),
141        };
142        configured
143            .iter()
144            .map(|source| ReferencePackageRoots::new(source.tree.reference(), source.packages))
145            .chain(observed.iter().copied())
146    }
147}
148
149#[derive(Clone, Copy)]
150enum Purpose<'a> {
151    Configured,
152    Structural(&'a [ReferenceTree<'a>]),
153}
154
155impl<'a> LockedPackageRoots<'a> {
156    /// Keep the sealed source root intact while selecting package manifests beneath it.
157    #[must_use]
158    pub const fn new(tree: LockedTree<'a>, packages: &'a [LockedManifest<'a>]) -> Self {
159        Self { tree, packages }
160    }
161}
162
163/// A source/manifest identity computed from a checked load, not from caller labels.
164/// Provenance alone does not imply active configuration; the separate optional
165/// configuration receipt records declared filtering, never provider policy.
166#[derive(Debug, PartialEq, Eq)]
167pub struct LockedBinding {
168    row: LockedPackageId,
169    name: String,
170    version: String,
171    source: Option<LockedSource>,
172    configurations: Vec<ActiveConfiguration>,
173}
174
175pub(super) struct AdmittedConfiguration<'a> {
176    pub(super) active: &'a ActiveConfiguration,
177    #[cfg(target_os = "linux")]
178    pub(super) ordinal: ConfigurationOrdinal,
179}
180
181impl LockedBinding {
182    /// Validated declared context, present only for a definition-filtered load.
183    #[must_use]
184    pub const fn configuration(&self) -> Option<&ActiveConfiguration> {
185        match self.configurations.as_slice() {
186            [only] => Some(only),
187            _ => None,
188        }
189    }
190    /// Every explicitly selected target context, empty for an unconfigured load.
191    #[must_use]
192    pub fn configurations(&self) -> &[ActiveConfiguration] {
193        &self.configurations
194    }
195    /// The exact selected context for an actual target kind and Cargo name.
196    #[must_use]
197    pub fn configuration_for(
198        &self,
199        kind: crate::TargetKind,
200        name: &str,
201    ) -> Option<&ActiveConfiguration> {
202        self.configurations
203            .iter()
204            .find(|config| config.target_kind() == kind && config.target_name() == name)
205    }
206    pub(crate) fn configuration_for_under(
207        &self,
208        kind: crate::TargetKind,
209        name: &str,
210        meter: &Meter,
211        path: &RelPath,
212    ) -> Result<Option<&ActiveConfiguration>, LoadError> {
213        self.admitted_configuration_for_under(kind, name, meter, path)
214            .map(|result| result.map(|configuration| configuration.active))
215    }
216    pub(super) fn admitted_configuration_for_under(
217        &self,
218        kind: crate::TargetKind,
219        name: &str,
220        meter: &Meter,
221        path: &RelPath,
222    ) -> Result<Option<AdmittedConfiguration<'_>>, LoadError> {
223        for (index, config) in self.configurations.iter().enumerate() {
224            #[cfg(not(target_os = "linux"))]
225            let _ = index;
226            meter.work(
227                config
228                    .target_name()
229                    .len()
230                    .saturating_add(name.len())
231                    .saturating_add(1),
232                path,
233                None,
234            )?;
235            if config.target_kind() == kind && config.target_name() == name {
236                return Ok(Some(AdmittedConfiguration {
237                    active: config,
238                    #[cfg(target_os = "linux")]
239                    ordinal: ConfigurationOrdinal(index),
240                }));
241            }
242        }
243        Ok(None)
244    }
245    /// The row in the catalog supplied to this load.
246    #[must_use]
247    pub const fn row(&self) -> LockedPackageId {
248        self.row
249    }
250    /// The actual manifest's validated package name.
251    #[must_use]
252    pub fn name(&self) -> &str {
253        &self.name
254    }
255    /// The actual explicit or inherited manifest version.
256    #[must_use]
257    pub fn version(&self) -> &str {
258        &self.version
259    }
260    /// Exact external source evidence, absent for explicitly associated local roots.
261    #[must_use]
262    pub const fn source(&self) -> Option<&LockedSource> {
263        self.source.as_ref()
264    }
265}
266
267struct Hint<'a> {
268    row: LockedPackageId,
269    manifest: RelPath,
270    edges: &'a [LockedEdge<'a>],
271    configuration: Option<Configurations<'a>>,
272}
273pub(super) struct BindingLoad<'a> {
274    catalog: &'a LockedCatalog,
275    hints: Vec<Hint<'a>>,
276    purpose: Purpose<'a>,
277}
278
279impl BindingLoad<'_> {
280    pub(super) fn structural(&self) -> bool {
281        matches!(self.purpose, Purpose::Structural(_))
282    }
283}
284
285struct MemberIdentity {
286    manifest: RelPath,
287    name: String,
288    version: Option<String>,
289}
290struct RepositoryMembers {
291    root: RelPath,
292    packages: Vec<MemberIdentity>,
293}
294
295impl Workspace {
296    /// Load checked source/manifest associations and explicitly requested locked edges.
297    ///
298    /// Ordinary discovery, indexing and resolution are reused. Every discovered
299    /// package must match one supplied manifest's actual name/version and source.
300    /// An external package must be the unique matching name/version in its checked
301    /// root package or root workspace membership; other layouts refuse.
302    /// Only requested, uniquely selected outgoing edges receive cross-package
303    /// targets; other dependency declarations remain unresolved syntax.
304    /// Target-conditional or optional requested edges need validated configuration
305    /// through [`LockedManifest::with_configuration`]. Without it they refuse.
306    /// This is not preferred-provider policy acceptance.
307    ///
308    /// # Errors
309    /// Refuses wrong/missing/duplicate manifests or source identities, inconsistent
310    /// versions, requested missing/ambiguous edges, unadmitted destinations and
311    /// unresolved conditional activation, preserving resource and source causes.
312    pub fn load_locked_sources(
313        catalog: &LockedCatalog,
314        first_party: &dyn Tree,
315        local: &[LockedManifest<'_>],
316        sources: &[LockedPackageRoots<'_>],
317        options: &LoadOptions,
318    ) -> Result<Self, LoadError> {
319        Self::load_locked_with(
320            catalog,
321            ReferenceTree::Opaque(first_party),
322            None,
323            local,
324            Sources::Configured(sources),
325            options,
326            SyntaxLoad::Ordinary(None),
327        )
328    }
329
330    /// Load all first-party packages discovered beneath explicit directory roots.
331    ///
332    /// Uses the same checked manifests, sealed Git and registry sources, budgets and index as
333    /// [`Self::load_locked_sources`]. Local manifest locators do not narrow the
334    /// discovery roots: every discovered package must have exactly one matching
335    /// locked association. External sealed roots retain their own source authority.
336    ///
337    /// # Errors
338    /// Refuses empty or externally qualified first-party roots, omitted or extra
339    /// manifest associations, and every failure of [`Self::load_locked_sources`].
340    pub fn load_locked_sources_under(
341        catalog: &LockedCatalog,
342        first_party: &dyn Tree,
343        first_party_roots: &[RelPath],
344        local: &[LockedManifest<'_>],
345        sources: &[LockedPackageRoots<'_>],
346        options: &LoadOptions,
347    ) -> Result<Self, LoadError> {
348        check_first_party_roots(first_party_roots)?;
349        Self::load_locked_with(
350            catalog,
351            ReferenceTree::Opaque(first_party),
352            Some(first_party_roots),
353            local,
354            Sources::Configured(sources),
355            options,
356            SyntaxLoad::Ordinary(None),
357        )
358    }
359
360    /// Load checked locked sources with bounded first-party parser read-ahead on Linux.
361    ///
362    /// The first-party tree meets the observation contract of [`crate::ParallelTree`].
363    /// Sealed sources are read in canonical budget order. The canonical walk selects
364    /// each target's configured syntax before extracting facts.
365    ///
366    /// # Errors
367    /// Returns the same input refusals as [`Self::load_locked_sources`], or a
368    /// scheduler-storage or worker-start failure. All workers are joined.
369    ///
370    /// # Panics
371    /// Resumes a canonically reached parser panic after worker cleanup.
372    #[cfg(target_os = "linux")]
373    pub fn par_load_locked_sources(
374        catalog: &LockedCatalog,
375        first_party: &dyn crate::ParallelTree,
376        local: &[LockedManifest<'_>],
377        sources: &[LockedPackageRoots<'_>],
378        options: &LoadOptions,
379        parallel: &crate::ParallelOptions,
380    ) -> Result<Self, LoadError> {
381        Self::load_locked_with(
382            catalog,
383            ReferenceTree::Opaque(first_party),
384            None,
385            local,
386            Sources::Configured(sources),
387            options,
388            SyntaxLoad::LockedParallel(parallel),
389        )
390    }
391
392    /// Load the checked packages beneath explicit first-party roots with bounded
393    /// native Linux parser read-ahead.
394    ///
395    /// Discovery follows [`Self::load_locked_sources_under`] and parsing follows
396    /// [`Self::par_load_locked_sources`].
397    ///
398    /// # Errors
399    /// Returns the discovery refusals of [`Self::load_locked_sources_under`] and
400    /// the input and scheduler failures of [`Self::par_load_locked_sources`].
401    ///
402    /// # Panics
403    /// Resumes a canonically reached parser panic after worker cleanup.
404    #[cfg(target_os = "linux")]
405    pub fn par_load_locked_sources_under(
406        catalog: &LockedCatalog,
407        first_party: &dyn crate::ParallelTree,
408        first_party_roots: &[RelPath],
409        local: &[LockedManifest<'_>],
410        sources: &[LockedPackageRoots<'_>],
411        options: &LoadOptions,
412        parallel: &crate::ParallelOptions,
413    ) -> Result<Self, LoadError> {
414        check_first_party_roots(first_party_roots)?;
415        Self::load_locked_with(
416            catalog,
417            ReferenceTree::Opaque(first_party),
418            Some(first_party_roots),
419            local,
420            Sources::Configured(sources),
421            options,
422            SyntaxLoad::LockedParallel(parallel),
423        )
424    }
425
426    fn load_locked_with(
427        catalog: &LockedCatalog,
428        first_party: ReferenceTree<'_>,
429        first_party_roots: Option<&[RelPath]>,
430        local: &[LockedManifest<'_>],
431        sources: Sources<'_>,
432        options: &LoadOptions,
433        syntax: SyntaxLoad<'_>,
434    ) -> Result<Self, LoadError> {
435        let meter = Meter::new(options);
436        let path = RelPath::root();
437        meter.items(catalog.usage().item_bytes, &path, None)?;
438        let mut admission = ItemAdmission::new(&meter, &path);
439        let result = (|| {
440            let mut memory = Memory::new(&mut admission);
441            let first_view = sealed_view(first_party, &meter)?;
442            let mut views = Vec::new();
443            memory.reserve(&mut views, sources.len()).map_err(native)?;
444            for source in sources.iter() {
445                views.push(sealed_view(source.tree, &meter)?);
446            }
447            let mut trees: Vec<&dyn Tree> = Vec::new();
448            memory.reserve(&mut trees, views.len()).map_err(native)?;
449            for (source, view) in sources.iter().zip(&views) {
450                trees.push(
451                    view.as_ref()
452                        .map_or_else(|| source.tree.tree(), |view| view.tree()),
453                );
454            }
455            let first = first_view
456                .as_ref()
457                .map_or_else(|| first_party.tree(), |view| view.tree());
458            let tree = SourceTrees::new(first, &trees);
459            let mut contexts = Vec::new();
460            if matches!(sources, Sources::Observed(_)) {
461                memory
462                    .reserve(&mut contexts, sources.len().saturating_add(1))
463                    .map_err(native)?;
464                contexts.push(first_party);
465                contexts.extend(sources.iter().map(|source| source.tree));
466            }
467            let mut binding = BindingLoad {
468                catalog,
469                hints: Vec::new(),
470                purpose: match sources {
471                    Sources::Configured(_) => Purpose::Configured,
472                    Sources::Observed(_) => Purpose::Structural(&contexts),
473                },
474            };
475            validate_registry_source(first_party, local, catalog)?;
476            let mut roots = Vec::new();
477            add_roots(
478                &mut binding,
479                &mut roots,
480                local,
481                SourceAuthorityId::FIRST_PARTY,
482                first_party.source(),
483                &meter,
484                &mut memory,
485            )?;
486            if let Some(selected) = first_party_roots {
487                roots.clear();
488                for root in selected {
489                    meter.items(crate::cost::shared_text(root.as_str().len()), root, None)?;
490                }
491                for root in selected {
492                    memory.push(&mut roots, root.clone()).map_err(native)?;
493                }
494            }
495            for (index, source) in sources.iter().enumerate() {
496                validate_registry_source(source.tree, source.packages, catalog)?;
497                add_roots(
498                    &mut binding,
499                    &mut roots,
500                    source.packages,
501                    SourceAuthorityId(index + 1),
502                    source.tree.source(),
503                    &meter,
504                    &mut memory,
505                )?;
506            }
507            try_sort_unstable_by(&mut binding.hints, |left, right| {
508                meter.work(
509                    left.manifest
510                        .as_str()
511                        .len()
512                        .saturating_add(right.manifest.as_str().len())
513                        .saturating_add(1),
514                    &path,
515                    None,
516                )?;
517                Ok::<_, LoadError>(left.manifest.cmp(&right.manifest))
518            })?;
519            for pair in binding.hints.windows(2) {
520                meter.work(1, &path, None)?;
521                if pair[0].manifest == pair[1].manifest {
522                    return Err(failure(&path, "duplicate manifest association"));
523                }
524            }
525            Self::load_meter_with_syntax(&tree, &roots, options, &meter, Some(&binding), syntax)
526        })();
527        result.map_err(|error| recover(error, &mut admission))
528    }
529}
530
531fn check_first_party_roots(roots: &[RelPath]) -> Result<(), LoadError> {
532    if roots.is_empty()
533        || roots
534            .iter()
535            .any(|root| root.authority() != SourceAuthorityId::FIRST_PARTY)
536    {
537        return Err(failure(
538            &RelPath::root(),
539            "supply nonempty first-party discovery roots",
540        ));
541    }
542    Ok(())
543}
544
545fn validate_registry_source(
546    tree: ReferenceTree<'_>,
547    packages: &[LockedManifest<'_>],
548    catalog: &LockedCatalog,
549) -> Result<(), LoadError> {
550    if let ReferenceTree::Registry(archive) = tree {
551        for package in packages {
552            if !catalog
553                .package(package.row)
554                .is_some_and(|row| archive.matches(row))
555            {
556                return Err(failure(
557                    &package.manifest,
558                    "registry archive differs from the selected package/checksum",
559                ));
560            }
561        }
562    }
563    Ok(())
564}
565
566enum SealedView<'a> {
567    Git(Box<CommittedGitTree<'a>>),
568    Registry(RegistryArchiveTree<'a>),
569}
570impl SealedView<'_> {
571    fn tree(&self) -> &dyn Tree {
572        match self {
573            Self::Git(tree) => tree.as_ref(),
574            Self::Registry(tree) => tree,
575        }
576    }
577}
578fn sealed_view<'a>(
579    tree: ReferenceTree<'a>,
580    meter: &'a Meter,
581) -> Result<Option<SealedView<'a>>, LoadError> {
582    match tree {
583        ReferenceTree::Git(tree) => {
584            let view = tree.under_meter(meter)?;
585            let path = RelPath::root();
586            let mut admission = ItemAdmission::new(meter, &path);
587            let view = Memory::new(&mut admission)
588                .boxed(view)
589                .map_err(|source| admission.error(source))?;
590            Ok(Some(SealedView::Git(view)))
591        }
592        ReferenceTree::Registry(tree) => tree
593            .under_meter(meter)
594            .map(|tree| Some(SealedView::Registry(tree))),
595        ReferenceTree::Opaque(_) | ReferenceTree::Disk(_) => Ok(None),
596    }
597}
598
599fn add_roots<'a>(
600    binding: &mut BindingLoad<'a>,
601    roots: &mut Vec<RelPath>,
602    packages: &'a [LockedManifest<'a>],
603    authority: SourceAuthorityId,
604    source: Option<&LockedSource>,
605    meter: &Meter,
606    memory: &mut Memory<'_, impl Admission>,
607) -> Result<(), LoadError> {
608    for package in packages {
609        let row = binding
610            .catalog
611            .package(package.row)
612            .ok_or_else(|| failure(&package.manifest, "unknown lock row"))?;
613        let observed_contents = binding.structural()
614            && source.is_none()
615            && row
616                .source()
617                .is_some_and(|source| source.kind() != crate::LockedSourceKind::Git);
618        if row.source() != source && !observed_contents {
619            return Err(failure(
620                &package.manifest,
621                "manifest locator's source does not match the checked snapshot or local root",
622            ));
623        }
624        if binding.structural() && package.configuration.is_some() {
625            return Err(failure(
626                &package.manifest,
627                "structural reference inputs must not supply configured target evidence",
628            ));
629        }
630        if package.manifest.authority() != SourceAuthorityId::FIRST_PARTY
631            || package.manifest.file_name() != Some("Cargo.toml")
632        {
633            return Err(failure(
634                &package.manifest,
635                "supply an unqualified Cargo.toml path inside the selected source",
636            ));
637        }
638        let manifest = package.manifest.clone().in_source(authority);
639        meter.items(
640            crate::cost::shared_text(manifest.as_str().len()),
641            &manifest,
642            None,
643        )?;
644        let dir = manifest
645            .parent()
646            .ok_or_else(|| failure(&manifest, "manifest has no package directory"))?;
647        memory.push(roots, dir).map_err(native)?;
648        memory
649            .push(
650                &mut binding.hints,
651                Hint {
652                    row: package.row,
653                    manifest,
654                    edges: package.edges,
655                    configuration: package.configuration,
656                },
657            )
658            .map_err(native)?;
659    }
660    Ok(())
661}
662
663pub(super) fn bind_found(
664    binding: &BindingLoad<'_>,
665    reader: &Reader<'_>,
666    caches: &mut Caches,
667) -> Result<Vec<LockedBinding>, LoadError> {
668    let path = RelPath::root();
669    let mut admission = ItemAdmission::new(reader.meter, &path);
670    let mut memory = Memory::new(&mut admission);
671    let result = (|| {
672        if reader.found.len() != binding.hints.len() {
673            return Err(failure(
674                &path,
675                "every discovered package needs exactly one explicit manifest association",
676            ));
677        }
678        let mut output = Vec::new();
679        let mut repositories = Vec::new();
680        memory
681            .reserve(&mut output, reader.found.len())
682            .map_err(native)?;
683        for found in reader.found {
684            let hint = hint_for(binding, &found.package.manifest, reader.meter)?;
685            let row = binding
686                .catalog
687                .package(hint.row)
688                .ok_or_else(|| failure(&found.package.manifest, "associated row is missing"))?;
689            let version_matches = match &found.declared.version {
690                VersionDecl::Explicit(version) => version == row.version(),
691                VersionDecl::Inherited => match workspace_of(reader, &found.package.dir, caches)? {
692                    WorkspaceOf::Member {
693                        version: Some(version),
694                        ..
695                    } => version.as_str() == row.version(),
696                    _ => {
697                        return Err(failure(
698                            &found.package.manifest,
699                            "inherited package version has no admitted workspace value",
700                        ));
701                    }
702                },
703                VersionDecl::Unset => {
704                    return Err(failure(
705                        &found.package.manifest,
706                        "grounded identity requires an actual explicit or inherited package version",
707                    ));
708                }
709            };
710            if found.declared.name != row.name() || !version_matches {
711                return Err(failure(
712                    &found.package.manifest,
713                    "actual manifest name/version does not match its exact lock row",
714                ));
715            }
716            if row.source().is_some() {
717                check_locator(
718                    reader,
719                    found,
720                    row.name(),
721                    row.version(),
722                    caches,
723                    &mut repositories,
724                    &mut memory,
725                )?;
726            }
727            let source = row
728                .source()
729                .map(|source| source.retained(&mut memory))
730                .transpose()
731                .map_err(native)?;
732            let name = memory.string(row.name()).map_err(native)?;
733            let version = memory.string(row.version()).map_err(native)?;
734            output.push(LockedBinding {
735                row: hint.row,
736                name,
737                version,
738                source,
739                configurations: Vec::new(),
740            });
741        }
742        Ok(output)
743    })();
744    result.map_err(|error| recover(error, &mut admission))
745}
746
747pub(super) fn install_edges(
748    binding: &BindingLoad<'_>,
749    reader: &Reader<'_>,
750    declarations: &[Vec<DependencyDeclaration>],
751    bound: &[LockedBinding],
752    targets: &[crate::Target],
753    infos: &mut [PackageInfo],
754) -> Result<(), LoadError> {
755    let found = reader.found;
756    let meter = reader.meter;
757    let rows = bound_rows(bound, meter)?;
758    for (index, info) in infos.iter_mut().enumerate() {
759        info.configured = !bound[index].configurations.is_empty();
760        let manifest = &found[index].package.manifest;
761        let hint = hint_for(binding, manifest, meter)?;
762        let mut matched = 0;
763        for (declaration, dependency) in declarations[index].iter().zip(&mut info.dependencies) {
764            let requested = requested_edge(hint.edges, &declaration.key, meter, manifest)?;
765            let Some(edge) = requested else {
766                if !binding.structural() {
767                    dependency.package = None;
768                }
769                continue;
770            };
771            matched += 1;
772            let active_targets = if binding.structural() {
773                None
774            } else {
775                eligible_targets(
776                    PackageId(index),
777                    &bound[index],
778                    targets,
779                    declaration,
780                    meter,
781                    manifest,
782                )?
783            };
784            let selected = binding.catalog.select_under(
785                bound[index].row,
786                declaration,
787                edge.registry,
788                meter,
789            )?;
790            let matching = try_equal_range_by(&rows, |id| {
791                meter.work(1, manifest, None)?;
792                Ok::<_, LoadError>(bound[id.index()].row.cmp(&selected))
793            })?;
794            let target = rows
795                .get(matching.start)
796                .copied()
797                .filter(|_| !matching.is_empty())
798                .ok_or_else(|| {
799                    failure(
800                        manifest,
801                        "selected outgoing row has no checked source/manifest package",
802                    )
803                })?;
804            for source in active_targets.iter().flatten() {
805                let selected = &targets[source.index()];
806                let active = bound[index]
807                    .configuration_for_under(selected.kind, &selected.name, meter, manifest)?
808                    .ok_or_else(|| {
809                        failure(manifest, "selected target has no admitted configuration")
810                    })?;
811                destination_configuration(
812                    (index, target),
813                    active,
814                    declaration,
815                    bound,
816                    found,
817                    meter,
818                    manifest,
819                )?;
820            }
821            dependency.active_targets = active_targets;
822            let spec = declaration
823                .inherited
824                .as_ref()
825                .map_or(&declaration.specification, |entry| &entry.specification);
826            if spec.path.is_some() && dependency.package != Some(target) {
827                if dependency.package.is_some() {
828                    return Err(failure(
829                        manifest,
830                        "declared path does not name the selected row's actual admitted manifest",
831                    ));
832                }
833                binding.check_observed_path(
834                    reader,
835                    declaration,
836                    manifest,
837                    &found[target.index()].package.manifest,
838                )?;
839            }
840            dependency.package = Some(target);
841        }
842        if matched != hint.edges.len() {
843            return Err(failure(
844                manifest,
845                "a requested key is absent; use the exact retained declaration key",
846            ));
847        }
848    }
849    Ok(())
850}
851
852fn requested_edge<'a>(
853    edges: &[LockedEdge<'a>],
854    key: &str,
855    meter: &Meter,
856    manifest: &RelPath,
857) -> Result<Option<LockedEdge<'a>>, LoadError> {
858    let mut requested = None;
859    for edge in edges {
860        meter.work(
861            edge.key.len().saturating_add(key.len()).saturating_add(1),
862            manifest,
863            None,
864        )?;
865        if edge.key == key && requested.replace(*edge).is_some() {
866            return Err(failure(manifest, "duplicate requested declaration key"));
867        }
868    }
869    Ok(requested)
870}
871
872fn bound_rows(bound: &[LockedBinding], meter: &Meter) -> Result<Vec<PackageId>, LoadError> {
873    let path = RelPath::root();
874    let mut admission = ItemAdmission::new(meter, &path);
875    let mut rows = Vec::new();
876    Memory::new(&mut admission)
877        .reserve(&mut rows, bound.len())
878        .map_err(|error| admission.error(error))?;
879    meter.work(bound.len(), &path, None)?;
880    rows.extend((0..bound.len()).map(PackageId));
881    try_sort_unstable_by(&mut rows, |left, right| {
882        meter.work(1, &path, None)?;
883        Ok::<_, LoadError>(bound[left.index()].row.cmp(&bound[right.index()].row))
884    })?;
885    for pair in rows.windows(2) {
886        meter.work(1, &path, None)?;
887        if bound[pair[0].index()].row == bound[pair[1].index()].row {
888            return Err(failure(
889                &path,
890                "one lock row cannot acquire multiple loaded package identities",
891            ));
892        }
893    }
894    Ok(rows)
895}
896
897fn eligible_targets(
898    package: PackageId,
899    proof: &LockedBinding,
900    targets: &[crate::Target],
901    declaration: &DependencyDeclaration,
902    meter: &Meter,
903    manifest: &RelPath,
904) -> Result<Option<Vec<crate::TargetId>>, LoadError> {
905    if proof.configurations.is_empty() {
906        eligible(declaration, None, meter, manifest)?;
907        return Ok(None);
908    }
909    let mut admission = ItemAdmission::new(meter, manifest);
910    let result = (|| {
911        let mut memory = Memory::new(&mut admission);
912        let mut selected = Vec::new();
913        for (position, target) in targets.iter().enumerate() {
914            meter.work(1, manifest, None)?;
915            if target.package_id != package {
916                continue;
917            }
918            let active = proof
919                .configuration_for_under(target.kind, &target.name, meter, manifest)?
920                .ok_or_else(|| {
921                    failure(manifest, "selected target has no admitted configuration")
922                })?;
923            if eligible(declaration, Some(active), meter, manifest)? {
924                memory
925                    .push(&mut selected, crate::TargetId(position))
926                    .map_err(native)?;
927            }
928        }
929        if selected.is_empty() {
930            return Err(failure(
931                manifest,
932                "requested dependency is inactive or ineligible in every selected target context",
933            ));
934        }
935        Ok(Some(selected))
936    })();
937    result.map_err(|error| recover(error, &mut admission))
938}
939
940fn eligible(
941    declaration: &DependencyDeclaration,
942    active: Option<&ActiveConfiguration>,
943    meter: &Meter,
944    manifest: &RelPath,
945) -> Result<bool, LoadError> {
946    let Some(active) = active else {
947        if declaration.condition.is_some() || declaration.specification.optional == Some(true) {
948            return Err(failure(
949                manifest,
950                "requested conditional/optional dependency needs admitted configuration",
951            ));
952        }
953        return Ok(true);
954    };
955    let allowed = match active.target_kind() {
956        crate::TargetKind::BuildScript => declaration.kind == crate::DependencyKind::Build,
957        crate::TargetKind::Lib | crate::TargetKind::Bin => {
958            declaration.kind == crate::DependencyKind::Normal
959                || (declaration.kind == crate::DependencyKind::Dev
960                    && configuration::evaluate(
961                        &crate::cfg::CfgExpr::Test,
962                        active,
963                        false,
964                        meter,
965                        manifest,
966                    )?)
967        }
968        crate::TargetKind::Test | crate::TargetKind::Bench | crate::TargetKind::Example => {
969            matches!(
970                declaration.kind,
971                crate::DependencyKind::Normal | crate::DependencyKind::Dev
972            )
973        }
974    };
975    if !allowed {
976        return Ok(false);
977    }
978    if let Some(condition) = &declaration.condition
979        && !configuration::condition(condition, active, meter, manifest)?
980    {
981        return Ok(false);
982    }
983    Ok(declaration.specification.optional != Some(true)
984        || configuration::contains(
985            active.optional_dependencies(),
986            &declaration.name,
987            meter,
988            manifest,
989        )?)
990}
991fn destination_configuration(
992    endpoints: (usize, PackageId),
993    active: &ActiveConfiguration,
994    declaration: &DependencyDeclaration,
995    bound: &[LockedBinding],
996    found: &[Found],
997    meter: &Meter,
998    manifest: &RelPath,
999) -> Result<(), LoadError> {
1000    let (index, target) = endpoints;
1001    meter.work(bound[target.index()].configurations.len(), manifest, None)?;
1002    let mut libraries = bound[target.index()]
1003        .configurations
1004        .iter()
1005        .filter(|config| config.target_kind() == crate::TargetKind::Lib);
1006    let destination = libraries.next().ok_or_else(|| {
1007        failure(
1008            manifest,
1009            "dependency destination must select its actual library target",
1010        )
1011    })?;
1012    if libraries.next().is_some() {
1013        return Err(failure(
1014            manifest,
1015            "dependency destination has ambiguous library configurations",
1016        ));
1017    }
1018    let expected = active
1019        .selected()
1020        .ok_or_else(|| failure(manifest, "selected context lacks its host cfg"))?;
1021    meter.work(
1022        expected
1023            .triple()
1024            .len()
1025            .saturating_add(destination.target().triple().len())
1026            .saturating_add(1),
1027        manifest,
1028        None,
1029    )?;
1030    if expected.triple() != destination.target().triple() {
1031        return Err(failure(
1032            manifest,
1033            "dependency destination has a different declared compilation target",
1034        ));
1035    }
1036    if configuration::evaluate(
1037        &crate::cfg::CfgExpr::Test,
1038        destination,
1039        false,
1040        meter,
1041        manifest,
1042    )? {
1043        return Err(failure(
1044            manifest,
1045            "dependency library must use its ordinary context; load unit-test modes separately",
1046        ));
1047    }
1048    configuration::destination(
1049        active,
1050        Some(destination),
1051        declaration,
1052        &found[index].manifest.features,
1053        &found[target.index()].manifest.features,
1054        meter,
1055        manifest,
1056    )
1057}
1058
1059pub(super) fn configure(
1060    binding: &BindingLoad<'_>,
1061    found: &[Found],
1062    declarations: &[Vec<DependencyDeclaration>],
1063    bound: &mut [LockedBinding],
1064    meter: &Meter,
1065) -> Result<bool, LoadError> {
1066    let active = binding
1067        .hints
1068        .iter()
1069        .any(|hint| hint.configuration.is_some());
1070    if !active {
1071        return Ok(false);
1072    }
1073    for (index, package) in found.iter().enumerate() {
1074        let hint = hint_for(binding, &package.package.manifest, meter)?;
1075        let input = hint.configuration.ok_or_else(|| {
1076            failure(
1077                &package.package.manifest,
1078                "a configured load needs explicit configuration for every admitted package",
1079            )
1080        })?;
1081        let mut admission = ItemAdmission::new(meter, &package.package.manifest);
1082        let result = (|| {
1083            let mut memory = Memory::new(&mut admission);
1084            for input in input.iter() {
1085                let active = configuration::admit(
1086                    input,
1087                    &package.manifest.features,
1088                    &declarations[index],
1089                    meter,
1090                    &package.package.manifest,
1091                )?;
1092                for known in &bound[index].configurations {
1093                    meter.work(
1094                        known
1095                            .target_name()
1096                            .len()
1097                            .saturating_add(active.target_name().len())
1098                            .saturating_add(1),
1099                        &package.package.manifest,
1100                        None,
1101                    )?;
1102                    if known.target_kind() == active.target_kind()
1103                        && known.target_name() == active.target_name()
1104                    {
1105                        return Err(failure(
1106                            &package.package.manifest,
1107                            "duplicate target configuration; load incompatible modes separately",
1108                        ));
1109                    }
1110                }
1111                memory
1112                    .push(&mut bound[index].configurations, active)
1113                    .map_err(native)?;
1114            }
1115            Ok(())
1116        })();
1117        result.map_err(|error| recover(error, &mut admission))?;
1118        if bound[index].configurations.is_empty() {
1119            return Err(failure(
1120                &package.package.manifest,
1121                "a configured package needs at least one explicit target context",
1122            ));
1123        }
1124    }
1125    Ok(true)
1126}
1127
1128pub(super) fn select_targets(
1129    bound: &[LockedBinding],
1130    derived: &mut Vec<(&RelPath, crate::target::Derived)>,
1131    meter: &Meter,
1132) -> Result<(), LoadError> {
1133    let root = RelPath::root();
1134    for (index, proof) in bound.iter().enumerate() {
1135        for config in proof.configurations() {
1136            let mut selected = None;
1137            for (_, item) in derived.iter() {
1138                meter.work(
1139                    item.target
1140                        .name
1141                        .len()
1142                        .saturating_add(config.target_name().len())
1143                        .saturating_add(1),
1144                    &root,
1145                    None,
1146                )?;
1147                if item.target.package_id == PackageId(index)
1148                    && item.target.kind == config.target_kind()
1149                    && item.target.name == config.target_name()
1150                {
1151                    if selected.is_some() {
1152                        return Err(configuration::failure(
1153                            &root,
1154                            "configured target name/kind is ambiguous",
1155                        ));
1156                    }
1157                    selected = Some(&item.target);
1158                }
1159            }
1160            let selected = selected.ok_or_else(|| {
1161                configuration::failure(
1162                    &root,
1163                    "configured target name/kind does not select exactly one actual package target",
1164                )
1165            })?;
1166            for feature in &selected.required_features {
1167                if !configuration::contains(config.features(), feature, meter, &selected.root)? {
1168                    return Err(configuration::failure(
1169                        &selected.root,
1170                        "selected target has an unsatisfied required feature",
1171                    ));
1172                }
1173            }
1174            if !matches!(
1175                config.target_kind(),
1176                crate::TargetKind::Lib | crate::TargetKind::BuildScript
1177            ) {
1178                check_companions(PackageId(index), proof, config, derived, meter)?;
1179            }
1180        }
1181    }
1182    let mut selection = Ok(());
1183    derived.retain(|(_, item)| {
1184        if selection.is_err() {
1185            return false;
1186        }
1187        match bound[item.target.package_id.index()].configuration_for_under(
1188            item.target.kind,
1189            &item.target.name,
1190            meter,
1191            &root,
1192        ) {
1193            Ok(context) => context.is_some(),
1194            Err(error) => {
1195                selection = Err(error);
1196                false
1197            }
1198        }
1199    });
1200    selection
1201}
1202
1203fn check_companions(
1204    package: PackageId,
1205    proof: &LockedBinding,
1206    config: &ActiveConfiguration,
1207    derived: &[(&RelPath, crate::target::Derived)],
1208    meter: &Meter,
1209) -> Result<(), LoadError> {
1210    let root = RelPath::root();
1211    meter.work(derived.len(), &root, None)?;
1212    for (_, library) in derived.iter().filter(|(_, item)| {
1213        item.target.package_id == package && item.target.kind == crate::TargetKind::Lib
1214    }) {
1215        meter.work(1, &root, None)?;
1216        let companion = proof
1217            .configuration_for_under(crate::TargetKind::Lib, &library.target.name, meter, &root)?
1218            .ok_or_else(|| {
1219                failure(
1220                    &root,
1221                    "selected target requires an explicit own-library companion configuration",
1222                )
1223            })?;
1224        meter.work(
1225            config
1226                .target()
1227                .triple()
1228                .len()
1229                .saturating_add(companion.target().triple().len())
1230                .saturating_add(1),
1231            &root,
1232            None,
1233        )?;
1234        if config.target().triple() != companion.target().triple()
1235            || !config.same_features_under(companion, meter, &root)?
1236            || configuration::evaluate(&crate::cfg::CfgExpr::Test, companion, false, meter, &root)?
1237        {
1238            return Err(failure(
1239                &root,
1240                "own-library companion needs the same declared target and unified features in its ordinary mode",
1241            ));
1242        }
1243    }
1244    Ok(())
1245}
1246
1247fn check_locator<S: Admission + ?Sized>(
1248    reader: &Reader<'_>,
1249    found: &Found,
1250    name: &str,
1251    version: &str,
1252    caches: &mut Caches,
1253    repositories: &mut Vec<RepositoryMembers>,
1254    memory: &mut Memory<'_, S>,
1255) -> Result<(), LoadError> {
1256    let root = found.package.dir.source_root();
1257    let mut position = None;
1258    for (index, repository) in repositories.iter().enumerate() {
1259        reader.meter.work(1, &found.package.manifest, None)?;
1260        if repository.root == root {
1261            position = Some(index);
1262            break;
1263        }
1264    }
1265    let index = if let Some(index) = position {
1266        index
1267    } else {
1268        let packages = repository_members(reader, &root, caches, memory)?;
1269        let index = repositories.len();
1270        memory
1271            .push(repositories, RepositoryMembers { root, packages })
1272            .map_err(native)?;
1273        index
1274    };
1275    let mut matched = None;
1276    for package in &repositories[index].packages {
1277        reader.meter.work(
1278            package
1279                .name
1280                .len()
1281                .saturating_add(name.len())
1282                .saturating_add(1),
1283            &found.package.manifest,
1284            None,
1285        )?;
1286        if package.name != name {
1287            continue;
1288        }
1289        let actual = package.version.as_deref().ok_or_else(|| {
1290            failure(
1291                &package.manifest,
1292                "same-named repository package has no version evidence",
1293            )
1294        })?;
1295        reader.meter.work(
1296            actual.len().saturating_add(version.len()).saturating_add(1),
1297            &found.package.manifest,
1298            None,
1299        )?;
1300        if actual == version {
1301            if matched.is_some() {
1302                return Err(failure(
1303                    &found.package.manifest,
1304                    "ambiguous package name/version in the checked root workspace",
1305                ));
1306            }
1307            matched = Some(&package.manifest);
1308        }
1309    }
1310    if matched != Some(&found.package.manifest) {
1311        return Err(failure(
1312            &found.package.manifest,
1313            "manifest locator is not the unique matching package in the checked root package/workspace",
1314        ));
1315    }
1316    Ok(())
1317}
1318
1319fn repository_members<S: Admission + ?Sized>(
1320    reader: &Reader<'_>,
1321    root: &RelPath,
1322    caches: &mut Caches,
1323    memory: &mut Memory<'_, S>,
1324) -> Result<Vec<MemberIdentity>, LoadError> {
1325    let root_manifest = root
1326        .join("Cargo.toml")
1327        .map_err(|error| failure(root, &error.to_string()))?;
1328    let parsed = read_manifest(reader, &root_manifest)?;
1329    let mut dirs = Vec::new();
1330    if parsed.has_workspace {
1331        let members = match caches.members.entry(root.clone()) {
1332            std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
1333            std::collections::btree_map::Entry::Vacant(entry) => entry.insert(super::members(
1334                reader.tree,
1335                reader.meter,
1336                root,
1337                &root_manifest,
1338                &parsed,
1339            )?),
1340        };
1341        memory.reserve(&mut dirs, members.len()).map_err(native)?;
1342        dirs.extend(members.iter().cloned());
1343    } else if parsed.package.is_some() {
1344        memory.push(&mut dirs, root.clone()).map_err(native)?;
1345    } else {
1346        return Err(failure(
1347            &root_manifest,
1348            "Git package binding needs a checked root package or root workspace",
1349        ));
1350    }
1351    let mut packages = Vec::new();
1352    memory.reserve(&mut packages, dirs.len()).map_err(native)?;
1353    for dir in dirs {
1354        reader.meter.items(
1355            crate::cost::shared_text(dir.as_str().len().saturating_add(11)),
1356            &root_manifest,
1357            None,
1358        )?;
1359        let manifest = dir
1360            .join("Cargo.toml")
1361            .map_err(|error| failure(&dir, &error.to_string()))?;
1362        let member = read_manifest(reader, &manifest)?;
1363        let package = member
1364            .package
1365            .as_ref()
1366            .ok_or_else(|| failure(&manifest, "workspace member has no package identity"))?;
1367        let version = match &package.version {
1368            VersionDecl::Explicit(version) => Some(version.as_str()),
1369            VersionDecl::Inherited => parsed.workspace_version.as_deref(),
1370            VersionDecl::Unset => None,
1371        }
1372        .map(|version| memory.string(version))
1373        .transpose()
1374        .map_err(native)?;
1375        let name = memory.string(&package.name).map_err(native)?;
1376        packages.push(MemberIdentity {
1377            manifest,
1378            name,
1379            version,
1380        });
1381    }
1382    Ok(packages)
1383}
1384
1385fn read_manifest(reader: &Reader<'_>, path: &RelPath) -> Result<manifest::Manifest, LoadError> {
1386    let text = reader
1387        .tree
1388        .read(path, reader.meter.options().max_file_bytes)
1389        .map_err(|error| LoadError::tree(path, None, &crate::Origin::Discovery, error))?;
1390    reader.meter.read(path, &text)?;
1391    manifest::parse(&text).map_err(|error| {
1392        let origin = error
1393            .key
1394            .map_or(crate::Origin::Discovery, |key| crate::Origin::ManifestKey {
1395                key,
1396            });
1397        LoadError::new(
1398            path,
1399            None,
1400            LoadErrorKind::Manifest {
1401                message: error.message,
1402                source: error.source,
1403            },
1404        )
1405        .reached_by(&origin)
1406    })
1407}
1408
1409fn hint_for<'a, 'b>(
1410    binding: &'a BindingLoad<'b>,
1411    path: &RelPath,
1412    meter: &Meter,
1413) -> Result<&'a Hint<'b>, LoadError> {
1414    let matching = try_equal_range_by(&binding.hints, |hint| {
1415        meter.work(
1416            hint.manifest
1417                .as_str()
1418                .len()
1419                .saturating_add(path.as_str().len())
1420                .saturating_add(1),
1421            path,
1422            None,
1423        )?;
1424        Ok::<_, LoadError>(hint.manifest.cmp(path))
1425    })?;
1426    binding
1427        .hints
1428        .get(matching.start)
1429        .filter(|_| !matching.is_empty())
1430        .ok_or_else(|| failure(path, "discovered manifest was not explicitly associated"))
1431}
1432
1433fn failure(path: &RelPath, message: &str) -> LoadError {
1434    LoadError::new(
1435        path,
1436        None,
1437        LoadErrorKind::Locked {
1438            field: "source-binding",
1439            message: message.to_owned(),
1440            source: None,
1441        },
1442    )
1443}
1444fn native(error: StorageError) -> LoadError {
1445    LoadError::new(&RelPath::root(), None, LoadErrorKind::Storage(error))
1446}
1447fn recover(error: LoadError, admission: &mut ItemAdmission<'_>) -> LoadError {
1448    admission.recover(error)
1449}