Skip to content

Commit

Permalink
chore: rebase
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbarsky committed May 30, 2024
1 parent e153d32 commit e41b15b
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 37 deletions.
15 changes: 10 additions & 5 deletions crates/project-model/src/project_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use serde::{de, Deserialize, Serialize};
use span::Edition;
use std::path::PathBuf;

use crate::{cfg_flag::CfgFlag, TargetKind};
use crate::{cfg::CfgFlag, ManifestPath, TargetKind};

/// Roots and crates that compose this Rust project.
#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -199,6 +199,11 @@ impl ProjectJson {
.find(|krate| krate.root_module == root)
.cloned()
}

/// Returns the path to the project's manifest or root folder, if no manifest exists.
pub fn manifest_or_root(&self) -> &AbsPath {
self.manifest.as_ref().map_or(&self.project_root, |manifest| manifest.as_ref())
}
}

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -245,14 +250,14 @@ enum EditionData {
Edition2024,
}

#[derive(Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BuildInfoData {
label: String,
target_kind: TargetKindData,
shell_runnables: Vec<ShellRunnableArgs>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShellRunnableArgs {
pub program: String,
Expand All @@ -261,15 +266,15 @@ pub struct ShellRunnableArgs {
pub kind: ShellRunnableKind,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ShellRunnableKind {
Check,
Run,
TestOne,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TargetKindData {
Bin,
Expand Down
2 changes: 1 addition & 1 deletion crates/project-model/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub enum ProjectWorkspaceKind {
/// Environment variables set in the `.cargo/config` file.
cargo_config_extra_env: FxHashMap<String, String>,
},
/// Project workspace was manually specified using a `rust-project.json` file.
/// Project workspace was specified using a `rust-project.json` file.
Json(ProjectJson),
// FIXME: The primary limitation of this approach is that the set of detached files needs to be fixed at the beginning.
// That's not the end user experience we should strive for.
Expand Down
52 changes: 43 additions & 9 deletions crates/rust-analyzer/src/global_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use parking_lot::{
RwLockWriteGuard,
};
use proc_macro_api::ProcMacroServer;
use project_model::{ProjectWorkspace, ProjectWorkspaceKind, WorkspaceBuildScripts};
use project_model::{ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, WorkspaceBuildScripts};
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::{span, Level};
use triomphe::Arc;
Expand Down Expand Up @@ -482,14 +482,48 @@ impl GlobalStateSnapshot {
let file_id = self.analysis.crate_root(crate_id).ok()?;
let path = self.vfs_read().file_path(file_id).clone();
let path = path.as_path()?;
self.workspaces.iter().find_map(|ws| match &ws.kind {
ProjectWorkspaceKind::Cargo { cargo, .. }
| ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _)), .. } => {
cargo.target_by_root(path).map(|it| (cargo, it))
}
ProjectWorkspaceKind::Json { .. } => None,
ProjectWorkspaceKind::DetachedFile { .. } => None,
})

for workspace in self.workspaces.iter() {
match &workspace.kind {
ProjectWorkspaceKind::Cargo { cargo, .. }
| ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _)), .. } => {
let Some(target_idx) = cargo.target_by_root(path) else {
continue;
};

let target_data = &cargo[target_idx];
let package_data = &cargo[target_data.package];

return Some(TargetSpec::Cargo(CargoTargetSpec {
workspace_root: cargo.workspace_root().to_path_buf(),
cargo_toml: package_data.manifest.clone(),
crate_id,
package: cargo.package_flag(package_data),
target: target_data.name.clone(),
target_kind: target_data.kind,
required_features: target_data.required_features.clone(),
features: package_data.features.keys().cloned().collect(),
}));
}
ProjectWorkspaceKind::Json(project) => {
let Some(krate) = project.crate_by_root(path) else {
continue;
};
let Some(build_info) = krate.build_info else {
continue;
};

return Some(TargetSpec::ProjectJson(ProjectJsonTargetSpec {
target_kind: build_info.target_kind,
label: build_info.label,
shell_runnables: build_info.shell_runnables,
}));
}
ProjectWorkspaceKind::DetachedFile { .. } => {}
};
}

None
}

pub(crate) fn file_exists(&self, file_id: FileId) -> bool {
Expand Down
10 changes: 7 additions & 3 deletions crates/rust-analyzer/src/lsp/to_proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1367,8 +1367,12 @@ pub(crate) fn runnable(

let target = spec.target.clone();

let (cargo_args, executable_args) =
CargoTargetSpec::runnable_args(snap, Some(spec), &runnable.kind, &runnable.cfg);
let (cargo_args, executable_args) = CargoTargetSpec::runnable_args(
snap,
Some(spec.clone()),
&runnable.kind,
&runnable.cfg,
);

let cwd = match runnable.kind {
ide::RunnableKind::Bin { .. } => workspace_root.clone(),
Expand All @@ -1394,7 +1398,7 @@ pub(crate) fn runnable(
}))
}
Some(TargetSpec::ProjectJson(spec)) => {
let label = runnable.label(Some(spec.label.clone()));
let label = runnable.label(Some(&spec.label));
let location = location_link(snap, None, runnable.nav)?;

match spec.runnable_args(&runnable.kind) {
Expand Down
12 changes: 9 additions & 3 deletions crates/rust-analyzer/src/target_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,17 +256,23 @@ fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
mod tests {
use super::*;

use mbe::{syntax_node_to_token_tree, DummyTestSpanMap, DUMMY};
use ide::Edition;
use mbe::{syntax_node_to_token_tree, DocCommentDesugarMode, DummyTestSpanMap, DUMMY};
use syntax::{
ast::{self, AstNode},
SmolStr,
};

fn check(cfg: &str, expected_features: &[&str]) {
let cfg_expr = {
let source_file = ast::SourceFile::parse(cfg).ok().unwrap();
let source_file = ast::SourceFile::parse(cfg, Edition::CURRENT).ok().unwrap();
let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
let tt = syntax_node_to_token_tree(tt.syntax(), &DummyTestSpanMap, DUMMY);
let tt = syntax_node_to_token_tree(
tt.syntax(),
&DummyTestSpanMap,
DUMMY,
DocCommentDesugarMode::Mbe,
);
CfgExpr::parse(&tt)
};

Expand Down
18 changes: 8 additions & 10 deletions editors/code/src/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ async function getDebugConfiguration(
}

const env = prepareEnv(runnable.label, runnableArgs, ctx.config.runnablesExtraEnv);
const { executable, workspace: cargoWorkspace } = await getDebugExecutableInfo(
const executable = await getDebugExecutable(
runnableArgs,
env,
);
Expand All @@ -161,9 +161,7 @@ async function getDebugConfiguration(
runnable,
runnableArgs,
simplifyPath(executable),
cargoWorkspace,
env,
sourceFileMap,
);
if (debugConfig.type in debugOptions.engineSettings) {
const settingsMap = (debugOptions.engineSettings as any)[debugConfig.type];
Expand All @@ -190,8 +188,8 @@ async function getDebugExecutable(
runnableArgs: ra.CargoRunnableArgs,
env: Record<string, string>,
): Promise<string> {
const cargo = new Cargo(runnable.args.workspaceRoot || ".", debugOutput, env);
const executable = await cargo.executableFromArgs(runnable.args.cargoArgs);
const cargo = new Cargo(runnableArgs.workspaceRoot || ".", debugOutput, env);
const executable = await cargo.executableFromArgs(runnableArgs.cargoArgs);

// if we are here, there were no compilation errors.
return executable;
Expand All @@ -209,8 +207,8 @@ function getCCppDebugConfig(
request: "launch",
name: runnable.label,
program: executable,
args: runnable.args.executableArgs,
cwd: runnable.args.cwd || runnable.args.workspaceRoot || ".",
args: runnableArgs.executableArgs,
cwd: runnable.args.cwd || runnableArgs.workspaceRoot || ".",
sourceFileMap,
environment: Object.entries(env).map((entry) => ({
name: entry[0],
Expand All @@ -235,8 +233,8 @@ function getCodeLldbDebugConfig(
request: "launch",
name: runnable.label,
program: executable,
args: runnable.args.executableArgs,
cwd: runnable.args.cwd || runnable.args.workspaceRoot || ".",
args: runnableArgs.executableArgs,
cwd: runnable.args.cwd || runnableArgs.workspaceRoot || ".",
sourceMap: sourceFileMap,
sourceLanguages: ["rust"],
env,
Expand All @@ -257,7 +255,7 @@ function getNativeDebugConfig(
target: executable,
// See https://github.com/WebFreak001/code-debug/issues/359
arguments: quote(runnableArgs.executableArgs),
cwd: runnable.args.cwd || runnable.args.workspaceRoot || ".",
cwd: runnable.args.cwd || runnableArgs.workspaceRoot || ".",
env,
valuesFormatting: "prettyPrinters",
};
Expand Down
4 changes: 3 additions & 1 deletion editors/code/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { Config, RunnableEnvCfg, RunnableEnvCfgItem } from "./config";
import { unwrapUndefinable } from "./undefinable";
import type { LanguageClient } from "vscode-languageclient/node";
import type { RustEditor } from "./util";
import * as toolchain from "./toolchain";

const quickPickButtons = [
{ iconPath: new vscode.ThemeIcon("save"), tooltip: "Save as a launch.json configuration." },
Expand Down Expand Up @@ -128,7 +129,7 @@ export async function createTask(runnable: ra.Runnable, config: Config): Promise

definition = {
type: tasks.TASK_TYPE,
program,
command: program,
args,
cwd: runnableArgs.workspaceRoot || ".",
env: prepareEnv(runnable.label, runnableArgs, config.runnablesExtraEnv),
Expand All @@ -138,6 +139,7 @@ export async function createTask(runnable: ra.Runnable, config: Config): Promise

definition = {
type: tasks.TASK_TYPE,
command: runnableArgs.program,
program: runnableArgs.program,
args: runnableArgs.args,
cwd: runnableArgs.cwd,
Expand Down
8 changes: 4 additions & 4 deletions editors/code/src/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const TASK_TYPE = "cargo";

export const TASK_SOURCE = "rust";

export interface CargoTaskDefinition extends vscode.TaskDefinition {
export interface RustTargetDefinition extends vscode.TaskDefinition {
// The cargo command, such as "run" or "check".
command: string;
// Additional arguments passed to the cargo command.
Expand Down Expand Up @@ -69,7 +69,7 @@ class RustTaskProvider implements vscode.TaskProvider {
// we need to inform VSCode how to execute that command by creating
// a ShellExecution for it.

const definition = task.definition as CargoTaskDefinition;
const definition = task.definition as RustTargetDefinition;

if (definition.type === TASK_TYPE) {
return await buildRustTask(
Expand All @@ -87,7 +87,7 @@ class RustTaskProvider implements vscode.TaskProvider {

export async function buildRustTask(
scope: vscode.WorkspaceFolder | vscode.TaskScope | undefined,
definition: CargoTaskDefinition,
definition: RustTargetDefinition,
name: string,
problemMatcher: string[],
customRunner?: string,
Expand All @@ -108,7 +108,7 @@ export async function buildRustTask(
}

async function cargoToExecution(
definition: CargoTaskDefinition,
definition: RustTargetDefinition,
customRunner: string | undefined,
throwOnError: boolean,
): Promise<vscode.ProcessExecution | vscode.ShellExecution> {
Expand Down
3 changes: 2 additions & 1 deletion editors/code/tests/unit/runnable_env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ function makeRunnable(label: string): ra.Runnable {
return {
label,
kind: "cargo",
args: {
args: {
cargoArgs: [],
cwd: ".",
executableArgs: [],
cargoExtraArgs: [],
},
Expand Down

0 comments on commit e41b15b

Please sign in to comment.