Skip to main content

project_model/
lib.rs

1//! In rust-analyzer, we maintain a strict separation between pure abstract
2//! semantic project model and a concrete model of a particular build system.
3//!
4//! Pure model is represented by the `base_db::CrateGraph` from another crate.
5//!
6//! In this crate, we are concerned with "real world" project models.
7//!
8//! Specifically, here we have a representation for a Cargo project
9//! ([`CargoWorkspace`]) and for manually specified layout ([`ProjectJson`]).
10//!
11//! Roughly, the things we do here are:
12//!
13//! * Project discovery (where's the relevant Cargo.toml for the current dir).
14//! * Custom build steps (`build.rs` code generation and compilation of
15//!   procedural macros).
16//! * Lowering of concrete model to a `base_db::CrateGraph`
17
18// It's useful to refer to code that is private in doc comments.
19#![allow(rustdoc::private_intra_doc_links)]
20#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
21
22#[cfg(feature = "in-rust-tree")]
23extern crate rustc_driver as _;
24
25pub mod project_json;
26pub mod toolchain_info {
27    pub mod rustc_cfg;
28    pub mod target_data;
29    pub mod target_tuple;
30    pub mod version;
31
32    use std::path::Path;
33
34    use crate::{ManifestPath, Sysroot, cargo_config_file::CargoConfigFile};
35
36    #[derive(Copy, Clone)]
37    pub enum QueryConfig<'a> {
38        /// Directly invoke `rustc` to query the desired information.
39        Rustc(&'a Sysroot, &'a Path),
40        /// Attempt to use cargo to query the desired information, honoring cargo configurations.
41        /// If this fails, falls back to invoking `rustc` directly.
42        Cargo(&'a Sysroot, &'a ManifestPath, &'a Option<CargoConfigFile>),
43    }
44}
45
46mod build_dependencies;
47mod cargo_config_file;
48mod cargo_workspace;
49mod env;
50mod manifest_path;
51mod sysroot;
52mod workspace;
53
54#[cfg(test)]
55mod tests;
56
57use std::{
58    fmt,
59    fs::{self, ReadDir, read_dir},
60    io,
61    process::Command,
62};
63
64use anyhow::{Context, bail, format_err};
65use paths::{AbsPath, AbsPathBuf, Utf8PathBuf};
66use rustc_hash::FxHashSet;
67
68use base_db::TargetKind;
69
70pub use crate::{
71    build_dependencies::{ProcMacroDylibPath, WorkspaceBuildScripts},
72    cargo_workspace::{
73        CargoConfig, CargoFeatures, CargoMetadataConfig, CargoWorkspace, Package, PackageData,
74        PackageDependency, RustLibSource, Target, TargetData, TargetDirectoryConfig,
75    },
76    manifest_path::ManifestPath,
77    project_json::{ProjectJson, ProjectJsonData},
78    sysroot::Sysroot,
79    workspace::{FileLoader, PackageRoot, ProjectWorkspace, ProjectWorkspaceKind},
80};
81pub use cargo_metadata::Metadata;
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct ProjectJsonFromCommand {
85    /// The data describing this project, such as its dependencies.
86    pub data: ProjectJsonData,
87    /// The build system specific file that describes this project,
88    /// such as a `my-project/BUCK` file.
89    pub buildfile: AbsPathBuf,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
93pub enum ProjectManifest {
94    ProjectJson(ManifestPath),
95    CargoToml(ManifestPath),
96    CargoScript(ManifestPath),
97}
98
99impl ProjectManifest {
100    pub fn from_manifest_file(path: AbsPathBuf) -> anyhow::Result<ProjectManifest> {
101        let path = ManifestPath::try_from(path)
102            .map_err(|path| format_err!("bad manifest path: {path}"))?;
103        if path.file_name().unwrap_or_default() == "rust-project.json" {
104            return Ok(ProjectManifest::ProjectJson(path));
105        }
106        if path.file_name().unwrap_or_default() == ".rust-project.json" {
107            return Ok(ProjectManifest::ProjectJson(path));
108        }
109        if path.file_name().unwrap_or_default() == "Cargo.toml" {
110            return Ok(ProjectManifest::CargoToml(path));
111        }
112        if path.extension().unwrap_or_default() == "rs" {
113            return Ok(ProjectManifest::CargoScript(path));
114        }
115        bail!(
116            "project root must point to a Cargo.toml, rust-project.json or <script>.rs file: {path}"
117        );
118    }
119
120    pub fn discover_single(path: &AbsPath) -> anyhow::Result<ProjectManifest> {
121        let mut candidates = ProjectManifest::discover(path)?;
122        let res = match candidates.pop() {
123            None => bail!("no projects"),
124            Some(it) => it,
125        };
126
127        if !candidates.is_empty() {
128            bail!("more than one project");
129        }
130        Ok(res)
131    }
132
133    pub fn discover(path: &AbsPath) -> io::Result<Vec<ProjectManifest>> {
134        if let Some(project_json) = find_in_parent_dirs(path, "rust-project.json") {
135            return Ok(vec![ProjectManifest::ProjectJson(project_json)]);
136        }
137        if let Some(project_json) = find_in_parent_dirs(path, ".rust-project.json") {
138            return Ok(vec![ProjectManifest::ProjectJson(project_json)]);
139        }
140        return find_cargo_toml(path)
141            .map(|paths| paths.into_iter().map(ProjectManifest::CargoToml).collect());
142
143        fn find_cargo_toml(path: &AbsPath) -> io::Result<Vec<ManifestPath>> {
144            match find_in_parent_dirs(path, "Cargo.toml") {
145                Some(it) => Ok(vec![it]),
146                None => Ok(find_cargo_toml_in_child_dir(read_dir(path)?)),
147            }
148        }
149
150        fn find_in_parent_dirs(path: &AbsPath, target_file_name: &str) -> Option<ManifestPath> {
151            if path.file_name().unwrap_or_default() == target_file_name
152                && let Ok(manifest) = ManifestPath::try_from(path.to_path_buf())
153            {
154                return Some(manifest);
155            }
156
157            let mut curr = Some(path);
158
159            while let Some(path) = curr {
160                let candidate = path.join(target_file_name);
161                if fs::metadata(&candidate).is_ok()
162                    && let Ok(manifest) = ManifestPath::try_from(candidate)
163                {
164                    return Some(manifest);
165                }
166
167                curr = path.parent();
168            }
169
170            None
171        }
172
173        fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec<ManifestPath> {
174            // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects
175            entities
176                .filter_map(Result::ok)
177                .map(|it| it.path().join("Cargo.toml"))
178                .filter(|it| it.exists())
179                .map(Utf8PathBuf::from_path_buf)
180                .filter_map(Result::ok)
181                .map(AbsPathBuf::try_from)
182                .filter_map(Result::ok)
183                .filter_map(|it| it.try_into().ok())
184                .collect()
185        }
186    }
187
188    pub fn discover_all(paths: &[AbsPathBuf]) -> Vec<ProjectManifest> {
189        let mut res = paths
190            .iter()
191            .filter_map(|it| ProjectManifest::discover(it.as_ref()).ok())
192            .flatten()
193            .collect::<FxHashSet<_>>()
194            .into_iter()
195            .collect::<Vec<_>>();
196        res.sort();
197        res
198    }
199
200    pub fn manifest_path(&self) -> &ManifestPath {
201        match self {
202            ProjectManifest::ProjectJson(it)
203            | ProjectManifest::CargoToml(it)
204            | ProjectManifest::CargoScript(it) => it,
205        }
206    }
207}
208
209impl fmt::Display for ProjectManifest {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        fmt::Display::fmt(self.manifest_path(), f)
212    }
213}
214
215fn utf8_stdout(cmd: &mut Command) -> anyhow::Result<String> {
216    let output = cmd.output().with_context(|| format!("{cmd:?} failed"))?;
217    if !output.status.success() {
218        match String::from_utf8(output.stderr) {
219            Ok(stderr) if !stderr.is_empty() => {
220                bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr)
221            }
222            _ => bail!("{:?} failed, {}", cmd, output.status),
223        }
224    }
225    let stdout = String::from_utf8(output.stdout)?;
226    Ok(stdout.trim().to_owned())
227}
228
229#[derive(Clone, Debug, Default, PartialEq, Eq)]
230pub enum InvocationStrategy {
231    Once,
232    #[default]
233    PerWorkspace,
234}
235
236/// A set of cfg-overrides per crate.
237#[derive(Default, Debug, Clone, Eq, PartialEq)]
238pub struct CfgOverrides {
239    /// A global set of overrides matching all crates.
240    pub global: cfg::CfgDiff,
241    /// A set of overrides matching specific crates.
242    pub selective: rustc_hash::FxHashMap<String, cfg::CfgDiff>,
243}
244
245impl CfgOverrides {
246    pub fn len(&self) -> usize {
247        self.global.len() + self.selective.values().map(|it| it.len()).sum::<usize>()
248    }
249
250    pub fn apply(&self, cfg_options: &mut cfg::CfgOptions, name: &str) {
251        if !self.global.is_empty() {
252            cfg_options.apply_diff(self.global.clone());
253        };
254        if let Some(diff) = self.selective.get(name) {
255            cfg_options.apply_diff(diff.clone());
256        };
257    }
258}
259
260fn parse_cfg(s: &str) -> Result<cfg::CfgAtom, String> {
261    let res = match s.split_once('=') {
262        Some((key, value)) => {
263            if !(value.starts_with('"') && value.ends_with('"')) {
264                return Err(format!("Invalid cfg ({s:?}), value should be in quotes"));
265            }
266            let key = intern::Symbol::intern(key);
267            let value = intern::Symbol::intern(&value[1..value.len() - 1]);
268            cfg::CfgAtom::KeyValue { key, value }
269        }
270        None => cfg::CfgAtom::Flag(intern::Symbol::intern(s)),
271    };
272    Ok(res)
273}
274
275#[derive(Clone, Debug, PartialEq, Eq)]
276pub enum RustSourceWorkspaceConfig {
277    CargoMetadata(CargoMetadataConfig),
278    Json(ProjectJson),
279}
280
281impl Default for RustSourceWorkspaceConfig {
282    fn default() -> Self {
283        RustSourceWorkspaceConfig::default_cargo()
284    }
285}
286
287impl RustSourceWorkspaceConfig {
288    pub fn default_cargo() -> Self {
289        RustSourceWorkspaceConfig::CargoMetadata(Default::default())
290    }
291}