Skip to main content

ridx_format/workspace/
target_kind.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! Target kinds and authoritative target classification for crate compilation units.
12
13use serde::{Deserialize, Serialize};
14use std::path::Path;
15
16/// Target compilation unit classification within a crate or workspace.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "kebab-case")]
19pub enum TargetKind {
20    /// Library crate (rlib, dylib, cdylib, proc-macro).
21    Lib,
22    /// Executable binary.
23    Bin,
24    /// Integration or unit test harness.
25    Test,
26    /// Benchmark harness.
27    Bench,
28    /// Example binary or library.
29    Example,
30    /// Custom build script (build.rs).
31    CustomBuild,
32    /// Other target type.
33    Other,
34}
35
36impl TargetKind {
37    /// Returns the lowercase canonical identifier string for the target kind.
38    pub fn as_str(&self) -> &'static str {
39        match self {
40            Self::Lib => "lib",
41            Self::Bin => "bin",
42            Self::Test => "test",
43            Self::Bench => "bench",
44            Self::Example => "example",
45            Self::CustomBuild => "custom-build",
46            Self::Other => "other",
47        }
48    }
49
50    /// Returns true if this target represents the primary library compilation unit.
51    pub fn is_lib(&self) -> bool {
52        matches!(self, Self::Lib)
53    }
54
55    /// Parses a string into a TargetKind, matching case-insensitively.
56    pub fn parse(s: &str) -> Option<Self> {
57        let trimmed = s.trim().to_ascii_lowercase();
58        match trimmed.as_str() {
59            "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro" => Some(Self::Lib),
60            "bin" => Some(Self::Bin),
61            "test" => Some(Self::Test),
62            "bench" => Some(Self::Bench),
63            "example" => Some(Self::Example),
64            "custom-build" => Some(Self::CustomBuild),
65            _ => None,
66        }
67    }
68}
69
70impl std::fmt::Display for TargetKind {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.write_str(self.as_str())
73    }
74}
75
76/// Authoritatively classifies a compilation unit based on its `cargo metadata` target kind,
77/// the active rustc compiler arguments, and manifest directory context.
78///
79/// Strictly eliminates path substring heuristics (`/tests/`, `/examples/`, `/benches/`):
80/// 1. If `base_kind` from `cargo metadata` is provided:
81///    - `lib` or `bin` compiled with `--test` becomes `Test` (unit test harness).
82///    - `lib` without `--test` remains `Lib` (even if in `examples/foo/src/lib.rs` or under `/tmp/x/tests/`).
83///    - `bin` remains `Bin` (even if path is `examples/tool.rs`).
84///    - `bench` remains `Bench` (even if compiled with `--crate-type bin` and `harness = false`).
85///    - `test` remains `Test`.
86///    - `example` remains `Example`.
87///    - `custom-build` remains `CustomBuild`.
88/// 2. If `base_kind` is absent (fallback for ad-hoc invocations):
89///    - `--test` -> `Test`.
90///    - If entrypoint relative to `manifest_dir` begins with `benches/`, `examples/`, `tests/`, or equals `build.rs` -> corresponding kind.
91///    - `--crate-type bin` -> `Bin`.
92///    - Default -> `Lib`.
93pub fn classify_target_with_manifest(base_kind: Option<&str>, compiler_args: &[String], manifest_dir: Option<&Path>) -> TargetKind {
94    let has_test_flag = compiler_args.iter().any(|a| a == "--test");
95
96    if let Some(kind) = base_kind {
97        let trimmed = kind.trim().to_ascii_lowercase();
98        match trimmed.as_str() {
99            "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro" => {
100                if has_test_flag {
101                    return TargetKind::Test;
102                } else {
103                    return TargetKind::Lib;
104                }
105            }
106            "bin" => {
107                if has_test_flag {
108                    return TargetKind::Test;
109                } else {
110                    return TargetKind::Bin;
111                }
112            }
113            "test" => return TargetKind::Test,
114            "bench" => return TargetKind::Bench,
115            "example" => return TargetKind::Example,
116            "custom-build" => return TargetKind::CustomBuild,
117            _ => {
118                if has_test_flag {
119                    return TargetKind::Test;
120                } else {
121                    return TargetKind::Lib;
122                }
123            }
124        }
125    }
126
127    if has_test_flag {
128        return TargetKind::Test;
129    }
130
131    if let Some(inferred) = infer_target_from_manifest(compiler_args, manifest_dir) {
132        return inferred;
133    }
134
135    if compiler_args.windows(2).any(|w| w[0] == "--crate-type" && w[1] == "bin") || compiler_args.iter().any(|a| a.starts_with("--crate-type=bin")) {
136        TargetKind::Bin
137    } else {
138        TargetKind::Lib
139    }
140}
141
142/// Backwards-compatible target classifier without manifest directory context.
143pub fn classify_target(base_kind: Option<&str>, compiler_args: &[String]) -> TargetKind {
144    classify_target_with_manifest(base_kind, compiler_args, None)
145}
146
147fn infer_target_from_manifest(compiler_args: &[String], manifest_dir: Option<&Path>) -> Option<TargetKind> {
148    let manifest = manifest_dir?;
149    let entry_rs = compiler_args.iter().find(|a| !a.starts_with('-') && a.ends_with(".rs"))?;
150
151    let p = Path::new(entry_rs);
152    let rel = if p.is_relative() {
153        p.to_path_buf()
154    } else {
155        p.strip_prefix(manifest).ok().map(|p| p.to_path_buf()).or_else(|| {
156            if let Ok(canon_p) = std::fs::canonicalize(p) {
157                if let Ok(canon_m) = std::fs::canonicalize(manifest) {
158                    return canon_p.strip_prefix(canon_m).ok().map(|p| p.to_path_buf());
159                }
160            }
161            None
162        })?
163    };
164
165    if rel.starts_with("benches") {
166        Some(TargetKind::Bench)
167    } else if rel.starts_with("examples") {
168        Some(TargetKind::Example)
169    } else if rel.starts_with("tests") {
170        Some(TargetKind::Test)
171    } else if rel == Path::new("build.rs") {
172        Some(TargetKind::CustomBuild)
173    } else {
174        None
175    }
176}