Skip to main content

raf_source/workspace/
selected.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//! Exact declared target selection without dependency or provider admission.
5
6use super::{PackageInfo, Reader, SyntaxLoad, Workspace};
7use crate::configuration::{self, ActiveConfiguration, DeclaredConfiguration};
8use crate::meter::Meter;
9use crate::{DependencyDeclaration, LoadError, LoadOptions, RelPath, Tree};
10
11impl Workspace {
12    /// Load one exact package manifest and one declared target configuration.
13    ///
14    /// Workspace ancestors remain available for inherited manifest fields, but
15    /// sibling packages and other targets are not indexed. Only the selected
16    /// target's module tree is followed. Dependency declarations remain syntax:
17    /// no dependency edge or [`Self::locked_binding`] is admitted.
18    ///
19    /// The configuration is supplied by the caller, not observed from Cargo or
20    /// a compiler. Selection covers the existing modeled declaration headers;
21    /// it does not expand macros or establish generated definitions.
22    ///
23    /// # Examples
24    ///
25    /// Declare `doc` explicitly; this does not query a compiler.
26    ///
27    /// ```
28    /// use raf_source::{
29    ///     CfgAtom, DeclaredCfg, DeclaredConfiguration, LoadOptions, MemoryTree,
30    ///     RelPath, TargetKind, Workspace,
31    /// };
32    /// let tree = MemoryTree::from([
33    ///     ("Cargo.toml", "[package]\nname='demo'\nversion='1.0.0'\nedition='2024'\n"),
34    ///     ("src/lib.rs", "#[cfg(doc)] pub struct Documented;"),
35    /// ]);
36    /// let atoms = [CfgAtom::Name("doc")];
37    /// let declared = DeclaredConfiguration::new(
38    ///     DeclaredCfg::complete("declared-documentation", &atoms),
39    ///     &[], TargetKind::Lib, "demo",
40    /// );
41    /// let source = Workspace::load_configured_target(
42    ///     &tree, &RelPath::new("Cargo.toml")?, declared, &LoadOptions::default(),
43    /// )?;
44    /// let target = source.target_ids().next().expect("one selected target");
45    /// assert!(source.exported_items(target)?.items.iter()
46    ///     .any(|item| item.path == "demo::Documented"));
47    /// # Ok::<(), Box<dyn std::error::Error>>(())
48    /// ```
49    ///
50    /// # Errors
51    /// Refuses an invalid or missing package manifest, absent/ambiguous target,
52    /// invalid inherited fields, incomplete required features or configuration,
53    /// and all ordinary contained source and resource failures.
54    pub fn load_configured_target(
55        tree: &dyn Tree,
56        manifest: &RelPath,
57        configuration: DeclaredConfiguration<'_>,
58        options: &LoadOptions,
59    ) -> Result<Self, LoadError> {
60        Self::load_selected(
61            tree,
62            manifest,
63            options,
64            SyntaxLoad::Configured(configuration),
65        )
66    }
67
68    /// Load one declared Cargo target using the bounded native Linux parser workers.
69    ///
70    /// The manifest, target and declaration selection match
71    /// [`Self::load_configured_target`]. Only parsing is speculative. The
72    /// canonical coordinator admits selection and facts using the original
73    /// source and configuration budgets. The tree must satisfy
74    /// [`crate::ParallelTree`]'s stable observation contract.
75    ///
76    /// # Errors
77    /// Returns the canonical input errors of [`Self::load_configured_target`],
78    /// or scheduler-storage and worker-start failures. All workers are joined.
79    ///
80    /// # Panics
81    /// Resumes a canonically reached parser panic after worker cleanup.
82    #[cfg(target_os = "linux")]
83    pub fn par_load_configured_target(
84        tree: &dyn crate::ParallelTree,
85        manifest: &RelPath,
86        configuration: DeclaredConfiguration<'_>,
87        options: &LoadOptions,
88        parallel: &crate::ParallelOptions,
89    ) -> Result<Self, LoadError> {
90        Self::load_selected(
91            tree,
92            manifest,
93            options,
94            SyntaxLoad::ConfiguredParallel(configuration, parallel),
95        )
96    }
97
98    fn load_selected(
99        tree: &dyn Tree,
100        manifest: &RelPath,
101        options: &LoadOptions,
102        syntax: SyntaxLoad<'_>,
103    ) -> Result<Self, LoadError> {
104        let meter = Meter::new(options);
105        meter.items(crate::index::LOAD_BASE_BYTES, manifest, None)?;
106        let discovered = crate::discovery::single(tree, manifest, &meter)?;
107        Self::build_discovered_with_syntax(tree, options, &meter, None, &discovered, syntax)
108    }
109}
110
111pub(super) fn configure(
112    reader: &Reader<'_>,
113    declarations: &[Vec<DependencyDeclaration>],
114    infos: &mut [PackageInfo],
115    targets: &mut Vec<(&RelPath, crate::target::Derived)>,
116    input: DeclaredConfiguration<'_>,
117) -> Result<ActiveConfiguration, LoadError> {
118    let [found] = reader.found else {
119        return Err(configuration::failure(
120            &RelPath::root(),
121            "select exactly one package manifest",
122        ));
123    };
124    let manifest = &found.package.manifest;
125    let active = configuration::admit(
126        input,
127        &found.manifest.features,
128        &declarations[0],
129        reader.meter,
130        manifest,
131    )?;
132    let mut selected = None;
133    for (index, (_, derived)) in targets.iter().enumerate() {
134        reader.meter.work(
135            derived
136                .target
137                .name
138                .len()
139                .saturating_add(active.target_name().len())
140                .saturating_add(1),
141            manifest,
142            None,
143        )?;
144        if derived.target.kind == active.target_kind()
145            && derived.target.name == active.target_name()
146        {
147            if selected.replace(index).is_some() {
148                return Err(configuration::failure(
149                    manifest,
150                    "declared kind/name selects multiple package targets",
151                ));
152            }
153            for feature in &derived.target.required_features {
154                if !configuration::contains(active.features(), feature, reader.meter, manifest)? {
155                    return Err(configuration::failure(
156                        manifest,
157                        "selected target requires an inactive feature",
158                    ));
159                }
160            }
161        }
162    }
163    let selected = selected.ok_or_else(|| {
164        configuration::failure(manifest, "declared kind/name selects no package target")
165    })?;
166    let target = targets.remove(selected);
167    targets.clear();
168    targets.push(target);
169    infos[0].configured = true;
170    for dependency in &mut infos[0].dependencies {
171        dependency.package = None;
172    }
173    Ok(active)
174}