Skip to main content

raf_source/
target.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//! Package targets: the library, binaries, tests, benches, examples and build
5//! script of a package, with the crate path each one is indexed under.
6
7use crate::error::{LoadError, LoadErrorKind, Origin, TargetProblem, TreeError};
8use crate::manifest::{Build, Manifest, PackageDecl, TargetDecl, TargetSettings};
9use crate::modtree::tidy;
10use crate::path::RelPath;
11use crate::tree::{EntryKind, Tree};
12
13/// The identity of a package within one loaded [`Workspace`](crate::Workspace).
14///
15/// IDs follow manifest order and are local to that load. A durable package or
16/// provider identity also requires its version and source; this ID proves neither.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct PackageId(pub(crate) usize);
19
20impl PackageId {
21    /// The position of the package in [`Workspace::packages`](crate::Workspace::packages).
22    #[must_use]
23    pub const fn index(self) -> usize {
24        self.0
25    }
26}
27
28/// What a target is.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
30#[non_exhaustive]
31pub enum TargetKind {
32    /// The library.
33    Lib,
34    /// A binary.
35    Bin,
36    /// An integration test.
37    Test,
38    /// A benchmark.
39    Bench,
40    /// An example.
41    Example,
42    /// The build script.
43    BuildScript,
44}
45
46impl TargetKind {
47    /// True for code that ships: the library, the binaries and the build
48    /// script, which is part of what a package builds with. Tests, benches and
49    /// examples do not.
50    #[must_use]
51    pub const fn is_shipping(self) -> bool {
52        matches!(self, Self::Lib | Self::Bin | Self::BuildScript)
53    }
54}
55
56/// A package found under a root.
57///
58/// The struct is `#[non_exhaustive]`: adding a field is not a breaking change,
59/// so a pattern names the fields it reads and ends in `..`.
60///
61/// ```compile_fail,E0638
62/// # fn names(package: &raf_source::Package) {
63/// let raf_source::Package { name, manifest, dir } = package;
64/// # }
65/// ```
66#[derive(Debug, Clone, PartialEq, Eq)]
67#[non_exhaustive]
68pub struct Package {
69    /// The name in `[package]`.
70    pub name: String,
71    /// The path of its `Cargo.toml`.
72    pub manifest: RelPath,
73    /// The directory that holds it.
74    pub dir: RelPath,
75}
76
77/// One target of a package.
78///
79/// The test settings (`harness`, `required_features`, `test` and `doctest`)
80/// are read from the target table, `[lib]` or `[[bin]]` and the others, and
81/// take cargo's default when the table leaves them out or the target has no
82/// table. The build script has no table and is never tested: its `harness`,
83/// `test` and `doctest` are false and it requires no feature.
84///
85/// The struct is `#[non_exhaustive]`: adding a field is not a breaking change,
86/// so a pattern names the fields it reads and ends in `..`.
87///
88/// ```compile_fail,E0638
89/// # fn names(target: &raf_source::Target) {
90/// let raf_source::Target {
91///     package, name, kind, crate_path, root, shipping,
92///     harness, required_features, test, doctest,
93/// } = target;
94/// # }
95/// ```
96#[derive(Debug, Clone, PartialEq, Eq)]
97#[non_exhaustive]
98#[expect(
99    clippy::struct_excessive_bools,
100    reason = "harness, test and doctest are Cargo's boolean target keys, kept one to one"
101)]
102pub struct Target {
103    /// The package's identity within the loaded workspace.
104    pub package_id: PackageId,
105    /// The package name.
106    pub package: String,
107    /// The Cargo name of the target.
108    pub name: String,
109    /// What the target is.
110    pub kind: TargetKind,
111    /// The path items of this target are indexed under: the crate name for the
112    /// library (`[lib] name`, or the package name, with `-` as `_`),
113    /// `<pkg>::bin_crate::<bin>` for a binary,
114    /// `<pkg>::{test,bench,example}_crate::<target>` for the others and
115    /// `<pkg>::build_script` for the build script.
116    pub crate_path: String,
117    /// The root source file.
118    pub root: RelPath,
119    /// True for the library, the binaries and the build script.
120    pub shipping: bool,
121    /// `harness`: true when `cargo test` builds the target with the libtest
122    /// harness, which is cargo's default for every target table.
123    pub harness: bool,
124    /// `required-features`: the features the target needs before cargo builds
125    /// it, in manifest order; empty by default.
126    pub required_features: Vec<String>,
127    /// `test`: true when `cargo test` tests the target by default. Cargo's
128    /// default is true for the library, the binaries and the tests and false
129    /// for benches and examples.
130    pub test: bool,
131    /// `doctest`: true when `cargo test` runs the documentation tests of the
132    /// target. Cargo's default is true for the library and false for every
133    /// other target. The value is reported as the manifest writes it; cargo
134    /// honours the key only for the library.
135    pub doctest: bool,
136}
137
138/// A target together with what led to its root file.
139pub(crate) struct Derived {
140    pub(crate) target: Target,
141    pub(crate) origin: Origin,
142}
143
144fn ident(name: &str) -> String {
145    name.replace('-', "_")
146}
147
148/// Everything target derivation needs about one package.
149pub(crate) struct Context<'a> {
150    pub(crate) package_id: PackageId,
151    pub(crate) tree: &'a dyn Tree,
152    pub(crate) manifest_path: &'a RelPath,
153    pub(crate) dir: &'a RelPath,
154    pub(crate) manifest: &'a Manifest,
155    pub(crate) package: &'a PackageDecl,
156}
157
158impl Context<'_> {
159    fn error(&self, origin: &Origin, kind: LoadErrorKind) -> LoadError {
160        LoadError::new(self.manifest_path, None, kind).reached_by(origin)
161    }
162
163    fn tree_error(&self, origin: &Origin, error: TreeError) -> LoadError {
164        LoadError::tree(self.manifest_path, None, origin, error)
165    }
166
167    /// `relative` below the package directory.
168    fn join(&self, relative: &str, origin: &Origin) -> Result<RelPath, LoadError> {
169        let joined = self
170            .dir
171            .join(relative)
172            .map_err(|error| self.tree_error(origin, error.into()))?;
173        tidy(self.tree, &joined).map_err(|error| self.tree_error(origin, error))
174    }
175
176    /// True when a file (or a symlink that may lead to one) is at `path`.
177    fn is_file(&self, path: &RelPath, origin: &Origin) -> Result<bool, LoadError> {
178        match self
179            .tree
180            .entry(path)
181            .map_err(|error| self.tree_error(origin, error))?
182        {
183            // A special file counts as present so that reading it is refused,
184            // not mistaken for a missing target.
185            Some(EntryKind::File | EntryKind::Symlink | EntryKind::Other) => Ok(true),
186            Some(EntryKind::Dir) | None => Ok(false),
187        }
188    }
189
190    /// The entries of a package directory such as `tests`, if it is one.
191    fn list(&self, relative: &str) -> Result<Vec<crate::tree::Entry>, LoadError> {
192        let origin = Origin::Discovery;
193        let path = self.join(relative, &origin)?;
194        match self
195            .tree
196            .entry(&path)
197            .map_err(|error| self.tree_error(&origin, error))?
198        {
199            None => Ok(Vec::new()),
200            Some(EntryKind::Dir) => self
201                .tree
202                .list(&path)
203                .map_err(|error| LoadError::tree(&path, None, &origin, error)),
204            Some(EntryKind::Symlink) => {
205                Err(LoadError::new(&path, None, LoadErrorKind::DirSymlink).reached_by(&origin))
206            }
207            Some(EntryKind::File | EntryKind::Other) => Err(LoadError::tree(
208                &path,
209                None,
210                &origin,
211                TreeError::NotRegular {
212                    path: path.to_string(),
213                },
214            )),
215        }
216    }
217
218    fn missing(&self, path: RelPath, origin: &Origin) -> LoadError {
219        self.error(
220            origin,
221            LoadErrorKind::Target(Box::new(TargetProblem::MissingFile { path })),
222        )
223    }
224
225    fn derive(
226        &self,
227        name: &str,
228        kind: TargetKind,
229        crate_path: String,
230        root: RelPath,
231        origin: Origin,
232        settings: Option<&TargetSettings>,
233    ) -> Derived {
234        let defaults = TargetSettings::default();
235        let settings = settings.unwrap_or(&defaults);
236        let tested = kind != TargetKind::BuildScript;
237        Derived {
238            target: Target {
239                package_id: self.package_id,
240                package: self.package.name.clone(),
241                name: name.to_owned(),
242                kind,
243                crate_path,
244                root,
245                shipping: kind.is_shipping(),
246                harness: settings.harness.unwrap_or(tested),
247                required_features: settings.required_features.clone(),
248                test: settings.test.unwrap_or(matches!(
249                    kind,
250                    TargetKind::Lib | TargetKind::Bin | TargetKind::Test
251                )),
252                doctest: settings.doctest.unwrap_or(kind == TargetKind::Lib),
253            },
254            origin,
255        }
256    }
257
258    fn key(table: &str, field: &str) -> Origin {
259        Origin::ManifestKey {
260            key: format!("{table}.{field}"),
261        }
262    }
263
264    /// The root of the first existing candidate, or of the only one that
265    /// exists; two candidates that both exist are ambiguous.
266    fn pick(&self, candidates: &[String], origin: &Origin) -> Result<Option<RelPath>, LoadError> {
267        let mut found: Vec<RelPath> = Vec::new();
268        for candidate in candidates {
269            let path = self.join(candidate, origin)?;
270            if self.is_file(&path, origin)? {
271                found.push(path);
272            }
273        }
274        match found.as_slice() {
275            [] => Ok(None),
276            [only] => Ok(Some(only.clone())),
277            [first, second, ..] => Err(self.error(
278                origin,
279                LoadErrorKind::Target(Box::new(TargetProblem::AmbiguousRoot {
280                    first: first.clone(),
281                    second: second.clone(),
282                })),
283            )),
284        }
285    }
286
287    fn library(&self, out: &mut Vec<Derived>) -> Result<(), LoadError> {
288        let explicit = self.manifest.lib.as_ref();
289        // `autolib = false` leaves `src/lib.rs` undiscovered; only an explicit
290        // `[lib]` makes a library, as `library_target_name` also decides.
291        if explicit.is_none() && !self.package.auto("lib") {
292            return Ok(());
293        }
294        let written = explicit.and_then(|lib| lib.path.as_deref());
295        // The key that led to the root: `lib.path` when the manifest names
296        // the file, the `[lib]` table when it only declares the library, and
297        // discovery for the default library of a package without `[lib]`.
298        let origin = match (written, explicit) {
299            (Some(_), _) => Self::key("lib", "path"),
300            (None, Some(_)) => Origin::ManifestKey {
301                key: "lib".to_owned(),
302            },
303            (None, None) => Origin::Discovery,
304        };
305        let relative = written.unwrap_or("src/lib.rs");
306        let root = self.join(relative, &origin)?;
307        if self.is_file(&root, &origin)? {
308            let name = explicit
309                .and_then(|lib| lib.name.clone())
310                .unwrap_or_else(|| self.package.name.clone());
311            let crate_path = ident(&name);
312            let settings = explicit.map(|lib| &lib.settings);
313            out.push(self.derive(&name, TargetKind::Lib, crate_path, root, origin, settings));
314            Ok(())
315        } else if explicit.is_some() {
316            Err(self.missing(root, &origin))
317        } else {
318            Ok(())
319        }
320    }
321
322    fn binaries(&self, out: &mut Vec<Derived>) -> Result<(), LoadError> {
323        let package = &self.package.name;
324        for declared in &self.manifest.bins {
325            let name = declared.name.clone().ok_or_else(|| self.no_name("bin"))?;
326            let (origin, root) = if let Some(path) = &declared.path {
327                let origin = Self::key("bin", "path");
328                let root = self.join(path, &origin)?;
329                if !self.is_file(&root, &origin)? {
330                    return Err(self.missing(root, &origin));
331                }
332                (origin, root)
333            } else {
334                let origin = Self::key("bin", "name");
335                let mut candidates = Vec::new();
336                if &name == package {
337                    candidates.push("src/main.rs".to_owned());
338                }
339                candidates.push(format!("src/bin/{name}.rs"));
340                candidates.push(format!("src/bin/{name}/main.rs"));
341                let Some(root) = self.pick(&candidates, &origin)? else {
342                    let first = self.join(&candidates[0], &origin)?;
343                    return Err(self.missing(first, &origin));
344                };
345                (origin, root)
346            };
347            let crate_path = format!("{}::bin_crate::{}", ident(package), ident(&name));
348            out.push(self.derive(
349                &name,
350                TargetKind::Bin,
351                crate_path,
352                root,
353                origin,
354                Some(&declared.settings),
355            ));
356        }
357        if !self.package.auto("bin") {
358            return Ok(());
359        }
360        let origin = Origin::Discovery;
361        let main = self.join("src/main.rs", &origin)?;
362        if self.is_file(&main, &origin)? {
363            self.add_inferred(out, package, TargetKind::Bin, main);
364        }
365        self.infer_from("src/bin", TargetKind::Bin, out)
366    }
367
368    fn no_name(&self, table: &str) -> LoadError {
369        self.error(
370            &Self::key(table, "name"),
371            LoadErrorKind::Target(Box::new(TargetProblem::NoName)),
372        )
373    }
374
375    /// Add an inferred target unless an explicit one has its name or root.
376    fn add_inferred(&self, out: &mut Vec<Derived>, name: &str, kind: TargetKind, root: RelPath) {
377        let taken = out
378            .iter()
379            .any(|d| d.target.kind == kind && (d.target.name == name || d.target.root == root));
380        if !taken {
381            let crate_path = self.crate_path(kind, name);
382            out.push(self.derive(name, kind, crate_path, root, Origin::Discovery, None));
383        }
384    }
385
386    fn crate_path(&self, kind: TargetKind, name: &str) -> String {
387        let package = ident(&self.package.name);
388        let segment = match kind {
389            TargetKind::Bin => "bin_crate",
390            TargetKind::Test => "test_crate",
391            TargetKind::Bench => "bench_crate",
392            TargetKind::Example => "example_crate",
393            TargetKind::Lib | TargetKind::BuildScript => return ident(name),
394        };
395        format!("{package}::{segment}::{}", ident(name))
396    }
397
398    /// Inferred targets of a directory: `*.rs` files and `*/main.rs`.
399    fn infer_from(
400        &self,
401        directory: &str,
402        kind: TargetKind,
403        out: &mut Vec<Derived>,
404    ) -> Result<(), LoadError> {
405        let origin = Origin::Discovery;
406        for entry in self.list(directory)? {
407            match entry.kind {
408                EntryKind::File | EntryKind::Symlink => {
409                    if let Some(stem) = entry.name.strip_suffix(".rs") {
410                        let root = self.join(&format!("{directory}/{}", entry.name), &origin)?;
411                        self.add_inferred(out, stem, kind, root);
412                    }
413                }
414                EntryKind::Dir => {
415                    let root =
416                        self.join(&format!("{directory}/{}/main.rs", entry.name), &origin)?;
417                    if self.is_file(&root, &origin)? {
418                        self.add_inferred(out, &entry.name, kind, root);
419                    }
420                }
421                EntryKind::Other => {}
422            }
423        }
424        Ok(())
425    }
426
427    fn examples_like(
428        &self,
429        table: &str,
430        directory: &str,
431        kind: TargetKind,
432        declared: &[TargetDecl],
433        auto: bool,
434        out: &mut Vec<Derived>,
435    ) -> Result<(), LoadError> {
436        for target in declared {
437            let name = target.name.clone().ok_or_else(|| self.no_name(table))?;
438            let (origin, root) = if let Some(path) = &target.path {
439                let origin = Self::key(table, "path");
440                let root = self.join(path, &origin)?;
441                if !self.is_file(&root, &origin)? {
442                    return Err(self.missing(root, &origin));
443                }
444                (origin, root)
445            } else {
446                let origin = Self::key(table, "name");
447                let candidates = [
448                    format!("{directory}/{name}.rs"),
449                    format!("{directory}/{name}/main.rs"),
450                ];
451                let Some(root) = self.pick(&candidates, &origin)? else {
452                    let first = self.join(&candidates[0], &origin)?;
453                    return Err(self.missing(first, &origin));
454                };
455                (origin, root)
456            };
457            let crate_path = self.crate_path(kind, &name);
458            out.push(self.derive(
459                &name,
460                kind,
461                crate_path,
462                root,
463                origin,
464                Some(&target.settings),
465            ));
466        }
467        if auto {
468            self.infer_from(directory, kind, out)?;
469        }
470        Ok(())
471    }
472
473    fn build_script(&self, out: &mut Vec<Derived>) -> Result<(), LoadError> {
474        let (origin, relative) = match &self.package.build {
475            Build::Disabled => return Ok(()),
476            Build::Path(path) => (Self::key("package", "build"), path.as_str()),
477            Build::Default => (Origin::Discovery, "build.rs"),
478        };
479        let root = self.join(relative, &origin)?;
480        if self.is_file(&root, &origin)? {
481            let crate_path = format!("{}::build_script", ident(&self.package.name));
482            out.push(self.derive(
483                "build-script-build",
484                TargetKind::BuildScript,
485                crate_path,
486                root,
487                origin,
488                None,
489            ));
490            Ok(())
491        } else if matches!(self.package.build, Build::Path(_)) {
492            Err(self.missing(root, &origin))
493        } else {
494            Ok(())
495        }
496    }
497}
498
499/// Derive every target of a package, in a fixed order: library, binaries,
500/// tests, benches, examples, build script.
501///
502/// # Errors
503///
504/// Returns a [`LoadError`] naming the manifest key at fault when a target has
505/// no name, an explicit file is missing, a path leaves the tree, or two
506/// targets share a root.
507pub(crate) fn derive_targets(context: &Context<'_>) -> Result<Vec<Derived>, LoadError> {
508    let mut out = Vec::new();
509    context.library(&mut out)?;
510    context.binaries(&mut out)?;
511    let manifest = context.manifest;
512    let package = context.package;
513    context.examples_like(
514        "test",
515        "tests",
516        TargetKind::Test,
517        &manifest.tests,
518        package.auto("test"),
519        &mut out,
520    )?;
521    context.examples_like(
522        "bench",
523        "benches",
524        TargetKind::Bench,
525        &manifest.benches,
526        package.auto("bench"),
527        &mut out,
528    )?;
529    context.examples_like(
530        "example",
531        "examples",
532        TargetKind::Example,
533        &manifest.examples,
534        package.auto("example"),
535        &mut out,
536    )?;
537    context.build_script(&mut out)?;
538    for (index, derived) in out.iter().enumerate() {
539        if let Some(first) = out[..index]
540            .iter()
541            .find(|earlier| earlier.target.root == derived.target.root)
542        {
543            return Err(context.error(
544                &derived.origin,
545                LoadErrorKind::Target(Box::new(TargetProblem::SharedRoot {
546                    root: derived.target.root.clone(),
547                    other: first.target.name.clone(),
548                })),
549            ));
550        }
551    }
552    Ok(out)
553}
554
555/// Refuse two targets of one package that share a crate path. Targets of
556/// different packages may share one: the index keys crates by package.
557///
558/// # Errors
559///
560/// Returns a [`LoadError`] on the manifest of the later target, naming the
561/// manifest key that declared it and the earlier target.
562pub(crate) fn check_crate_paths(derived: &[(&RelPath, Derived)]) -> Result<(), LoadError> {
563    for (index, (manifest, later)) in derived.iter().enumerate() {
564        if let Some((first_manifest, first)) = derived[..index].iter().find(|(_, earlier)| {
565            earlier.target.package_id == later.target.package_id
566                && earlier.target.crate_path == later.target.crate_path
567        }) {
568            return Err(LoadError::new(
569                manifest,
570                None,
571                LoadErrorKind::Target(Box::new(TargetProblem::DuplicateCratePath {
572                    crate_path: later.target.crate_path.clone(),
573                    other: first.target.name.clone(),
574                    with: (*first_manifest).clone(),
575                })),
576            )
577            .reached_by(&later.origin));
578        }
579    }
580    Ok(())
581}