From 98e7b944fcbf1439d9f99581ea35f37760e02aa9 Mon Sep 17 00:00:00 2001 From: Mark Pots Date: Mon, 23 Jun 2025 21:27:26 +0200 Subject: feat: Extend vscode 'run' command with optional mode argument for running test(s) or bin at keyboard cursor --- .../rust-analyzer/editors/code/src/commands.ts | 4 +- src/tools/rust-analyzer/editors/code/src/ctx.ts | 13 ++++- src/tools/rust-analyzer/editors/code/src/run.ts | 57 ++++++++++++++++++++++ 3 files changed, 70 insertions(+), 4 deletions(-) (limited to 'src/tools/rust-analyzer/editors/code') diff --git a/src/tools/rust-analyzer/editors/code/src/commands.ts b/src/tools/rust-analyzer/editors/code/src/commands.ts index 3ac1a933d9e..25b30013fa1 100644 --- a/src/tools/rust-analyzer/editors/code/src/commands.ts +++ b/src/tools/rust-analyzer/editors/code/src/commands.ts @@ -1114,11 +1114,11 @@ export function applySnippetWorkspaceEditCommand(_ctx: CtxInit): Cmd { }; } -export function run(ctx: CtxInit): Cmd { +export function run(ctx: CtxInit, mode?: "cursor"): Cmd { let prevRunnable: RunnableQuickPick | undefined; return async () => { - const item = await selectRunnable(ctx, prevRunnable); + const item = await selectRunnable(ctx, prevRunnable, false, true, mode); if (!item) return; item.detail = "rerun"; diff --git a/src/tools/rust-analyzer/editors/code/src/ctx.ts b/src/tools/rust-analyzer/editors/code/src/ctx.ts index e55754fb9f0..0fb0a1f17cb 100644 --- a/src/tools/rust-analyzer/editors/code/src/ctx.ts +++ b/src/tools/rust-analyzer/editors/code/src/ctx.ts @@ -1,6 +1,7 @@ import * as vscode from "vscode"; import type * as lc from "vscode-languageclient/node"; import * as ra from "./lsp_ext"; +import * as commands from "./commands"; import { Config, prepareVSCodeConfig } from "./config"; import { createClient } from "./client"; @@ -462,9 +463,17 @@ export class Ctx implements RustAnalyzerExtensionApi { for (const [name, factory] of Object.entries(this.commandFactories)) { const fullName = `rust-analyzer.${name}`; let callback; + if (isClientRunning(this)) { - // we asserted that `client` is defined - callback = factory.enabled(this); + if (name === "run") { + // Special case: support optional argument for `run` + callback = (mode?: "cursor") => { + return commands.run(this, mode)(); + }; + } else { + // we asserted that `client` is defined + callback = factory.enabled(this); + } } else if (factory.disabled) { callback = factory.disabled(this); } else { diff --git a/src/tools/rust-analyzer/editors/code/src/run.ts b/src/tools/rust-analyzer/editors/code/src/run.ts index 40027cc7c85..95166c427b2 100644 --- a/src/tools/rust-analyzer/editors/code/src/run.ts +++ b/src/tools/rust-analyzer/editors/code/src/run.ts @@ -18,10 +18,15 @@ export async function selectRunnable( prevRunnable?: RunnableQuickPick, debuggeeOnly = false, showButtons: boolean = true, + mode?: "cursor", ): Promise { const editor = ctx.activeRustEditor ?? ctx.activeCargoTomlEditor; if (!editor) return; + if (mode === "cursor") { + return selectRunnableAtCursor(ctx, editor, prevRunnable); + } + // show a placeholder while we get the runnables from the server const quickPick = vscode.window.createQuickPick(); quickPick.title = "Select Runnable"; @@ -54,6 +59,58 @@ export async function selectRunnable( ); } +async function selectRunnableAtCursor( + ctx: CtxInit, + editor: RustEditor, + prevRunnable?: RunnableQuickPick, +): Promise { + const runnableQuickPicks = await getRunnables(ctx.client, editor, prevRunnable, false); + let runnableQuickPickAtCursor = null; + const cursorPosition = ctx.client.code2ProtocolConverter.asPosition(editor.selection.active); + for (const runnableQuickPick of runnableQuickPicks) { + if (!runnableQuickPick.runnable.location?.targetRange) { + continue; + } + const runnableQuickPickRange = runnableQuickPick.runnable.location.targetRange; + if ( + runnableQuickPickAtCursor?.runnable?.location?.targetRange != null && + rangeContainsOtherRange( + runnableQuickPickRange, + runnableQuickPickAtCursor.runnable.location.targetRange, + ) + ) { + continue; + } + if (rangeContainsPosition(runnableQuickPickRange, cursorPosition)) { + runnableQuickPickAtCursor = runnableQuickPick; + } + } + if (runnableQuickPickAtCursor == null) { + return; + } + return Promise.resolve(runnableQuickPickAtCursor); +} + +function rangeContainsPosition(range: lc.Range, position: lc.Position): boolean { + return ( + (position.line > range.start.line || + (position.line === range.start.line && position.character >= range.start.character)) && + (position.line < range.end.line || + (position.line === range.end.line && position.character <= range.end.character)) + ); +} + +function rangeContainsOtherRange(range: lc.Range, otherRange: lc.Range) { + return ( + (range.start.line < otherRange.start.line || + (range.start.line === otherRange.start.line && + range.start.character <= otherRange.start.character)) && + (range.end.line > otherRange.end.line || + (range.end.line === otherRange.end.line && + range.end.character >= otherRange.end.character)) + ); +} + export class RunnableQuickPick implements vscode.QuickPickItem { public label: string; public description?: string | undefined; -- cgit 1.4.1-3-g733a5 From 7eb776e22eff6704df27c7023f289ef04fec12d7 Mon Sep 17 00:00:00 2001 From: Mark Pots Date: Tue, 24 Jun 2025 11:56:22 +0200 Subject: Remove special casing in command factory (revert changes in ctx.ts), update main.createCommands instead --- src/tools/rust-analyzer/editors/code/src/ctx.ts | 13 ++----------- src/tools/rust-analyzer/editors/code/src/main.ts | 2 +- 2 files changed, 3 insertions(+), 12 deletions(-) (limited to 'src/tools/rust-analyzer/editors/code') diff --git a/src/tools/rust-analyzer/editors/code/src/ctx.ts b/src/tools/rust-analyzer/editors/code/src/ctx.ts index 0fb0a1f17cb..e55754fb9f0 100644 --- a/src/tools/rust-analyzer/editors/code/src/ctx.ts +++ b/src/tools/rust-analyzer/editors/code/src/ctx.ts @@ -1,7 +1,6 @@ import * as vscode from "vscode"; import type * as lc from "vscode-languageclient/node"; import * as ra from "./lsp_ext"; -import * as commands from "./commands"; import { Config, prepareVSCodeConfig } from "./config"; import { createClient } from "./client"; @@ -463,17 +462,9 @@ export class Ctx implements RustAnalyzerExtensionApi { for (const [name, factory] of Object.entries(this.commandFactories)) { const fullName = `rust-analyzer.${name}`; let callback; - if (isClientRunning(this)) { - if (name === "run") { - // Special case: support optional argument for `run` - callback = (mode?: "cursor") => { - return commands.run(this, mode)(); - }; - } else { - // we asserted that `client` is defined - callback = factory.enabled(this); - } + // we asserted that `client` is defined + callback = factory.enabled(this); } else if (factory.disabled) { callback = factory.disabled(this); } else { diff --git a/src/tools/rust-analyzer/editors/code/src/main.ts b/src/tools/rust-analyzer/editors/code/src/main.ts index 5e500730693..996298524f1 100644 --- a/src/tools/rust-analyzer/editors/code/src/main.ts +++ b/src/tools/rust-analyzer/editors/code/src/main.ts @@ -167,7 +167,7 @@ function createCommands(): Record { viewCrateGraph: { enabled: commands.viewCrateGraph }, viewFullCrateGraph: { enabled: commands.viewFullCrateGraph }, expandMacro: { enabled: commands.expandMacro }, - run: { enabled: commands.run }, + run: { enabled: (ctx) => (mode?: "cursor") => commands.run(ctx, mode)() }, copyRunCommandLine: { enabled: commands.copyRunCommandLine }, debug: { enabled: commands.debug }, newDebugConfig: { enabled: commands.newDebugConfig }, -- cgit 1.4.1-3-g733a5 From 62e112a780a25dbaba783324d8ecd7929076674a Mon Sep 17 00:00:00 2001 From: roifewu Date: Wed, 9 Apr 2025 11:29:05 +0800 Subject: feat: highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`) --- .../crates/ide/src/goto_definition.rs | 210 +++++++++++++ .../crates/ide/src/highlight_related.rs | 333 ++++++++++++++++++++- .../rust-analyzer/crates/ide/src/references.rs | 221 +++++++++++++- .../crates/rust-analyzer/src/config.rs | 3 + .../docs/book/src/configuration_generated.md | 7 + src/tools/rust-analyzer/editors/code/package.json | 10 + 6 files changed, 775 insertions(+), 9 deletions(-) (limited to 'src/tools/rust-analyzer/editors/code') diff --git a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs index 574803fb9e8..0efc6cfe9b7 100644 --- a/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs +++ b/src/tools/rust-analyzer/crates/ide/src/goto_definition.rs @@ -298,6 +298,7 @@ fn handle_control_flow_keywords( T![for] if token.parent().and_then(ast::ForExpr::cast).is_some() => { nav_for_break_points(sema, token) } + T![match] | T![=>] | T![if] => nav_for_branches(sema, token), _ => None, } } @@ -407,6 +408,64 @@ fn nav_for_exit_points( Some(navs) } +fn nav_for_branches( + sema: &Semantics<'_, RootDatabase>, + token: &SyntaxToken, +) -> Option> { + let db = sema.db; + + let navs = match token.kind() { + T![match] => sema + .descend_into_macros(token.clone()) + .into_iter() + .filter_map(|token| { + let match_expr = + sema.token_ancestors_with_macros(token).find_map(ast::MatchExpr::cast)?; + let file_id = sema.hir_file_for(match_expr.syntax()); + let focus_range = match_expr.match_token()?.text_range(); + let match_expr_in_file = InFile::new(file_id, match_expr.into()); + Some(expr_to_nav(db, match_expr_in_file, Some(focus_range))) + }) + .flatten() + .collect_vec(), + + T![=>] => sema + .descend_into_macros(token.clone()) + .into_iter() + .filter_map(|token| { + let match_arm = + sema.token_ancestors_with_macros(token).find_map(ast::MatchArm::cast)?; + let match_expr = sema + .ancestors_with_macros(match_arm.syntax().clone()) + .find_map(ast::MatchExpr::cast)?; + let file_id = sema.hir_file_for(match_expr.syntax()); + let focus_range = match_arm.fat_arrow_token()?.text_range(); + let match_expr_in_file = InFile::new(file_id, match_expr.into()); + Some(expr_to_nav(db, match_expr_in_file, Some(focus_range))) + }) + .flatten() + .collect_vec(), + + T![if] => sema + .descend_into_macros(token.clone()) + .into_iter() + .filter_map(|token| { + let if_expr = + sema.token_ancestors_with_macros(token).find_map(ast::IfExpr::cast)?; + let file_id = sema.hir_file_for(if_expr.syntax()); + let focus_range = if_expr.if_token()?.text_range(); + let if_expr_in_file = InFile::new(file_id, if_expr.into()); + Some(expr_to_nav(db, if_expr_in_file, Some(focus_range))) + }) + .flatten() + .collect_vec(), + + _ => return Some(Vec::new()), + }; + + Some(navs) +} + pub(crate) fn find_loops( sema: &Semantics<'_, RootDatabase>, token: &SyntaxToken, @@ -3614,4 +3673,155 @@ fn foo() { "#, ); } + + #[test] + fn goto_def_for_match_keyword() { + check( + r#" +fn main() { + match$0 0 { + // ^^^^^ + 0 => {}, + _ => {}, + } +} +"#, + ); + } + + #[test] + fn goto_def_for_match_arm_fat_arrow() { + check( + r#" +fn main() { + match 0 { + 0 =>$0 {}, + // ^^ + _ => {}, + } +} +"#, + ); + } + + #[test] + fn goto_def_for_if_keyword() { + check( + r#" +fn main() { + if$0 true { + // ^^ + () + } +} +"#, + ); + } + + #[test] + fn goto_def_for_match_nested_in_if() { + check( + r#" +fn main() { + if true { + match$0 0 { + // ^^^^^ + 0 => {}, + _ => {}, + } + } +} +"#, + ); + } + + #[test] + fn goto_def_for_multiple_match_expressions() { + check( + r#" +fn main() { + match 0 { + 0 => {}, + _ => {}, + }; + + match$0 1 { + // ^^^^^ + 1 => {}, + _ => {}, + } +} +"#, + ); + } + + #[test] + fn goto_def_for_nested_match_expressions() { + check( + r#" +fn main() { + match 0 { + 0 => match$0 1 { + // ^^^^^ + 1 => {}, + _ => {}, + }, + _ => {}, + } +} +"#, + ); + } + + #[test] + fn goto_def_for_if_else_chains() { + check( + r#" +fn main() { + if true { + () + } else if$0 false { + // ^^ + () + } else { + () + } +} +"#, + ); + } + + #[test] + fn goto_def_for_match_with_guards() { + check( + r#" +fn main() { + match 42 { + x if x > 0 =>$0 {}, + // ^^ + _ => {}, + } +} +"#, + ); + } + + #[test] + fn goto_def_for_match_with_macro_arm() { + check( + r#" +macro_rules! arm { + () => { 0 => {} }; +} + +fn main() { + match$0 0 { + // ^^^^^ + arm!(), + _ => {}, + } +} +"#, + ); + } } diff --git a/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs b/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs index aa947921a9b..8d93cd63283 100644 --- a/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs +++ b/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs @@ -37,8 +37,11 @@ pub struct HighlightRelatedConfig { pub break_points: bool, pub closure_captures: bool, pub yield_points: bool, + pub branches: bool, } +type HighlightMap = FxHashMap>; + // Feature: Highlight Related // // Highlights constructs related to the thing under the cursor: @@ -64,7 +67,7 @@ pub(crate) fn highlight_related( let token = pick_best_token(syntax.token_at_offset(offset), |kind| match kind { T![?] => 4, // prefer `?` when the cursor is sandwiched like in `await$0?` - T![->] => 4, + T![->] | T![=>] => 4, kind if kind.is_keyword(file_id.edition(sema.db)) => 3, IDENT | INT_NUMBER => 2, T![|] => 1, @@ -78,6 +81,9 @@ pub(crate) fn highlight_related( T![fn] | T![return] | T![->] if config.exit_points => { highlight_exit_points(sema, token).remove(&file_id) } + T![match] | T![=>] | T![if] if config.branches => { + highlight_branches(sema, token).remove(&file_id) + } T![await] | T![async] if config.yield_points => { highlight_yield_points(sema, token).remove(&file_id) } @@ -300,11 +306,122 @@ fn highlight_references( if res.is_empty() { None } else { Some(res.into_iter().collect()) } } +pub(crate) fn highlight_branches( + sema: &Semantics<'_, RootDatabase>, + token: SyntaxToken, +) -> FxHashMap> { + let mut highlights: HighlightMap = FxHashMap::default(); + + let push_to_highlights = |file_id, range, highlights: &mut HighlightMap| { + if let Some(FileRange { file_id, range }) = original_frange(sema.db, file_id, range) { + let hrange = HighlightedRange { category: ReferenceCategory::empty(), range }; + highlights.entry(file_id).or_default().insert(hrange); + } + }; + + let push_tail_expr = |tail: Option, highlights: &mut HighlightMap| { + let Some(tail) = tail else { + return; + }; + + for_each_tail_expr(&tail, &mut |tail| { + let file_id = sema.hir_file_for(tail.syntax()); + let range = tail.syntax().text_range(); + push_to_highlights(file_id, Some(range), highlights); + }); + }; + + match token.kind() { + T![match] => { + for token in sema.descend_into_macros(token.clone()) { + let Some(match_expr) = + sema.token_ancestors_with_macros(token).find_map(ast::MatchExpr::cast) + else { + continue; + }; + + let file_id = sema.hir_file_for(match_expr.syntax()); + let range = match_expr.match_token().map(|token| token.text_range()); + push_to_highlights(file_id, range, &mut highlights); + + let Some(arm_list) = match_expr.match_arm_list() else { + continue; + }; + + for arm in arm_list.arms() { + push_tail_expr(arm.expr(), &mut highlights); + } + } + } + T![=>] => { + for token in sema.descend_into_macros(token.clone()) { + let Some(arm) = + sema.token_ancestors_with_macros(token).find_map(ast::MatchArm::cast) + else { + continue; + }; + let file_id = sema.hir_file_for(arm.syntax()); + let range = arm.fat_arrow_token().map(|token| token.text_range()); + push_to_highlights(file_id, range, &mut highlights); + + push_tail_expr(arm.expr(), &mut highlights); + } + } + T![if] => { + for tok in sema.descend_into_macros(token.clone()) { + let Some(if_expr) = + sema.token_ancestors_with_macros(tok).find_map(ast::IfExpr::cast) + else { + continue; + }; + + // Find the root of the if expression + let mut if_to_process = iter::successors(Some(if_expr.clone()), |if_expr| { + let parent_if = if_expr.syntax().parent().and_then(ast::IfExpr::cast)?; + if let ast::ElseBranch::IfExpr(nested_if) = parent_if.else_branch()? { + (nested_if.syntax() == if_expr.syntax()).then_some(parent_if) + } else { + None + } + }) + .last() + .or(Some(if_expr)); + + while let Some(cur_if) = if_to_process.take() { + let file_id = sema.hir_file_for(cur_if.syntax()); + + let if_kw_range = cur_if.if_token().map(|token| token.text_range()); + push_to_highlights(file_id, if_kw_range, &mut highlights); + + if let Some(then_block) = cur_if.then_branch() { + push_tail_expr(Some(then_block.into()), &mut highlights); + } + + match cur_if.else_branch() { + Some(ast::ElseBranch::Block(else_block)) => { + push_tail_expr(Some(else_block.into()), &mut highlights); + if_to_process = None; + } + Some(ast::ElseBranch::IfExpr(nested_if)) => if_to_process = Some(nested_if), + None => if_to_process = None, + } + } + } + } + _ => unreachable!(), + } + + highlights + .into_iter() + .map(|(file_id, ranges)| (file_id, ranges.into_iter().collect())) + .collect() +} + fn hl_exit_points( sema: &Semantics<'_, RootDatabase>, def_token: Option, body: ast::Expr, -) -> Option>> { +) -> Option { let mut highlights: FxHashMap> = FxHashMap::default(); let mut push_to_highlights = |file_id, range| { @@ -411,7 +528,7 @@ pub(crate) fn highlight_break_points( loop_token: Option, label: Option, expr: ast::Expr, - ) -> Option>> { + ) -> Option { let mut highlights: FxHashMap> = FxHashMap::default(); let mut push_to_highlights = |file_id, range| { @@ -504,7 +621,7 @@ pub(crate) fn highlight_yield_points( sema: &Semantics<'_, RootDatabase>, async_token: Option, body: Option, - ) -> Option>> { + ) -> Option { let mut highlights: FxHashMap> = FxHashMap::default(); let mut push_to_highlights = |file_id, range| { @@ -597,10 +714,7 @@ fn original_frange( InFile::new(file_id, text_range?).original_node_file_range_opt(db).map(|(frange, _)| frange) } -fn merge_map( - res: &mut FxHashMap>, - new: Option>>, -) { +fn merge_map(res: &mut HighlightMap, new: Option) { let Some(new) = new else { return; }; @@ -750,6 +864,7 @@ mod tests { references: true, closure_captures: true, yield_points: true, + branches: true, }; #[track_caller] @@ -2134,6 +2249,62 @@ fn main() { ) } + #[test] + fn nested_match() { + check( + r#" +fn main() { + match$0 0 { + // ^^^^^ + 0 => match 1 { + 1 => 2, + // ^ + _ => 3, + // ^ + }, + _ => 4, + // ^ + } +} +"#, + ) + } + + #[test] + fn single_arm_highlight() { + check( + r#" +fn main() { + match 0 { + 0 =>$0 { + // ^^ + let x = 1; + x + // ^ + } + _ => 2, + } +} +"#, + ) + } + + #[test] + fn no_branches_when_disabled() { + let config = HighlightRelatedConfig { branches: false, ..ENABLED_CONFIG }; + check_with_config( + r#" +fn main() { + match$0 0 { + 0 => 1, + _ => 2, + } +} +"#, + config, + ); + } + #[test] fn asm() { check( @@ -2164,6 +2335,152 @@ pub unsafe fn bootstrap() -> ! { ) } + #[test] + fn complex_arms_highlight() { + check( + r#" +fn calculate(n: i32) -> i32 { n * 2 } + +fn main() { + match$0 Some(1) { + // ^^^^^ + Some(x) => match x { + 0 => { let y = x; y }, + // ^ + 1 => calculate(x), + //^^^^^^^^^^^^ + _ => (|| 6)(), + // ^^^^^^^^ + }, + None => loop { + break 5; + // ^^^^^^^ + }, + } +} +"#, + ) + } + + #[test] + fn match_in_macro_highlight() { + check( + r#" +macro_rules! M { + ($e:expr) => { $e }; +} + +fn main() { + M!{ + match$0 Some(1) { + // ^^^^^ + Some(x) => x, + // ^ + None => 0, + // ^ + } + } +} +"#, + ) + } + + #[test] + fn nested_if_else() { + check( + r#" +fn main() { + if$0 true { + // ^^ + if false { + 1 + // ^ + } else { + 2 + // ^ + } + } else { + 3 + // ^ + } +} +"#, + ) + } + + #[test] + fn if_else_if_highlight() { + check( + r#" +fn main() { + if$0 true { + // ^^ + 1 + // ^ + } else if false { + // ^^ + 2 + // ^ + } else { + 3 + // ^ + } +} +"#, + ) + } + + #[test] + fn complex_if_branches() { + check( + r#" +fn calculate(n: i32) -> i32 { n * 2 } + +fn main() { + if$0 true { + // ^^ + let x = 5; + calculate(x) + // ^^^^^^^^^^^^ + } else if false { + // ^^ + (|| 10)() + // ^^^^^^^^^ + } else { + loop { + break 15; + // ^^^^^^^^ + } + } +} +"#, + ) + } + + #[test] + fn if_in_macro_highlight() { + check( + r#" +macro_rules! M { + ($e:expr) => { $e }; +} + +fn main() { + M!{ + if$0 true { + // ^^ + 5 + // ^ + } else { + 10 + // ^^ + } + } +} +"#, + ) + } + #[test] fn labeled_block_tail_expr() { check( diff --git a/src/tools/rust-analyzer/crates/ide/src/references.rs b/src/tools/rust-analyzer/crates/ide/src/references.rs index c6a323d4081..900f49910d3 100644 --- a/src/tools/rust-analyzer/crates/ide/src/references.rs +++ b/src/tools/rust-analyzer/crates/ide/src/references.rs @@ -397,7 +397,10 @@ fn handle_control_flow_keywords( .attach_first_edition(file_id) .map(|it| it.edition(sema.db)) .unwrap_or(Edition::CURRENT); - let token = file.syntax().token_at_offset(offset).find(|t| t.kind().is_keyword(edition))?; + let token = file + .syntax() + .token_at_offset(offset) + .find(|t| t.kind().is_keyword(edition) || t.kind() == T![=>])?; let references = match token.kind() { T![fn] | T![return] | T![try] => highlight_related::highlight_exit_points(sema, token), @@ -408,6 +411,7 @@ fn handle_control_flow_keywords( T![for] if token.parent().and_then(ast::ForExpr::cast).is_some() => { highlight_related::highlight_break_points(sema, token) } + T![if] | T![=>] | T![match] => highlight_related::highlight_branches(sema, token), _ => return None, } .into_iter() @@ -1344,6 +1348,159 @@ impl Foo { ); } + #[test] + fn test_highlight_if_branches() { + check( + r#" +fn main() { + let x = if$0 true { + 1 + } else if false { + 2 + } else { + 3 + }; + + println!("x: {}", x); +} +"#, + expect![[r#" + FileId(0) 24..26 + FileId(0) 42..43 + FileId(0) 55..57 + FileId(0) 74..75 + FileId(0) 97..98 + "#]], + ); + } + + #[test] + fn test_highlight_match_branches() { + check( + r#" +fn main() { + $0match Some(42) { + Some(x) if x > 0 => println!("positive"), + Some(0) => println!("zero"), + Some(_) => println!("negative"), + None => println!("none"), + }; +} +"#, + expect![[r#" + FileId(0) 16..21 + FileId(0) 61..81 + FileId(0) 102..118 + FileId(0) 139..159 + FileId(0) 177..193 + "#]], + ); + } + + #[test] + fn test_highlight_match_arm_arrow() { + check( + r#" +fn main() { + match Some(42) { + Some(x) if x > 0 $0=> println!("positive"), + Some(0) => println!("zero"), + Some(_) => println!("negative"), + None => println!("none"), + } +} +"#, + expect![[r#" + FileId(0) 58..60 + FileId(0) 61..81 + "#]], + ); + } + + #[test] + fn test_highlight_nested_branches() { + check( + r#" +fn main() { + let x = $0if true { + if false { + 1 + } else { + match Some(42) { + Some(_) => 2, + None => 3, + } + } + } else { + 4 + }; + + println!("x: {}", x); +} +"#, + expect![[r#" + FileId(0) 24..26 + FileId(0) 65..66 + FileId(0) 140..141 + FileId(0) 167..168 + FileId(0) 215..216 + "#]], + ); + } + + #[test] + fn test_highlight_match_with_complex_guards() { + check( + r#" +fn main() { + let x = $0match (x, y) { + (a, b) if a > b && a % 2 == 0 => 1, + (a, b) if a < b || b % 2 == 1 => 2, + (a, _) if a > 40 => 3, + _ => 4, + }; + + println!("x: {}", x); +} +"#, + expect![[r#" + FileId(0) 24..29 + FileId(0) 80..81 + FileId(0) 124..125 + FileId(0) 155..156 + FileId(0) 171..172 + "#]], + ); + } + + #[test] + fn test_highlight_mixed_if_match_expressions() { + check( + r#" +fn main() { + let x = $0if let Some(x) = Some(42) { + 1 + } else if let None = None { + 2 + } else { + match 42 { + 0 => 3, + _ => 4, + } + }; +} +"#, + expect![[r#" + FileId(0) 24..26 + FileId(0) 60..61 + FileId(0) 73..75 + FileId(0) 102..103 + FileId(0) 153..154 + FileId(0) 173..174 + "#]], + ); + } + fn check(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expect) { check_with_scope(ra_fixture, None, expect) } @@ -2867,4 +3024,66 @@ const FOO$0: i32 = 0; "#]], ); } + + #[test] + fn test_highlight_if_let_match_combined() { + check( + r#" +enum MyEnum { A(i32), B(String), C } + +fn main() { + let val = MyEnum::A(42); + + let x = $0if let MyEnum::A(x) = val { + 1 + } else if let MyEnum::B(s) = val { + 2 + } else { + match val { + MyEnum::C => 3, + _ => 4, + } + }; +} +"#, + expect![[r#" + FileId(0) 92..94 + FileId(0) 128..129 + FileId(0) 141..143 + FileId(0) 177..178 + FileId(0) 237..238 + FileId(0) 257..258 + "#]], + ); + } + + #[test] + fn test_highlight_nested_match_expressions() { + check( + r#" +enum Outer { A(Inner), B } +enum Inner { X, Y(i32) } + +fn main() { + let val = Outer::A(Inner::Y(42)); + + $0match val { + Outer::A(inner) => match inner { + Inner::X => println!("Inner::X"), + Inner::Y(n) if n > 0 => println!("Inner::Y positive: {}", n), + Inner::Y(_) => println!("Inner::Y non-positive"), + }, + Outer::B => println!("Outer::B"), + } +} +"#, + expect![[r#" + FileId(0) 108..113 + FileId(0) 185..205 + FileId(0) 243..279 + FileId(0) 308..341 + FileId(0) 374..394 + "#]], + ); + } } diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs index 05e1b832cd1..cc8711f2c08 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs @@ -94,6 +94,8 @@ config_data! { + /// Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`). + highlightRelated_branches_enable: bool = true, /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. highlightRelated_breakPoints_enable: bool = true, /// Enables highlighting of all captures of a closure while the cursor is on the `|` or move keyword of a closure. @@ -1629,6 +1631,7 @@ impl Config { exit_points: self.highlightRelated_exitPoints_enable().to_owned(), yield_points: self.highlightRelated_yieldPoints_enable().to_owned(), closure_captures: self.highlightRelated_closureCaptures_enable().to_owned(), + branches: self.highlightRelated_branches_enable().to_owned(), } } diff --git a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md index 9404b1454a0..587c09234c1 100644 --- a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md +++ b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md @@ -612,6 +612,13 @@ Default: `"client"` Controls file watching implementation. +## rust-analyzer.highlightRelated.branches.enable {#highlightRelated.branches.enable} + +Default: `true` + +Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`). + + ## rust-analyzer.highlightRelated.breakPoints.enable {#highlightRelated.breakPoints.enable} Default: `true` diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index 26a21c1468d..c792ef0ffdc 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -1529,6 +1529,16 @@ } } }, + { + "title": "highlightRelated", + "properties": { + "rust-analyzer.highlightRelated.branches.enable": { + "markdownDescription": "Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`).", + "default": true, + "type": "boolean" + } + } + }, { "title": "highlightRelated", "properties": { -- cgit 1.4.1-3-g733a5 From 7ab46b4b3a9c275df08dd52faf0ef12e5adf70ef Mon Sep 17 00:00:00 2001 From: roifewu Date: Tue, 15 Apr 2025 11:02:14 +0800 Subject: refactor: rename `branches` to `branch_exit_points` in highlight_related --- src/tools/rust-analyzer/crates/ide/src/highlight_related.rs | 12 ++++++------ src/tools/rust-analyzer/crates/ide/src/references.rs | 2 +- src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs | 4 ++-- .../rust-analyzer/docs/book/src/configuration_generated.md | 2 +- src/tools/rust-analyzer/editors/code/package.json | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) (limited to 'src/tools/rust-analyzer/editors/code') diff --git a/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs b/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs index 28447005c1f..77b8599fd02 100644 --- a/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs +++ b/src/tools/rust-analyzer/crates/ide/src/highlight_related.rs @@ -37,7 +37,7 @@ pub struct HighlightRelatedConfig { pub break_points: bool, pub closure_captures: bool, pub yield_points: bool, - pub branches: bool, + pub branch_exit_points: bool, } type HighlightMap = FxHashMap>; @@ -81,8 +81,8 @@ pub(crate) fn highlight_related( T![fn] | T![return] | T![->] if config.exit_points => { highlight_exit_points(sema, token).remove(&file_id) } - T![match] | T![=>] | T![if] if config.branches => { - highlight_branches(sema, token).remove(&file_id) + T![match] | T![=>] | T![if] if config.branch_exit_points => { + highlight_branch_exit_points(sema, token).remove(&file_id) } T![await] | T![async] if config.yield_points => { highlight_yield_points(sema, token).remove(&file_id) @@ -306,7 +306,7 @@ fn highlight_references( if res.is_empty() { None } else { Some(res.into_iter().collect()) } } -pub(crate) fn highlight_branches( +pub(crate) fn highlight_branch_exit_points( sema: &Semantics<'_, RootDatabase>, token: SyntaxToken, ) -> FxHashMap> { @@ -871,7 +871,7 @@ mod tests { references: true, closure_captures: true, yield_points: true, - branches: true, + branch_exit_points: true, }; #[track_caller] @@ -2298,7 +2298,7 @@ fn main() { #[test] fn no_branches_when_disabled() { - let config = HighlightRelatedConfig { branches: false, ..ENABLED_CONFIG }; + let config = HighlightRelatedConfig { branch_exit_points: false, ..ENABLED_CONFIG }; check_with_config( r#" fn main() { diff --git a/src/tools/rust-analyzer/crates/ide/src/references.rs b/src/tools/rust-analyzer/crates/ide/src/references.rs index 900f49910d3..205e93d7a24 100644 --- a/src/tools/rust-analyzer/crates/ide/src/references.rs +++ b/src/tools/rust-analyzer/crates/ide/src/references.rs @@ -411,7 +411,7 @@ fn handle_control_flow_keywords( T![for] if token.parent().and_then(ast::ForExpr::cast).is_some() => { highlight_related::highlight_break_points(sema, token) } - T![if] | T![=>] | T![match] => highlight_related::highlight_branches(sema, token), + T![if] | T![=>] | T![match] => highlight_related::highlight_branch_exit_points(sema, token), _ => return None, } .into_iter() diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs index cc8711f2c08..e716d140752 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs @@ -95,7 +95,7 @@ config_data! { /// Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`). - highlightRelated_branches_enable: bool = true, + highlightRelated_branchExitPoints_enable: bool = true, /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords. highlightRelated_breakPoints_enable: bool = true, /// Enables highlighting of all captures of a closure while the cursor is on the `|` or move keyword of a closure. @@ -1631,7 +1631,7 @@ impl Config { exit_points: self.highlightRelated_exitPoints_enable().to_owned(), yield_points: self.highlightRelated_yieldPoints_enable().to_owned(), closure_captures: self.highlightRelated_closureCaptures_enable().to_owned(), - branches: self.highlightRelated_branches_enable().to_owned(), + branch_exit_points: self.highlightRelated_branchExitPoints_enable().to_owned(), } } diff --git a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md index 587c09234c1..ebac26e1d60 100644 --- a/src/tools/rust-analyzer/docs/book/src/configuration_generated.md +++ b/src/tools/rust-analyzer/docs/book/src/configuration_generated.md @@ -612,7 +612,7 @@ Default: `"client"` Controls file watching implementation. -## rust-analyzer.highlightRelated.branches.enable {#highlightRelated.branches.enable} +## rust-analyzer.highlightRelated.branchExitPoints.enable {#highlightRelated.branchExitPoints.enable} Default: `true` diff --git a/src/tools/rust-analyzer/editors/code/package.json b/src/tools/rust-analyzer/editors/code/package.json index c792ef0ffdc..3cb4c21ee1f 100644 --- a/src/tools/rust-analyzer/editors/code/package.json +++ b/src/tools/rust-analyzer/editors/code/package.json @@ -1532,7 +1532,7 @@ { "title": "highlightRelated", "properties": { - "rust-analyzer.highlightRelated.branches.enable": { + "rust-analyzer.highlightRelated.branchExitPoints.enable": { "markdownDescription": "Enables highlighting of related return values while the cursor is on any `match`, `if`, or match arm arrow (`=>`).", "default": true, "type": "boolean" -- cgit 1.4.1-3-g733a5 From 0af03671ec9e1db44c1e51a961789f0d140ec50c Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 26 Jun 2025 10:31:58 +0200 Subject: Cleanup `provideCodeActions` vscode hook --- src/tools/rust-analyzer/editors/code/src/client.ts | 114 +++++++++++---------- 1 file changed, 59 insertions(+), 55 deletions(-) (limited to 'src/tools/rust-analyzer/editors/code') diff --git a/src/tools/rust-analyzer/editors/code/src/client.ts b/src/tools/rust-analyzer/editors/code/src/client.ts index cdeea7333a6..073ff2f4703 100644 --- a/src/tools/rust-analyzer/editors/code/src/client.ts +++ b/src/tools/rust-analyzer/editors/code/src/client.ts @@ -3,7 +3,7 @@ import * as lc from "vscode-languageclient/node"; import * as vscode from "vscode"; import * as ra from "../src/lsp_ext"; import * as Is from "vscode-languageclient/lib/common/utils/is"; -import { assert, unwrapUndefinable } from "./util"; +import { assert } from "./util"; import * as diagnostics from "./diagnostics"; import { WorkspaceEdit } from "vscode"; import { type Config, prepareVSCodeConfig } from "./config"; @@ -188,11 +188,17 @@ export async function createClient( context: await client.code2ProtocolConverter.asCodeActionContext(context, token), }; const callback = async ( - values: (lc.Command | lc.CodeAction)[] | null, + values: (lc.Command | lc.CodeAction | object)[] | null, ): Promise<(vscode.Command | vscode.CodeAction)[] | undefined> => { if (values === null) return undefined; const result: (vscode.CodeAction | vscode.Command)[] = []; - const groups = new Map(); + const groups = new Map< + string, + { + primary: vscode.CodeAction; + items: { label: string; arguments: lc.CodeAction }[]; + } + >(); for (const item of values) { // In our case we expect to get code edits only from diagnostics if (lc.CodeAction.is(item)) { @@ -204,62 +210,55 @@ export async function createClient( result.push(action); continue; } - assert( - isCodeActionWithoutEditsAndCommands(item), - "We don't expect edits or commands here", - ); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind); - const action = new vscode.CodeAction(item.title, kind); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const group = (item as any).group; - action.command = { - command: "rust-analyzer.resolveCodeAction", - title: item.title, - arguments: [item], - }; + assertIsCodeActionWithoutEditsAndCommands(item); + const kind = client.protocol2CodeConverter.asCodeActionKind(item.kind); + const group = item.group; - // Set a dummy edit, so that VS Code doesn't try to resolve this. - action.edit = new WorkspaceEdit(); + const mkAction = () => { + const action = new vscode.CodeAction(item.title, kind); + action.command = { + command: "rust-analyzer.resolveCodeAction", + title: item.title, + arguments: [item], + }; + // Set a dummy edit, so that VS Code doesn't try to resolve this. + action.edit = new WorkspaceEdit(); + return action; + }; if (group) { let entry = groups.get(group); if (!entry) { - entry = { index: result.length, items: [] }; + entry = { primary: mkAction(), items: [] }; groups.set(group, entry); - result.push(action); + } else { + entry.items.push({ + label: item.title, + arguments: item, + }); } - entry.items.push(action); } else { - result.push(action); + result.push(mkAction()); } } - for (const [group, { index, items }] of groups) { - if (items.length === 1) { - const item = unwrapUndefinable(items[0]); - result[index] = item; - } else { - const action = new vscode.CodeAction(group); - const item = unwrapUndefinable(items[0]); - action.kind = item.kind; - action.command = { + for (const [group, { items, primary }] of groups) { + // This group contains more than one item, so rewrite it to be a group action + if (items.length !== 0) { + const args = [ + { + label: primary.title, + arguments: primary.command!.arguments![0], + }, + ...items, + ]; + primary.title = group; + primary.command = { command: "rust-analyzer.applyActionGroup", title: "", - arguments: [ - items.map((item) => { - return { - label: item.title, - arguments: item.command!.arguments![0], - }; - }), - ], + arguments: [args], }; - - // Set a dummy edit, so that VS Code doesn't try to resolve this. - action.edit = new WorkspaceEdit(); - - result[index] = action; } + result.push(primary); } return result; }; @@ -363,17 +362,22 @@ class OverrideFeatures implements lc.StaticFeature { clear(): void {} } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function isCodeActionWithoutEditsAndCommands(value: any): boolean { - const candidate: lc.CodeAction = value; - return ( +function assertIsCodeActionWithoutEditsAndCommands( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + candidate: any, +): asserts candidate is lc.CodeAction & { + group?: string; +} { + assert( candidate && - Is.string(candidate.title) && - (candidate.diagnostics === void 0 || - Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) && - (candidate.kind === void 0 || Is.string(candidate.kind)) && - candidate.edit === void 0 && - candidate.command === void 0 + Is.string(candidate.title) && + (candidate.diagnostics === undefined || + Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) && + (candidate.group === undefined || Is.string(candidate.group)) && + (candidate.kind === undefined || Is.string(candidate.kind)) && + candidate.edit === undefined && + candidate.command === undefined, + `Expected a CodeAction without edits or commands, got: ${JSON.stringify(candidate)}`, ); } -- cgit 1.4.1-3-g733a5