Compare commits

...
Author SHA1 Message Date
l0ng-ai 38ff80fe6a feat(refactor): Change Signature dialog for Java methods
Change Signature… (⌘F6, also in Refactor This) on a Java method opens a
dialog for its visibility, return type, name and parameters (add with a
default value for existing calls, remove, reorder), with Delegate via
overloading method and a signature preview. jdtls reads the method
(java/getChangeSignatureInfo) and checks the new signature and computes the
edit for the method, its overrides and its calls (java/getRefactorEdit
changeSignature); warnings are confirmed in Problems Detected before the edit,
and Preview lists the changes first. jdtls offers the refactoring only through
a client-side command, so Java had no Change Signature before.

New IPC: lsp_signature_info, lsp_change_signature.
2026-11-16 15:18:27 +08:00
19 changed files with 987 additions and 10 deletions

No files matched your search

+65
View File
@@ -1173,6 +1173,55 @@ pub async fn lsp_hierarchy_refactor(
.await
}
/// The signature of the method at `pos`, for Change Signature.
pub async fn lsp_signature_info(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<MethodSignature> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.change_signature_info(doc, pos, cancel).await;
host.end_request(request);
result
}
/// Checks changing the method at `pos` to `signature` and computes the edit without applying it.
#[allow(clippy::too_many_arguments)]
pub async fn lsp_change_signature(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
) -> IdeResult<SignatureChanged> {
let project = host.project(window)?;
let documents = project.documents.clone();
let version = blocking(move || documents.version(doc)).await?;
let cancel = host.begin_request(request);
let result = project.lsp.change_signature(doc, pos, signature, delegate, confirmation, cancel).await;
host.end_request(request);
let mut changed = result?;
blocking(move || {
if project.documents.version(doc)? != version {
return Err(ide_core::IdeError::new(
ide_core::error::ErrorKind::OutOfSync,
"document changed while computing the refactoring; request it again",
));
}
if let Some(edit) = &mut changed.edit {
project.documents.prepare_workspace_edit(edit)?;
}
Ok(changed)
})
.await
}
pub async fn lsp_rename(
host: &Host,
window: &str,
@@ -1896,6 +1945,22 @@ pub(crate) fn register(d: &mut Dispatcher) {
)
.await
});
d.add("lsp_signature_info", |c| async move {
lsp_signature_info(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?).await
});
d.add("lsp_change_signature", |c| async move {
lsp_change_signature(
&c.host,
&c.window,
c.arg("request")?,
c.arg("doc")?,
c.arg("pos")?,
c.arg("signature")?,
c.arg("delegate")?,
c.arg("confirmation")?,
)
.await
});
d.add("lsp_format", |c| async move {
lsp_format(&c.host, &c.window, c.arg("doc")?, c.arg("range")?, c.arg("options")?).await
});
+1
View File
@@ -23,6 +23,7 @@ mod formatter;
mod hierarchy;
pub(crate) mod jvm_inspect;
pub(crate) mod reserved_names;
mod signature;
pub use formatter::configure_formatter;
/// First start imports the Maven / Gradle model, which can take minutes.
const READY_TIMEOUT: Duration = Duration::from_secs(240);
+181
View File
@@ -0,0 +1,181 @@
//! Change Signature through jdtls' own requests: `java/getChangeSignatureInfo` reads the method at
//! a position, `java/getRefactorEdit` (`changeSignature`) checks the new signature and computes the
//! edit. The UI edits the signature and applies the edit itself.
use super::{COMMAND_TIMEOUT, SERVER};
use crate::types::{MethodSignature, ProblemSeverity, RefactoringProblem, SignatureChanged};
use crate::{DocSnap, LspManager, Target, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
use serde_json::{Value, json};
const FEATURE: &str = "Change Signature";
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Info {
#[serde(flatten)]
signature: Option<MethodSignature>,
error_message: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RefactorEdit {
edit: Option<lsp_types::WorkspaceEdit>,
error_message: Option<String>,
confirmation_token: Option<String>,
}
/// `java/getRefactorEdit`'s answer as Change Signature's result: an error message alone is fatal;
/// with a confirmation token it lists warnings to accept before the edit is computed.
fn changed(
answer: RefactorEdit,
convert_edit: impl FnOnce(lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit,
) -> SignatureChanged {
let problem = |severity| {
answer
.error_message
.as_deref()
.filter(|m| !m.trim().is_empty())
.map(|message| RefactoringProblem { severity, message: message.trim().to_owned() })
};
if let Some(token) = answer.confirmation_token {
return SignatureChanged {
problems: problem(ProblemSeverity::Warning).into_iter().collect(),
edit: None,
confirmation: Some(token),
};
}
match answer.edit {
Some(edit) if answer.error_message.is_none() => {
SignatureChanged { problems: Vec::new(), edit: Some(convert_edit(edit)), confirmation: None }
}
_ => SignatureChanged {
problems: problem(ProblemSeverity::Fatal).into_iter().collect(),
edit: None,
confirmation: None,
},
}
}
impl LspManager {
async fn signature_target(&self, doc: DocId) -> IdeResult<(DocSnap, Target)> {
let (snap, targets) = self.doc_targets(doc, FEATURE, |_| true).await?;
let t = targets
.into_iter()
.find(|t| t.server.name == SERVER)
.ok_or_else(|| IdeError::unavailable(format!("{FEATURE} needs the Java language server (jdtls)")))?;
Ok((snap, t))
}
fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
let at = snap.position(t, pos);
json!({
"textDocument": { "uri": snap.uri },
"range": { "start": at, "end": at },
"context": { "diagnostics": [] },
})
}
/// The signature of the method at `pos`; an invalid-input error says why it can't be changed.
pub async fn change_signature_info(
&self,
doc: DocId,
pos: Pos,
cancel: CancellationToken,
) -> IdeResult<MethodSignature> {
let (snap, t) = self.signature_target(doc).await?;
let params = Self::signature_context(&snap, &t, pos);
let info: Option<Info> =
self.call(&t, "java/getChangeSignatureInfo", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match info {
Some(Info { error_message: Some(message), .. }) => Err(IdeError::invalid(message)),
Some(Info { signature: Some(signature), .. }) => Ok(signature),
_ => Err(IdeError::invalid("Caret should be on a method declaration")),
}
}
/// Checks changing the method at `pos` to `signature` and computes the edit without applying it.
/// `confirmation` accepts the warnings an earlier check returned with it.
pub async fn change_signature(
&self,
doc: DocId,
pos: Pos,
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<SignatureChanged> {
let (snap, t) = self.signature_target(doc).await?;
let MethodSignature { method_identifier, modifier, return_type, method_name, parameters, exceptions } =
signature;
let mut params = json!({
"command": "changeSignature",
"context": Self::signature_context(&snap, &t, pos),
"options": { "tabSize": 4, "insertSpaces": true },
"commandArguments": [
method_identifier, delegate, method_name, modifier, return_type, parameters, exceptions, false
],
});
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
}
let answer: Option<RefactorEdit> =
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let answer = answer.unwrap_or(RefactorEdit { edit: None, error_message: None, confirmation_token: None });
let conv = self.conv(t.enc());
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn answer(v: Value) -> RefactorEdit {
serde_json::from_value(v).unwrap()
}
fn no_edit(_: lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit {
ide_core::WorkspaceEdit::default()
}
#[test]
fn reads_the_signature_or_why_there_is_none() {
let info: Info = serde_json::from_value(json!({
"methodIdentifier": "=p/src<p{A.java[A~m~I",
"modifier": "public",
"returnType": "void",
"methodName": "m",
"parameters": [{ "type": "int", "name": "a", "defaultValue": "null", "originalIndex": 0 }],
"exceptions": [{ "type": "java.io.IOException", "typeHandleIdentifier": "=x" }],
"errorMessage": null,
}))
.unwrap();
let s = info.signature.unwrap();
assert_eq!((s.method_name.as_str(), s.parameters[0].type_name.as_str()), ("m", "int"));
assert_eq!(s.exceptions[0].type_name, "java.io.IOException");
let refused: Info = serde_json::from_value(json!({ "errorMessage": "Cannot change signature." })).unwrap();
assert!(refused.signature.is_none());
assert_eq!(refused.error_message.as_deref(), Some("Cannot change signature."));
}
#[test]
fn errors_are_fatal_and_tokens_ask_for_confirmation() {
let fatal = changed(answer(json!({ "errorMessage": "Duplicate parameter name" })), no_edit);
assert_eq!(fatal.problems[0].severity, ProblemSeverity::Fatal);
assert!(fatal.edit.is_none() && fatal.confirmation.is_none());
let warn = changed(answer(json!({ "errorMessage": "Overrides a method", "confirmationToken": "t1" })), no_edit);
assert_eq!(warn.problems[0].severity, ProblemSeverity::Warning);
assert_eq!(warn.confirmation.as_deref(), Some("t1"));
let ok = changed(answer(json!({ "edit": { "changes": {} } })), no_edit);
assert!(ok.problems.is_empty() && ok.edit.is_some());
}
}
+45
View File
@@ -504,6 +504,51 @@ pub struct HierarchyRefactored {
pub edit: Option<WorkspaceEdit>,
}
/// A parameter in Change Signature: its type, name, the value passed at existing calls when it is
/// added, and its index in the current signature (-1 for an added one).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SignatureParameter {
#[serde(rename = "type")]
pub type_name: String,
pub name: String,
pub default_value: String,
pub original_index: i32,
}
/// A declared exception (`throws`), with the server's handle of its type.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SignatureException {
#[serde(rename = "type")]
pub type_name: String,
pub type_handle_identifier: String,
}
/// The signature of the method at a position, as Change Signature edits it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MethodSignature {
/// The server's handle of the method, passed back unchanged.
pub method_identifier: String,
/// `public`, `protected`, `private`, or empty for package-private.
pub modifier: String,
pub return_type: String,
pub method_name: String,
pub parameters: Vec<SignatureParameter>,
pub exceptions: Vec<SignatureException>,
}
/// Change Signature's check: problems to show, the edit when none is fatal, and the token that
/// confirms going on despite warnings.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SignatureChanged {
pub problems: Vec<RefactoringProblem>,
pub edit: Option<WorkspaceEdit>,
pub confirmation: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchy {
+6 -2
View File
@@ -18,7 +18,7 @@ The **Refactor** menu has IntelliJ IDEA's refactorings with their usual shortcut
| Refactoring | macOS | Windows / Linux | Works through |
| ------------------------ | ----- | --------------- | ------------------------------------------------------ |
| **Rename…** | `⇧F6` | `Shift+F6` | Language server; local variables also without one |
| **Change Signature…** | `⌘F6` | `Ctrl+F6` | Language server |
| **Change Signature…** | `⌘F6` | `Ctrl+F6` | Java (dialog); other languages: language server |
| **Introduce Variable…** | `⌥⌘V` | `Ctrl+Alt+V` | Language server; simple cases also without one |
| **Introduce Constant…** | `⌥⌘C` | `Ctrl+Alt+C` | Language server; simple cases also without one |
| **Introduce Field…** | `⌥⌘F` | `Ctrl+Alt+F` | Language server |
@@ -82,6 +82,10 @@ In the editor, **Move…** on a symbol runs the server's move refactoring, where
These move fields and methods between a class and its superclasses or subclasses, in Java and, with Phoxite as the PHP server, in PHP (methods, properties and constants). A dialog lets you pick the members and the destination; problems the move would cause are listed in **Problems Detected** before you continue. For Java they are provided by the extension bundled with OpenIDEA, for PHP by Phoxite; they are not available for other languages or other PHP servers.
## Change Signature
In Java, **Change Signature…** (`⌘F6`) on a method opens a dialog to change its visibility, return type and name, and to add, remove and reorder its parameters. A new parameter needs a default value, which is passed at every existing call; **Delegate via overloading method** keeps the old signature as an overload that calls the new one. The preview line shows the resulting declaration. **Refactor** updates the method, its overrides and all calls in one step; **Preview** lists the changes first. In other languages it appears when the server offers a signature rewrite as a code action.
## Undo
A refactoring is one undo step, even when it changed several files. After a multi-file refactoring, a notification offers **Undo** (and then **Redo**).
@@ -89,5 +93,5 @@ A refactoring is one undo step, even when it changed several files. After a mult
## Limits
- Refactorings other than Rename, Safe Delete and the syntax-based fallbacks need a running language server that offers them. Check the **Language Services** widget in the status bar if one is missing.
- Change Signature appears only when the server offers a signature rewrite as a code action.
- Outside Java, Change Signature appears only when the server offers a signature rewrite as a code action.
- There is no structural search-and-replace refactoring in this menu; see **Edit › Find › Replace Structurally…** in [Inspections](/en/guide/inspections).
+6 -2
View File
@@ -18,7 +18,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
| 重构 | macOS | Windows / Linux | 实现方式 |
| ------------- | ----- | --------------- | --------------------------------------- |
| **重命名…** | `⇧F6` | `Shift+F6` | 语言服务器;局部变量没有服务器也可以 |
| **更改签名…** | `⌘F6` | `Ctrl+F6` | 语言服务器 |
| **更改签名…** | `⌘F6` | `Ctrl+F6` | Java(对话框);其他语言:语言服务器 |
| **引入变量…** | `⌥⌘V` | `Ctrl+Alt+V` | 语言服务器;简单情况没有服务器也可以 |
| **引入常量…** | `⌥⌘C` | `Ctrl+Alt+C` | 语言服务器;简单情况没有服务器也可以 |
| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 |
@@ -75,6 +75,10 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
用于在类和它的父类或子类之间移动字段和方法:支持 Java,以及使用 Phoxite 作为 PHP 服务器时的 PHP(方法、属性和常量)。在对话框中选择成员和目标类;移动会引起的问题会先在 **检测到问题** 中列出,再决定是否继续。Java 由 OpenIDEA 自带的扩展提供,PHP 由 Phoxite 提供;其他语言和其他 PHP 服务器不可用。
## 更改签名
在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。
## 撤销
一次重构就是一步撤销,即使它改了多个文件。多文件重构完成后,通知中会提供 **撤消**(撤销后变为 **重做**)。
@@ -82,5 +86,5 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
## 限制
- 除了重命名、安全删除和基于语法树的兜底实现,其他重构都需要语言服务器运行并提供相应功能。缺少时先看状态栏的 **语言服务** 微件。
- 只有当服务器把签名重写作为代码操作提供时,才会出现更改签名。
- 除 Java 外,只有当服务器把签名重写作为代码操作提供时,才会出现更改签名。
- 这个菜单里没有结构化搜索替换;见 [代码检查](/zh/guide/inspections) 中的 **编辑 › 查找 › 结构化替换…**。
+38
View File
@@ -317,6 +317,44 @@ pub async fn lsp_hierarchy_refactor(
.await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_signature_info(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<MethodSignature> {
ide_host::ops::lsp::lsp_signature_info(&state.host, window.label(), request, doc, pos).await
}
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_change_signature(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
) -> IdeResult<SignatureChanged> {
ide_host::ops::lsp::lsp_change_signature(
&state.host,
window.label(),
request,
doc,
pos,
signature,
delegate,
confirmation,
)
.await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_format(
+2
View File
@@ -302,6 +302,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_rename,
lsp::lsp_hierarchy_members,
lsp::lsp_hierarchy_refactor,
lsp::lsp_signature_info,
lsp::lsp_change_signature,
lsp::lsp_format,
lsp::lsp_inlay_hints,
lsp::lsp_semantic_tokens,
+2
View File
@@ -297,6 +297,7 @@ log_frontend always desktop bin
lsp_apply_code_action trusted project_host bindings async
lsp_call_hierarchy trusted project_host bindings async
lsp_can_download_sources trusted project_host bindings async
lsp_change_signature trusted project_host bindings async
lsp_code_action_query trusted project_host bindings async
lsp_code_actions trusted project_host bindings async
lsp_code_lens trusted project_host bindings async
@@ -329,6 +330,7 @@ lsp_restart_named trusted desktop bin
lsp_semantic_tokens trusted project_host bindings async
lsp_servers always project_host bindings sync
lsp_signature_help trusted project_host bindings async
lsp_signature_info trusted project_host bindings async
lsp_type_hierarchy trusted project_host bindings async
lsp_virtual_document trusted project_host bindings async
lsp_workspace_symbols trusted project_host bindings async
+41
View File
@@ -642,6 +642,8 @@ export const commands = {
lspHierarchyMembers: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring) => typedError<HierarchyMembers, IdeError>(__TAURI_INVOKE("lsp_hierarchy_members", { request, doc, pos, kind })),
/** Checks Pull Members Up / Push Members Down and computes the edit without applying it. */
lspHierarchyRefactor: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring, target: string | null, choices: HierarchyChoice[]) => typedError<HierarchyRefactored, IdeError>(__TAURI_INVOKE("lsp_hierarchy_refactor", { request, doc, pos, kind, target, choices })),
lspSignatureInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<MethodSignature, IdeError>(__TAURI_INVOKE("lsp_signature_info", { request, doc, pos })),
lspChangeSignature: (request: RequestId, doc: DocId, pos: Pos, signature: MethodSignature, delegate: boolean, confirmation: string | null) => typedError<SignatureChanged, IdeError>(__TAURI_INVOKE("lsp_change_signature", { request, doc, pos, signature, delegate, confirmation })),
lspFormat: (doc: DocId, range: {
start: Pos,
end: Pos,
@@ -7992,6 +7994,18 @@ export type MethodBody =
/** Anything else. */
{ kind: "other" };
/** The signature of the method at a position, as Change Signature edits it. */
export type MethodSignature = {
/** The server's handle of the method, passed back unchanged. */
methodIdentifier: string,
/** `public`, `protected`, `private`, or empty for package-private. */
modifier: string,
returnType: string,
methodName: string,
parameters: SignatureParameter[],
exceptions: SignatureException[],
};
/** Per-function totals (a recursive function's samples count once in `total`). */
export type MethodStat = {
frame: number,
@@ -10286,12 +10300,39 @@ export type Signature = {
parameters: ([number, number])[],
};
/**
* Change Signature's check: problems to show, the edit when none is fatal, and the token that
* confirms going on despite warnings.
*/
export type SignatureChanged = {
problems: RefactoringProblem[],
edit: WorkspaceEdit | null,
confirmation: string | null,
};
/** A declared exception (`throws`), with the server's handle of its type. */
export type SignatureException = {
type: string,
typeHandleIdentifier: string,
};
export type SignatureHelp = {
signatures: Signature[],
activeSignature: number,
activeParameter: number,
};
/**
* A parameter in Change Signature: its type, name, the value passed at existing calls when it is
* added, and its index in the current signature (-1 for an added one).
*/
export type SignatureParameter = {
type: string,
name: string,
defaultValue: string,
originalIndex: number,
};
/**
* Where the sizes of instances came from.
*
+2 -1
View File
@@ -42,7 +42,7 @@ import { DOCUMENTATION_WINDOW } from "./docs";
import { prefetchMarkdown } from "./markdown";
import { outsideProjectBanner } from "./outsideProject";
import { implementationGutter, registerNavigationActions } from "@/editor/navigation";
import { HierarchyDialog } from "@/editor/refactor";
import { ChangeSignatureDialog, HierarchyDialog } from "@/editor/refactor";
export function lspExtensions(ctx: EditorDocContext): Extension[] {
return [
@@ -116,6 +116,7 @@ export function activate(): () => void {
registerEditorContribution({ id: "lsp.parameterTab", order: 95, extensions: () => parameterTabKeys }),
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
registerOverlay({ id: "editor-lsp.hierarchyDialog", component: HierarchyDialog }),
registerOverlay({ id: "editor-lsp.changeSignatureDialog", component: ChangeSignatureDialog }),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
@@ -0,0 +1,111 @@
.dialog [data-dialog-body] {
display: flex;
flex-direction: column;
overflow: hidden;
}
.body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 14px;
font-size: var(--fs-ui);
color: var(--fg);
}
.header {
flex: none;
display: grid;
grid-template-columns: 150px 1fr 1fr;
gap: var(--space-3);
}
.field {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
min-width: 0;
}
.parameters {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
border: 1px solid var(--border);
border-radius: 4px;
}
.toolbar {
flex: none;
display: flex;
gap: var(--space-1);
padding: 2px 4px;
border-bottom: 1px solid var(--border);
}
.table {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.head,
.row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
gap: var(--space-2);
padding: 0 8px;
min-height: var(--h-list-row);
}
.head {
color: var(--fg-muted);
border-bottom: 1px solid var(--border);
}
.rows {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
.row:hover {
background: var(--bg-hover);
}
.row[aria-selected="true"] {
background: var(--bg-selected);
}
.preview {
margin: 0;
padding: 6px 8px;
border: 1px solid var(--border);
border-radius: 4px;
font-family: var(--font-mono);
font-size: var(--fs-code);
white-space: pre-wrap;
overflow-wrap: anywhere;
color: var(--fg);
background: var(--bg-input);
}
.busy {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
}
.error {
flex: none;
color: var(--danger);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
@@ -0,0 +1,202 @@
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
import { useState } from "react";
import type { MethodSignature } from "@/bindings";
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
import { useTx } from "@/platform/i18n";
import {
VISIBILITIES,
changeSignature,
newParameter,
parameterRow,
signatureChanged,
signatureProblem,
signatureText,
useSignatureDialog,
type ParameterRow,
type SignatureRequest,
} from "./signature";
import styles from "./ChangeSignatureDialog.module.css";
export function ChangeSignatureDialog() {
const request = useSignatureDialog((s) => s.request);
if (!request) return null;
return <ChangeSignatureDialogInner key={request.seq} request={request} />;
}
function ChangeSignatureDialogInner({ request }: { request: SignatureRequest }) {
const tx = useTx();
const { info } = request;
const [modifier, setModifier] = useState(info.modifier);
const [returnType, setReturnType] = useState(info.returnType);
const [methodName, setMethodName] = useState(info.methodName);
const [rows, setRows] = useState<ParameterRow[]>(() => info.parameters.map(parameterRow));
const [selected, setSelected] = useState(0);
const [delegate, setDelegate] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const signature: MethodSignature = {
...info,
modifier,
returnType: returnType.trim(),
methodName: methodName.trim(),
parameters: rows.map(({ key: _, ...p }) => ({ ...p, type: p.type.trim(), name: p.name.trim() })),
};
const problem = signatureProblem(signature);
const ready = !busy && !problem && signatureChanged(info, signature);
const current = Math.min(selected, rows.length - 1);
const close = () => {
useSignatureDialog.setState({ request: null });
request.view.focus();
};
const update = (key: number, change: Partial<ParameterRow>) =>
setRows((all) => all.map((r) => (r.key === key ? { ...r, ...change } : r)));
const add = () => {
setRows((all) => [...all, newParameter()]);
setSelected(rows.length);
};
const remove = () => {
if (current < 0) return;
setRows((all) => all.filter((_, i) => i !== current));
};
const move = (by: -1 | 1) => {
const to = current + by;
if (current < 0 || to < 0 || to >= rows.length) return;
setRows((all) => {
const next = [...all];
[next[current], next[to]] = [next[to]!, next[current]!];
return next;
});
setSelected(to);
};
const submit = async (preview: boolean) => {
if (!ready) return;
setBusy(true);
setError(null);
const outcome = await changeSignature(request, signature, delegate, preview);
if (useSignatureDialog.getState().request !== request) return;
setBusy(false);
if (outcome.status === "done") close();
else if (outcome.error) setError(outcome.error);
};
return (
<Dialog
open
onClose={close}
title="Change Signature"
className={styles.dialog}
width={640}
minHeight={380}
maxHeight={640}
resizable="both"
buttons={[
{ label: "Preview", role: "extra", disabled: !ready, onClick: () => void submit(true) },
{ label: "Refactor", role: "default", disabled: !ready, onClick: () => void submit(false) },
{ label: "Cancel", role: "cancel" },
]}
footerStart={
busy ? (
<span className={styles.busy}>
<Spinner size={12} />
<T>Checking for conflicts…</T>
</span>
) : undefined
}
>
<div className={styles.body}>
<div className={styles.header}>
<label className={styles.field}>
<T>Visibility:</T>
<Select
aria-label="Visibility"
value={modifier}
options={VISIBILITIES.map((v) => ({ value: v, label: v || tx("package-private") }))}
onChange={setModifier}
/>
</label>
<label className={styles.field}>
<T>Return type:</T>
<Input mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
</label>
<label className={styles.field}>
<T>Name:</T>
<Input mono autoFocus autoSelect value={methodName} onChange={(e) => setMethodName(e.target.value)} />
</label>
</div>
<div className={styles.parameters}>
<Toolbar aria-label={tx("Parameters")} className={styles.toolbar}>
<IconButton icon="plus" title={tx("Add")} onClick={add} />
<IconButton icon="minus" title={tx("Remove")} disabled={current < 0} onClick={remove} />
<IconButton icon="arrow-up" title={tx("Move Up")} disabled={current <= 0} onClick={() => move(-1)} />
<IconButton
icon="arrow-down"
title={tx("Move Down")}
disabled={current < 0 || current >= rows.length - 1}
onClick={() => move(1)}
/>
</Toolbar>
<div className={styles.table} role="table" aria-label={tx("Parameters")}>
<div className={styles.head} role="row">
<span role="columnheader">
<T>Type</T>
</span>
<span role="columnheader">
<T>Name</T>
</span>
<span role="columnheader">
<T>Default value</T>
</span>
</div>
<div className={styles.rows}>
{rows.map((row, i) => (
<div
key={row.key}
className={styles.row}
role="row"
aria-selected={i === current}
onFocusCapture={() => setSelected(i)}
>
<Input
mono
variant="bare"
aria-label={tx("Type")}
value={row.type}
autoFocus={row.originalIndex < 0 && !row.type}
onChange={(e) => update(row.key, { type: e.target.value })}
/>
<Input
mono
variant="bare"
aria-label={tx("Name")}
value={row.name}
onChange={(e) => update(row.key, { name: e.target.value })}
/>
<Input
mono
variant="bare"
aria-label={tx("Default value")}
value={row.originalIndex < 0 ? row.defaultValue : ""}
disabled={row.originalIndex >= 0}
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
/>
</div>
))}
</div>
</div>
</div>
<Checkbox checked={delegate} onChange={setDelegate} label={<T>Delegate via overloading method</T>} />
<div className={styles.field}>
<T>Signature Preview</T>
<pre className={styles.preview}>{signatureText(signature)}</pre>
</div>
{(error ?? (signatureChanged(info, signature) ? problem : null)) && (
<span className={styles.error} role="alert">
{tx(error ?? problem!)}
</span>
)}
</div>
</Dialog>
);
}
+1
View File
@@ -1,4 +1,5 @@
export { refactorThis, runRefactoring, showNothingHere } from "./refactorThis";
export { askUsagesDetected, fileUsages, safeDelete, viewUsages } from "./safeDelete";
export { startHierarchyRefactoring } from "./hierarchy";
export { ChangeSignatureDialog } from "./ChangeSignatureDialog";
export { HierarchyDialog } from "./HierarchyDialog";
+12 -3
View File
@@ -40,6 +40,7 @@ import {
} from "./serverIntroduce";
import { safeDelete } from "./safeDelete";
import { startHierarchyRefactoring } from "./hierarchy";
import { SIGNATURE_LANGUAGES, startChangeSignature } from "./signature";
/** Languages with a server that runs the class-hierarchy refactorings (the app-owned JDT extension; Phoxite for PHP). */
const HIERARCHY_LANGUAGES = new Set(["java", "php"]);
@@ -153,6 +154,10 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi
showHint(view, cannotPerform("The file is read-only"));
return;
}
if (id === "changeSignature" && SIGNATURE_LANGUAGES.has(ctx.language)) {
await startChangeSignature(view);
return;
}
// IDEA picks the expression first (and the server then extracts exactly that one).
if (EXPRESSION_REFACTORINGS.has(id) && view.state.selection.main.empty) {
if (await chooseExpressionFirst(view, () => runRefactoring(view, id))) return;
@@ -219,11 +224,12 @@ async function expressionAtCaret(view: EditorView, signal: AbortSignal): Promise
export function refactorThisItems(
view: EditorView,
answer: ServerAnswer,
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean },
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean; signature?: boolean },
run: {
rename: (view: EditorView) => unknown;
safeDelete: (view: EditorView) => unknown;
hierarchy?: (view: EditorView, kind: "pullUp" | "pushDown") => unknown;
signature?: (view: EditorView) => unknown;
},
): ListPopupItem[] {
const { mapped, other } = groupActions(answer.status === "ok" ? answer.query.actions : []);
@@ -237,6 +243,8 @@ export function refactorThisItems(
// With only a caret the expression is chosen first, then the server asked for it.
if (expression && caretOnly && serverUsable && (actions.length || facts.expression))
go = () => runRefactoring(view, r.id);
else if (r.id === "changeSignature" && facts.signature && serverUsable && run.signature)
go = () => run.signature!(view);
else if (actions.length) go = () => runActions(view, r.label.replace(/…$/, ""), actions, r.id);
else if (r.id === "rename" && facts.symbol) go = () => run.rename(view);
else if (r.id === "safeDelete" && facts.symbol && !docOf(view)?.readOnly) go = () => run.safeDelete(view);
@@ -278,11 +286,12 @@ export async function refactorThis(view: EditorView, rename: (view: EditorView)
expressionAtCaret(view, run.signal),
]);
const hierarchy = HIERARCHY_LANGUAGES.has(ctx.language) && !ctx.readOnly;
const signature = SIGNATURE_LANGUAGES.has(ctx.language) && !ctx.readOnly && symbol;
items = refactorThisItems(
view,
answer,
{ symbol, expression, hierarchy },
{ rename, safeDelete, hierarchy: startHierarchyRefactoring },
{ symbol, expression, hierarchy, signature },
{ rename, safeDelete, hierarchy: startHierarchyRefactoring, signature: startChangeSignature },
);
} catch (e) {
if (isCancelled(e)) return;
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import type { MethodSignature } from "@/bindings";
import { signatureChanged, signatureProblem, signatureText } from "./signature";
const info: MethodSignature = {
methodIdentifier: "=p/src<p{A.java[A~sum~I~I",
modifier: "public",
returnType: "int",
methodName: "sum",
parameters: [
{ type: "int", name: "a", defaultValue: "null", originalIndex: 0 },
{ type: "int", name: "b", defaultValue: "null", originalIndex: 1 },
],
exceptions: [{ type: "java.io.IOException", typeHandleIdentifier: "=x" }],
};
describe("change signature", () => {
it("previews the signature like the declaration", () => {
expect(signatureText(info)).toBe("public int sum(int a, int b) throws java.io.IOException");
expect(signatureText({ ...info, modifier: "", parameters: [], exceptions: [] })).toBe("int sum()");
});
it("tells what keeps the signature from being submitted", () => {
expect(signatureProblem(info)).toBeNull();
expect(signatureProblem({ ...info, methodName: "2x" })).toBe("Method name is not a valid identifier");
expect(signatureProblem({ ...info, returnType: " " })).toBe("Return type is not specified");
const dup = { ...info, parameters: [info.parameters[0]!, { ...info.parameters[1]!, name: "a" }] };
expect(signatureProblem(dup)).toBe("Duplicate parameter name");
const added = {
...info,
parameters: [...info.parameters, { type: "String", name: "s", defaultValue: "", originalIndex: -1 }],
};
expect(signatureProblem(added)).toBe("Default value is not specified for a new parameter");
added.parameters[2]!.defaultValue = '""';
expect(signatureProblem(added)).toBeNull();
});
it("notices changes, including reordered parameters", () => {
expect(signatureChanged(info, { ...info })).toBe(false);
expect(signatureChanged(info, { ...info, parameters: [...info.parameters].reverse() })).toBe(true);
expect(signatureChanged(info, { ...info, modifier: "private" })).toBe(true);
});
});
+199
View File
@@ -0,0 +1,199 @@
/**
* Change Signature (⌘F6) for Java: jdtls reads the method at the caret, the dialog
* (`ChangeSignatureDialog.tsx`) edits its visibility, return type, name and parameters, and
* jdtls checks the new signature and computes the edit for the method, its overrides and
* every call. Problems are confirmed like IDEA's "Problems Detected".
*/
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { create } from "zustand";
import type { MethodSignature, Pos, SignatureChanged, SignatureParameter, WorkspaceEdit } from "@/bindings";
import { whenAllSynced, whenSynced } from "@/editor/api";
import { docOf, isUnavailable, lspRequest, reportLspError } from "@/editor/lsp/lsp";
import { offsetToPos } from "@/editor/lsp/positions";
import { showHint } from "@/editor/lsp/hint";
import { openPopup } from "@/editor/lsp/popupStore";
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
import { tx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { ask } from "@/workbench/messages";
import { cannotPerform } from "./catalog";
/** Languages whose server changes signatures through the dialog. */
export const SIGNATURE_LANGUAGES = new Set(["java"]);
/** IDEA's visibility choices; jdtls spells package-private as the empty string. */
export const VISIBILITIES = ["public", "protected", "", "private"] as const;
/** A parameter row; `key` keeps React rows stable while they move. */
export interface ParameterRow extends SignatureParameter {
key: number;
}
let rowKeys = 0;
export const parameterRow = (p: SignatureParameter): ParameterRow => ({ ...p, key: ++rowKeys });
/** IDEA's new parameter: an empty type and name, `null` passed at existing calls. */
export const newParameter = (): ParameterRow =>
parameterRow({ type: "", name: "", defaultValue: "", originalIndex: -1 });
/** `public int sum(int a, int b) throws IOException`, as the dialog's preview shows it. */
export function signatureText(sig: {
modifier: string;
returnType: string;
methodName: string;
parameters: readonly SignatureParameter[];
exceptions?: readonly { type: string }[];
}): string {
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim()).join(", ");
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${params})`].filter(Boolean).join(" ");
const throws = sig.exceptions?.length ? ` throws ${sig.exceptions.map((e) => e.type).join(", ")}` : "";
return head + throws;
}
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
/** Why the edited signature can't be submitted yet, or null. */
export function signatureProblem(sig: MethodSignature): string | null {
if (!JAVA_NAME.test(sig.methodName)) return "Method name is not a valid identifier";
if (!sig.returnType.trim()) return "Return type is not specified";
const seen = new Set<string>();
for (const p of sig.parameters) {
if (!p.type.trim()) return "Parameter type is not specified";
if (!JAVA_NAME.test(p.name)) return "Parameter name is not a valid identifier";
if (seen.has(p.name)) return "Duplicate parameter name";
seen.add(p.name);
if (p.originalIndex < 0 && !p.defaultValue.trim()) return "Default value is not specified for a new parameter";
}
return null;
}
/** Whether `sig` differs from the method's current signature. */
export function signatureChanged(original: MethodSignature, sig: MethodSignature): boolean {
const same = (a: SignatureParameter, b: SignatureParameter) =>
a.type === b.type && a.name === b.name && a.originalIndex === b.originalIndex;
return (
original.modifier !== sig.modifier ||
original.returnType !== sig.returnType ||
original.methodName !== sig.methodName ||
original.parameters.length !== sig.parameters.length ||
original.parameters.some((p, i) => !same(p, sig.parameters[i]!))
);
}
export interface SignatureRequest {
seq: number;
view: EditorView;
doc: number;
pos: Pos;
/** The document `pos` refers to. */
text: Text;
info: MethodSignature;
}
export const useSignatureDialog = create<{ request: SignatureRequest | null }>(() => ({ request: null }));
let seq = 0;
let running: AbortController | null = null;
function errorText(e: unknown): string {
if (isUnavailable(e)) return unavailableText(e, "No language server available");
return e instanceof Error ? e.message : String(e);
}
/** Change Signature…: reads the method at the caret, then opens the dialog. */
export async function startChangeSignature(view: EditorView): Promise<void> {
const ctx = docOf(view);
if (!ctx) return;
if (ctx.readOnly) {
showHint(view, cannotPerform("The file is read-only"));
return;
}
running?.abort();
const run = (running = new AbortController());
await whenSynced(view);
const state = view.state;
const pos = offsetToPos(state.doc, state.selection.main.head);
const request = nextRequestId();
const abort = () => void commands.cancelRequest(request);
run.signal.addEventListener("abort", abort);
try {
const info = await lspRequest(() => commands.lspSignatureInfo(request, ctx.doc, pos));
if (run.signal.aborted || view.state.doc !== state.doc) return;
useSignatureDialog.setState({ request: { seq: ++seq, view, doc: ctx.doc, pos, text: state.doc, info } });
} catch (e) {
if (isCancelled(e) || run.signal.aborted) return;
showHint(view, cannotPerform(errorText(e)));
} finally {
run.signal.removeEventListener("abort", abort);
if (running === run) running = null;
}
}
async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
try {
await whenAllSynced();
await lspRequest(() => commands.applyWorkspaceEdit(edit));
} catch (e) {
reportLspError(view, e, true);
}
}
async function confirmProblems(messages: readonly string[]): Promise<boolean> {
const { button } = await ask({
title: "Problems Detected",
icon: "warning",
body: messages.join("\n"),
buttons: [
{ id: "continue", label: "Continue", primary: true },
{ id: "cancel", label: "Cancel" },
],
});
return button === "continue";
}
export type SignatureOutcome = { status: "done" } | { status: "stay"; error?: string };
/** Checks the new signature, confirms its problems and applies the edit, or previews it with `preview`. */
export async function changeSignature(
request: SignatureRequest,
signature: MethodSignature,
delegate: boolean,
preview: boolean,
): Promise<SignatureOutcome> {
const { view } = request;
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
let confirmation: string | null = null;
let changed: SignatureChanged;
try {
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
changed = await lspRequest(() =>
commands.lspChangeSignature(nextRequestId(), request.doc, request.pos, signature, delegate, token),
);
const fatal = changed.problems.find((p) => p.severity === "fatal");
if (fatal || (!changed.edit && !changed.confirmation))
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
if (!changed.confirmation) break;
if (!(await confirmProblems(changed.problems.map((p) => p.message)))) return { status: "stay" };
confirmation = changed.confirmation;
}
} catch (e) {
if (isCancelled(e)) return { status: "stay" };
return { status: "stay", error: errorText(e) };
}
const edit = changed.edit!;
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) return { status: "stay", error: "Nothing to change" };
if (preview) {
openPopup({
kind: "preview",
title: tx`Change Signature of '${request.info.methodName}'`,
summary,
confirmLabel: "Do Refactor",
onConfirm: () => void applyEdit(view, edit),
});
} else {
await applyEdit(view, edit);
}
return { status: "done" };
}
+15 -1
View File
@@ -2113,5 +2113,19 @@
"Controller": "Controller",
"Helper": "Helper",
"Model": "Model",
"Migration": "Migration"
"Migration": "Migration",
"Change Signature": "Change Signature",
"Visibility:": "Visibility:",
"Return type:": "Return type:",
"package-private": "package-private",
"Delegate via overloading method": "Delegate via overloading method",
"Signature Preview": "Signature Preview",
"Method name is not a valid identifier": "Method name is not a valid identifier",
"Return type is not specified": "Return type is not specified",
"Parameter type is not specified": "Parameter type is not specified",
"Parameter name is not a valid identifier": "Parameter name is not a valid identifier",
"Duplicate parameter name": "Duplicate parameter name",
"Default value is not specified for a new parameter": "Default value is not specified for a new parameter",
"Visibility": "Visibility",
"Change Signature of '{name}'": "Change Signature of '{name}'"
}
+15 -1
View File
@@ -8497,5 +8497,19 @@
"Controller": "控制器",
"Helper": "辅助模块",
"Model": "模型",
"Migration": "迁移"
"Migration": "迁移",
"Change Signature": "更改签名",
"Visibility:": "可见性:",
"Return type:": "返回类型:",
"package-private": "包私有",
"Delegate via overloading method": "通过重载方法委托",
"Signature Preview": "签名预览",
"Method name is not a valid identifier": "方法名不是有效的标识符",
"Return type is not specified": "未指定返回类型",
"Parameter type is not specified": "未指定形参类型",
"Parameter name is not a valid identifier": "形参名不是有效的标识符",
"Duplicate parameter name": "形参名重复",
"Default value is not specified for a new parameter": "未给新形参指定默认值",
"Visibility": "可见性",
"Change Signature of '{name}'": "更改 '{name}' 的签名"
}