diff --git a/MIGRATION.md b/MIGRATION.md index 0bda742..519035d 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -669,8 +669,7 @@ Java 一侧的中转已经实现并在清单里声明(第 5 节、第 5.7 节 - 阶段 J2:语言服务器由后端启动(第 5.8 节),设置中转(API-25 / API-35)与运行/调试/测试(第 5.9 节)都在后端实现。 仍未接:`java.configuration.runtimes` 只含 `tools.java` 这一个默认运行时,列出全机 JDK 等 API-23 `toolchains.list`; - argfile 规划(`execution/launch_command.rs`)没有接到 `run/start`;TestNG 结果协议不解析;导航标记(父类/实现)与 CodeLens - 没有宿主 API;测试结果摘要是英文(等 API-37);三个会话命令仍只回答 `NotSupported`。 + argfile 规划(`execution/launch_command.rs`)没有接到 `run/start`;TestNG 结果协议不解析;双向继承/实现导航标记已接入 `editor/registerActions`(`backend/src/navigation.rs`,配合 JDT LS `textDocument/implementation`、`textDocument/definition`、`java/findLinks` 与 4 枚语义图标);CodeLens 其余入口仍待接通;测试结果摘要是英文(等 API-37);三个会话命令仍只回答 `NotSupported`。 - 运行/调试/测试的接管只由后端单元测试和 Core 清单校验验证,还要对着真实宿主(主仓库 Java 拆分分支)跑通: 打开 Java 工程后出现行内 Run/Debug 标记、点击能启动并在 Run 窗口看到输出、调试能在断点停下、JUnit 测试结束后弹出摘要、 堆栈行可点击跳转。 diff --git a/README.md b/README.md index f2d7e71..4e53196 100644 --- a/README.md +++ b/README.md @@ -245,8 +245,8 @@ Spring/MyBatis 等既有能力不属于本轮 Maven 验收范围。 | 事实 | 级别 | 来源 | 内容 | | --- | --- | --- | --- | -| 关键操作成功:`runConfig.selectJava`、`debug.javaTestLaunch`、`execution.planLaunchCommand`、`java.prepareLaunch`、`java.resolveLaunch`、`java.runAction`、`java.rerun`、`languageImport.settingsChanged`(`backend/src/lib.rs` 的 `KEY_OPERATIONS`) | INFO | SDK 自动 | 操作 ID、耗时 | -| 其余函数成功(编辑器驱动或启动时的读取,如 `java.runMarkers`、`java.codeVision`、`spring.index`、`settings.view`) | 不记录 | `suppress_success_diagnostics`(`backend/src/lib.rs`) | — | +| 关键操作成功:`runConfig.selectJava`、`debug.javaTestLaunch`、`execution.planLaunchCommand`、`java.prepareLaunch`、`java.resolveLaunch`、`java.runAction`、`java.rerun`、`java.navigation.invoke`、`languageImport.settingsChanged`(`backend/src/lib.rs` 的 `KEY_OPERATIONS`) | INFO | SDK 自动 | 操作 ID、耗时 | +| 其余函数成功(编辑器驱动或启动时的读取,如 `java.runMarkers`、`java.codeVision`、`java.navigation.collect`、`spring.index`、`settings.view`) | 不记录 | `suppress_success_diagnostics`(`backend/src/lib.rs`) | — | | 任一函数失败 | ERROR | SDK 自动 | 类别为 `pluginErrorCode`(如 `java.invalidRequest`;`languageImport.settingsChanged` 的 `relay.caller_missing`、`relay.context_missing`、`relay.invalid_params`)、耗时;不含消息与 `details` | | 领域命令失败类别 | ERROR | `plugin_error_code` | `java.invalidRequest`、`java.workspaceNotFound`、`java.permissionDenied`、`java.notSupported`、`java.runtimeMissing`、`java.processStartFailed`、`java.processFailed`、`java.parseFailed`、`java.cancelled`、`java.timedOut`、`java.connectionClosed`、`java.unknown`;SDK 识别的取消不记录 | | JDT 启动规划失败 | ERROR | SDK 自动 | `launch.invalid_params`、`launch.package_unavailable`、`launch.resource_missing`、`launch.configuration_failed`、`launch.runtime_too_old`(语言服务 JDK 低于本插件要求的 25);运行环境问题使用下行类别 | @@ -259,6 +259,8 @@ Spring/MyBatis 等既有能力不属于本轮 Maven 验收范围。 | 插件存储清理失败 | WARN(`degraded`) | `crates/java-domain/src/host/diagnostics.rs`(`host::diagnostics`) | 类别 `storage.cleanup_failed.<阶段>`(阶段为 `jdt-configuration`、`jdt-settings`、`java-argfile-remove`),计数 | | 运行动作失败 | ERROR | SDK 自动 | `backend/src/run.rs` 的 `RUN_ERROR_CODES`:`run.invalid_params`、`run.context_missing`、`run.workspace_unavailable`、`run.language_server_failed`、`run.build_failed`、`run.no_tests`、`run.port_unavailable`、`run.host_rejected`、`run.classpath_failed` | | 动作注册、上下文读取或测试结果摘要降级 | WARN | SDK `degraded` | `RUN_CATEGORIES`:`run.actions_registration_failed`、`run.contexts_unavailable`、`run.result_summary_failed` | +| 双向导航动作失败 | ERROR | SDK 自动 | `backend/src/navigation.rs` 的 `NAV_ERROR_CODES`:`nav.invalid_params`、`nav.context_missing`、`nav.workspace_unavailable`、`nav.language_server_failed` | +| 导航动作注册或上下文读取降级 | WARN | SDK `degraded` | `NAV_CATEGORIES`:`nav.actions_registration_failed`、`nav.contexts_unavailable` | | 冷索引动作查询延迟/恢复、自动刷新耗尽 | WARN | SDK `degraded` / `recovered` | `run.actions_query_deferred`、`run.actions_query_exhausted`、`run.actions_progress_limit`,每个失败周期记录延迟及恢复/耗尽,不含工作区内容 | | 设置页预览参数不合法或未识别草稿/生效值 | ERROR / WARN(`degraded`) | `backend/src/settings_view.rs`(`VIEW_ERROR_CODES`、`VIEW_CATEGORIES`) | 错误类别 `settings_view.invalid_params`;非预期设置值计数通过 `settings_view.setting_unrecognized` 降级上报并回退默认显示,不含设置路径或文本 | | 宿主启动 JDT LS、java-debug、项目 JVM | 宿主决定 | 声明式贡献/Run 生命周期 | 插件不重复发送启动终态;上游 stderr 由宿主按 DEBUG 接收 | diff --git a/backend/src/lib.rs b/backend/src/lib.rs index 14cab74..3fadc8f 100644 --- a/backend/src/lib.rs +++ b/backend/src/lib.rs @@ -55,6 +55,7 @@ pub mod launch; pub mod library_settings; pub mod managed_runtimes; pub mod module_structure; +pub mod navigation; pub mod plugin_functions; pub mod project_model; pub mod project_settings; @@ -103,6 +104,7 @@ pub const KEY_OPERATIONS: &[&str] = &[ "execution.planLaunchCommand", "java.prepareLaunch", LAUNCH_FUNCTION_ID, + navigation::INVOKE_FUNCTION_ID, RERUN_FUNCTION_ID, RUN_ACTION_FUNCTION_ID, SETTINGS_CHANGED_FUNCTION_ID, @@ -148,9 +150,14 @@ pub fn backend() -> Result { })?; backend.suppress_success_diagnostics(class_content::CONTENT_FUNCTION)?; let run_session = Arc::new(RunSession::new(backend.handle(), Arc::clone(&session))); + let nav_session = Arc::new(navigation::NavigationSession::new( + backend.handle(), + Arc::clone(&session), + )); let handle = backend.handle(); backend.on_host_notification(LANGUAGE_SERVER_STATE_NOTIFICATION, { let run_session = Arc::clone(&run_session); + let nav_session = Arc::clone(&nav_session); let session = Arc::clone(&session); let content_session = Arc::clone(&content_session); move |params| { @@ -164,6 +171,7 @@ pub fn backend() -> Result { session.did_change_state(¶ms, &report); content_session.sync_reporting(&session, &report); run_session.sync_contexts_reporting(&report); + nav_session.sync_contexts_reporting(&report); Ok(()) } })?; @@ -212,20 +220,24 @@ pub fn backend() -> Result { }; backend.on_initialize({ let run_session = Arc::clone(&run_session); + let nav_session = Arc::clone(&nav_session); let report = Arc::clone(&report); move |_initialize| { run_session.sync_after_initialize(Arc::clone(&report)); + nav_session.sync_after_initialize(Arc::clone(&report)); Ok(()) } }); backend.on_contexts_changed({ let run_session = Arc::clone(&run_session); + let nav_session = Arc::clone(&nav_session); let report = Arc::clone(&report); let content_session = Arc::clone(&content_session); let session = Arc::clone(&session); move |_params| { content_session.sync_reporting(&session, &*report); run_session.sync_contexts_reporting(&*report); + nav_session.sync_contexts_reporting(&*report); Ok(()) } }); @@ -238,9 +250,11 @@ pub fn backend() -> Result { })?; backend.on_host_notification(LANGUAGE_SERVER_NOTIFICATION, { let run_session = Arc::clone(&run_session); + let nav_session = Arc::clone(&nav_session); let report = Arc::clone(&report); move |params| { run_session.did_receive_notification(¶ms, &*report); + nav_session.did_receive_notification(¶ms, &*report); Ok(()) } })?; @@ -249,6 +263,15 @@ pub fn backend() -> Result { move |params, context| run::collect_actions_function(&run_session, params, context) })?; backend.suppress_success_diagnostics(COLLECT_FUNCTION_ID)?; + backend.function(navigation::COLLECT_FUNCTION_ID, { + let nav_session = Arc::clone(&nav_session); + move |params, context| navigation::collect_actions_function(&nav_session, params, context) + })?; + backend.suppress_success_diagnostics(navigation::COLLECT_FUNCTION_ID)?; + backend.function(navigation::INVOKE_FUNCTION_ID, { + let nav_session = Arc::clone(&nav_session); + move |params, context| navigation::invoke_action_function(&nav_session, params, context) + })?; backend.function(RUN_ACTION_FUNCTION_ID, { let run_session = Arc::clone(&run_session); move |params, context| run::run_action_function(&run_session, params, context) @@ -446,6 +469,8 @@ mod tests { .chain(managed_runtimes::ERROR_CODES) .chain(run::RUN_ERROR_CODES) .chain(run::RUN_CATEGORIES) + .chain(navigation::NAV_ERROR_CODES) + .chain(navigation::NAV_CATEGORIES) .chain(settings_view::VIEW_ERROR_CODES) .chain(settings_view::VIEW_CATEGORIES) { @@ -478,6 +503,8 @@ mod tests { COLLECT_FUNCTION_ID, RUN_ACTION_FUNCTION_ID, RERUN_FUNCTION_ID, + navigation::COLLECT_FUNCTION_ID, + navigation::INVOKE_FUNCTION_ID, ]) .collect(); let distinct: std::collections::BTreeSet<&str> = KEY_OPERATIONS.iter().copied().collect(); diff --git a/backend/src/navigation.rs b/backend/src/navigation.rs new file mode 100644 index 0000000..8250cd2 --- /dev/null +++ b/backend/src/navigation.rs @@ -0,0 +1,936 @@ +//! Bidirectional inheritance/implementation navigation actions for Java files. +//! +//! Registers an `editor/registerActions` collector for `.java` files when JDT LS +//! is active. Syntax candidates identify types and methods whose relation must +//! still be confirmed semantically by JDT LS (`textDocument/implementation`, +//! `java/findLinks`, `textDocument/definition`) before a gutter icon is shown. + +use crate::run::{file_uri, Report}; +use crate::settings_session::{SettingsSession, REQUEST_METHOD, SERVER_ID}; +use lithe_java_domain::lsp::languages::java_navigation_syntax::{ + navigation_candidates, JavaNavigationCandidate, JavaNavigationCandidateKind, +}; +use lithe_java_domain::lsp::languages::jdt_navigation::{ + extract_normalized_locations, NormalizedNavigationLocation, +}; +use lithe_plugin_sdk::{ + BackendHandle, Context, FunctionError, Host, PluginError, SdkError, Subscription, Value, + WorkspaceContext, +}; +use serde_json::json; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::thread; +use std::time::{Duration, Instant}; + +/// Registration ID of the Java navigation gutter actions binding per workspace. +pub const ACTIONS_BINDING_ID: &str = "java.navigation"; + +/// Function the host calls on document idle to collect navigation gutter actions. +pub const COLLECT_FUNCTION_ID: &str = "java.navigation.collect"; + +/// Function the host calls when the user clicks a navigation gutter icon. +pub const INVOKE_FUNCTION_ID: &str = "java.navigation.invoke"; + +const LIST_CONTEXTS_METHOD: &str = "lithe/host/workspace/listContexts"; +const GET_CAPABILITIES_METHOD: &str = "lithe/host/getCapabilities"; +const LANGUAGE_STATUS_METHOD: &str = "language/status"; +const SERVICE_READY_TYPE: &str = "ServiceReady"; + +const SYNC_RETRY_INTERVAL: Duration = Duration::from_millis(250); +const SYNC_RETRY_ATTEMPTS: u32 = 40; +const COLLECT_BUDGET: Duration = Duration::from_millis(4_500); +const COLLECT_LSP_TIMEOUT_MS: u64 = 1_500; +const INVOKE_LSP_TIMEOUT_MS: u64 = 5_000; +const MAX_COLLECT_CANDIDATES: usize = 40; +const MAX_ACTIONS: usize = 1000; + +/// Plugin error code for malformed navigation function arguments. +pub const NAV_INVALID_PARAMS: &str = "nav.invalid_params"; + +/// Plugin error code when a navigation function is called without a workspace context. +pub const NAV_CONTEXT_MISSING: &str = "nav.context_missing"; + +/// Plugin error code when a workspace has no accessible local folder. +pub const NAV_WORKSPACE_UNAVAILABLE: &str = "nav.workspace_unavailable"; + +/// Plugin error code when JDT LS rejects or fails a click-triggered navigation query. +pub const NAV_LANGUAGE_SERVER_FAILED: &str = "nav.language_server_failed"; + +/// Every plugin error code the navigation functions answer with. +pub const NAV_ERROR_CODES: &[&str] = &[ + NAV_INVALID_PARAMS, + NAV_CONTEXT_MISSING, + NAV_WORKSPACE_UNAVAILABLE, + NAV_LANGUAGE_SERVER_FAILED, +]; + +/// Category reported when registering the navigation actions binding failed. +pub const NAV_ACTIONS_REGISTRATION_FAILED: &str = "nav.actions_registration_failed"; + +/// Category reported when workspace contexts could not be listed for navigation sync. +pub const NAV_CONTEXTS_UNAVAILABLE: &str = "nav.contexts_unavailable"; + +/// Every degraded category this module reports. +pub const NAV_CATEGORIES: &[&str] = &[NAV_ACTIONS_REGISTRATION_FAILED, NAV_CONTEXTS_UNAVAILABLE]; + +struct Registration { + generation: u64, + subscription: Subscription, +} + +/// Host icon support negotiated once from `lithe/host/getCapabilities`. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct ActionIconPalette { + pub semantic: bool, +} + +impl ActionIconPalette { + /// Inspects `services.editor.options.actionIcons` for the four dedicated + /// IDEA-style navigation tokens (`navigate-implemented`, + /// `navigate-implementing`, `navigate-overridden`, `navigate-overriding`), + /// falling back to `navigate-implementations` / `navigate-super` when absent. + pub fn from_capabilities(capabilities: &Value) -> Self { + let Some(icons) = capabilities + .pointer("/services/editor/options/actionIcons") + .and_then(Value::as_array) + else { + return Self { semantic: false }; + }; + let has = |token: &str| icons.iter().any(|entry| entry.as_str() == Some(token)); + let semantic = has("navigate-implemented") + && has("navigate-implementing") + && has("navigate-overridden") + && has("navigate-overriding"); + Self { semantic } + } + + /// Selects the host-supported icon token for `(direction, relation)`. + pub fn icon(self, direction: &str, relation: &str) -> &'static str { + if self.semantic { + match (direction, relation) { + ("down", "interface") => "navigate-implemented", + ("up", "interface") => "navigate-implementing", + ("down", _) => "navigate-overridden", + _ => "navigate-overriding", + } + } else if direction == "down" { + "navigate-implementations" + } else { + "navigate-super" + } + } +} + +/// Coordinates editor-action registrations for Java implementation/super navigation. +pub struct NavigationSession { + handle: BackendHandle, + settings: Arc, + registrations: Mutex>, + palette: Mutex>, +} + +impl NavigationSession { + pub fn new(handle: BackendHandle, settings: Arc) -> Self { + Self { + handle, + settings, + registrations: Mutex::new(HashMap::new()), + palette: Mutex::new(None), + } + } + + fn icon_palette(&self, host: &Host) -> ActionIconPalette { + if let Some(cached) = *lock(&self.palette) { + return cached; + } + match host.request(GET_CAPABILITIES_METHOD, json!({})) { + Ok(capabilities) => { + let palette = ActionIconPalette::from_capabilities(&capabilities); + *lock(&self.palette) = Some(palette); + palette + } + Err(_) => ActionIconPalette { semantic: false }, + } + } + + /// Brings active workspace context bindings in line with running JDT LS instances. + pub fn sync_contexts(&self) -> Result { + let host = self.handle.host(); + let listed = host.request(LIST_CONTEXTS_METHOD, json!({}))?; + let contexts = listed + .get("contexts") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let mut registrations = lock(&self.registrations); + let mut seen = HashSet::new(); + let mut failures = 0; + for context in &contexts { + let Ok(reference) = WorkspaceContext::from_value(context) else { + continue; + }; + if !self.settings.server_is_running(&reference) { + continue; + } + seen.insert(reference.context_id().to_owned()); + if let Some(existing) = registrations.get(reference.context_id()) { + if existing.generation == reference.generation() { + continue; + } + if let Some(stale) = registrations.remove(reference.context_id()) { + let _ = stale.subscription.dispose(); + } + } + let params = json!({ + "id": ACTIONS_BINDING_ID, + "function": COLLECT_FUNCTION_ID, + "selector": {"fileExtensions": ["java"], "fileNames": []}, + }); + match host.editor().register_actions(&reference, params) { + Ok(subscription) => { + registrations.insert( + reference.context_id().to_owned(), + Registration { + generation: reference.generation(), + subscription, + }, + ); + } + Err(_) => failures += 1, + } + } + let gone: Vec = registrations + .keys() + .filter(|id| !seen.contains(*id)) + .cloned() + .collect(); + for id in gone { + if let Some(stale) = registrations.remove(&id) { + let _ = stale.subscription.dispose(); + } + } + Ok(failures) + } + + pub fn sync_contexts_reporting(&self, report: &dyn Fn(&str, u64)) -> bool { + match self.sync_contexts() { + Ok(0) => true, + Ok(failures) => { + report(NAV_ACTIONS_REGISTRATION_FAILED, failures); + true + } + Err(_) => { + report(NAV_CONTEXTS_UNAVAILABLE, 1); + false + } + } + } + + /// Performs initial binding sync once initialize completes. + pub fn sync_after_initialize(self: &Arc, report: Report) { + let session = Arc::clone(self); + thread::Builder::new() + .name("java-nav-sync".into()) + .spawn(move || { + for attempt in 0..SYNC_RETRY_ATTEMPTS { + thread::sleep(SYNC_RETRY_INTERVAL); + match session.sync_contexts() { + Ok(0) => return, + Ok(failures) => { + report(NAV_ACTIONS_REGISTRATION_FAILED, failures); + return; + } + Err(_) if attempt + 1 < SYNC_RETRY_ATTEMPTS => continue, + Err(_) => report(NAV_CONTEXTS_UNAVAILABLE, 1), + } + } + }) + .ok(); + } + + /// Refreshes bindings when JDT LS finishes ServiceReady or imports modules. + pub fn did_receive_notification(&self, params: &Value, report: &dyn Fn(&str, u64)) { + if !is_refresh_notification(params) { + return; + } + let Ok(reference) = WorkspaceContext::from_value(¶ms["context"]) else { + return; + }; + let Some(generation) = params.get("generation").and_then(Value::as_u64) else { + return; + }; + if !self + .settings + .accepts_server_notification(&reference, generation) + { + return; + } + if let Some(stale) = lock(&self.registrations).remove(reference.context_id()) { + let _ = stale.subscription.dispose(); + } + self.sync_contexts_reporting(report); + } +} + +/// Collects navigation actions for one `.java` document without blocking indefinitely. +pub fn collect_actions_function( + session: &NavigationSession, + params: Value, + context: &Context, +) -> Result { + context.check_cancelled()?; + let reference = workspace_context(context)?; + if !session.settings.server_is_running(reference) { + return Ok(json!({ "actions": [] })); + } + let path = params + .pointer("/document/path") + .and_then(Value::as_str) + .filter(|path| !path.is_empty()) + .ok_or_else(|| failure(NAV_INVALID_PARAMS, "The document has no path."))?; + let text = params + .get("text") + .and_then(Value::as_str) + .unwrap_or_default(); + if text.is_empty() { + return Ok(json!({ "actions": [] })); + } + + let root = workspace_root(context.host(), reference)?; + let doc_uri = file_uri(&root.join(path))?; + let mut candidates = navigation_candidates(text); + if candidates.is_empty() { + return Ok(json!({ "actions": [] })); + } + // Verify parent (`up`) candidates ahead of child (`down`) candidates when + // capped, so child classes keep override arrows even in huge files. + candidates.sort_by_key(|candidate| (candidate.direction != "up", candidate.line)); + candidates.truncate(MAX_COLLECT_CANDIDATES); + + let host = context.host(); + let palette = session.icon_palette(host); + let started = Instant::now(); + let mut resolved = Vec::new(); + + for candidate in candidates { + context.check_cancelled()?; + if started.elapsed() >= COLLECT_BUDGET { + break; + } + match resolve_candidate_targets( + host, + reference, + &doc_uri, + &candidate, + COLLECT_LSP_TIMEOUT_MS, + ) { + Ok(targets) => { + if !targets.is_empty() { + resolved.push(ResolvedCandidate { candidate, targets }); + } + } + Err(error) if is_transient_code(error.code()) => { + return Ok(json!({ + "actions": build_navigation_actions(&doc_uri, resolved, palette) + })); + } + Err(_) => continue, + } + } + + Ok(json!({ + "actions": build_navigation_actions(&doc_uri, resolved, palette) + })) +} + +/// Resolves fresh target locations when the user clicks a navigation gutter icon. +pub fn invoke_action_function( + _session: &NavigationSession, + params: Value, + context: &Context, +) -> Result { + context.check_cancelled()?; + let reference = workspace_context(context)?; + let data = params + .get("data") + .filter(|value| value.is_object()) + .ok_or_else(|| failure(NAV_INVALID_PARAMS, "The click carries no navigation data."))?; + let target = InvokeRequest::from_value(data)?; + let host = context.host(); + let locations = query_invoke_locations(host, reference, &target, INVOKE_LSP_TIMEOUT_MS) + .map_err(|error| failure(NAV_LANGUAGE_SERVER_FAILED, error.message().to_owned()))?; + let reveal_locations: Vec = locations + .iter() + .map(NormalizedNavigationLocation::to_lsp_location_value) + .collect(); + Ok(json!({ + "reveal": { + "locations": reveal_locations + } + })) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct InvokeRequest { + uri: String, + line: i64, + utf16_column: i64, + kind: JavaNavigationCandidateKind, + direction: String, + super_positions: Vec<(i64, i64)>, +} + +impl InvokeRequest { + fn from_value(value: &Value) -> Result { + let uri = value + .get("uri") + .and_then(Value::as_str) + .filter(|uri| !uri.is_empty()) + .ok_or_else(|| failure(NAV_INVALID_PARAMS, "The action names no document URI."))? + .to_owned(); + let line = value + .get("line") + .and_then(Value::as_i64) + .ok_or_else(|| failure(NAV_INVALID_PARAMS, "The action names no line."))?; + let utf16_column = value + .get("utf16Column") + .and_then(Value::as_i64) + .ok_or_else(|| failure(NAV_INVALID_PARAMS, "The action names no column."))?; + let kind = match value.get("kind").and_then(Value::as_str) { + Some("type") => JavaNavigationCandidateKind::Type, + Some("method") => JavaNavigationCandidateKind::Method, + _ => { + return Err(failure( + NAV_INVALID_PARAMS, + "The action names no declaration kind.", + )) + } + }; + let direction = match value.get("direction").and_then(Value::as_str) { + Some(dir @ ("up" | "down")) => dir.to_owned(), + _ => { + return Err(failure( + NAV_INVALID_PARAMS, + "The action names no direction.", + )) + } + }; + let super_positions = value + .get("superPositions") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(|pair| { + let arr = pair.as_array()?; + Some((arr.first()?.as_i64()?, arr.get(1)?.as_i64()?)) + }) + .collect() + }) + .unwrap_or_default(); + Ok(Self { + uri, + line, + utf16_column, + kind, + direction, + super_positions, + }) + } +} + +fn query_invoke_locations( + host: &Host, + reference: &WorkspaceContext, + target: &InvokeRequest, + timeout_milliseconds: u64, +) -> Result, SdkError> { + let candidate = JavaNavigationCandidate { + line: target.line, + utf16_column: target.utf16_column, + direction: if target.direction == "down" { + "down" + } else { + "up" + }, + relation: "inheritance", + kind: target.kind, + super_positions: target.super_positions.clone(), + }; + resolve_candidate_targets( + host, + reference, + &target.uri, + &candidate, + timeout_milliseconds, + ) +} + +fn resolve_candidate_targets( + host: &Host, + reference: &WorkspaceContext, + doc_uri: &str, + candidate: &JavaNavigationCandidate, + timeout_milliseconds: u64, +) -> Result, SdkError> { + let raw_responses = if candidate.direction == "down" { + vec![lsp_request( + host, + reference, + "textDocument/implementation", + json!({ + "textDocument": { "uri": doc_uri }, + "position": { "line": candidate.line, "character": candidate.utf16_column } + }), + timeout_milliseconds, + )?] + } else if candidate.kind == JavaNavigationCandidateKind::Type + && !candidate.super_positions.is_empty() + { + let mut responses = Vec::with_capacity(candidate.super_positions.len()); + for &(super_line, super_col) in &candidate.super_positions { + responses.push(lsp_request( + host, + reference, + "textDocument/definition", + json!({ + "textDocument": { "uri": doc_uri }, + "position": { "line": super_line, "character": super_col } + }), + timeout_milliseconds, + )?); + } + responses + } else { + vec![lsp_request( + host, + reference, + "java/findLinks", + json!({ + "type": "superImplementation", + "position": { + "textDocument": { "uri": doc_uri }, + "position": { "line": candidate.line, "character": candidate.utf16_column } + } + }), + timeout_milliseconds, + )?] + }; + + let mut targets = Vec::new(); + let mut seen = HashSet::new(); + for value in raw_responses { + for loc in extract_normalized_locations(&value) { + if is_self_location(&loc, doc_uri, candidate.line) { + continue; + } + let key = (loc.uri.clone(), loc.start_line, loc.start_character); + if seen.insert(key) { + targets.push(loc); + } + } + } + Ok(targets) +} + +fn is_self_location( + loc: &NormalizedNavigationLocation, + doc_uri: &str, + candidate_line: i64, +) -> bool { + loc.uri == doc_uri && i64::from(loc.start_line) == candidate_line +} + +/// One resolved syntax candidate paired with verified JDT LS target locations. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct ResolvedCandidate { + pub candidate: JavaNavigationCandidate, + pub targets: Vec, +} + +struct MergedAction { + line: i64, + utf16_column: i64, + direction: &'static str, + relation: &'static str, + kind: JavaNavigationCandidateKind, + super_positions: Vec<(i64, i64)>, + targets: Vec, +} + +/// Converts resolved candidates into contract-compliant editor actions, +/// merging multiple super clauses on the same `(line, direction)` into a single +/// gutter lane icon while keeping `up` and `down` in separate lanes. +pub fn build_navigation_actions( + doc_uri: &str, + resolved: Vec, + palette: ActionIconPalette, +) -> Vec { + let mut merged: BTreeMap<(i64, &'static str), MergedAction> = BTreeMap::new(); + for entry in resolved { + let targets: Vec<_> = entry + .targets + .into_iter() + .filter(|loc| !is_self_location(loc, doc_uri, entry.candidate.line)) + .collect(); + if targets.is_empty() { + continue; + } + let key = (entry.candidate.line, entry.candidate.direction); + let slot = merged.entry(key).or_insert_with(|| MergedAction { + line: entry.candidate.line, + utf16_column: entry.candidate.utf16_column, + direction: entry.candidate.direction, + relation: entry.candidate.relation, + kind: entry.candidate.kind, + super_positions: Vec::new(), + targets: Vec::new(), + }); + if entry.candidate.relation == "interface" { + slot.relation = "interface"; + } + for pos in entry.candidate.super_positions { + if !slot.super_positions.contains(&pos) { + slot.super_positions.push(pos); + } + } + for target in targets { + let dup = slot.targets.iter().any(|existing| { + existing.uri == target.uri + && existing.start_line == target.start_line + && existing.start_character == target.start_character + }); + if !dup { + slot.targets.push(target); + } + } + } + + merged + .into_values() + .take(MAX_ACTIONS) + .map(|item| { + let title = + format_action_title(item.direction, item.relation, item.kind, &item.targets); + let icon = palette.icon(item.direction, item.relation); + let line_one_based = item.line + 1; + let mut invoke_params = json!({ + "uri": doc_uri, + "line": item.line, + "utf16Column": item.utf16_column, + "kind": match item.kind { + JavaNavigationCandidateKind::Type => "type", + JavaNavigationCandidateKind::Method => "method", + }, + "direction": item.direction, + }); + if !item.super_positions.is_empty() { + invoke_params["superPositions"] = json!(item.super_positions); + } + json!({ + "id": format!("nav-{}-{}", item.direction, item.line), + "range": { + "start": { "line": line_one_based, "column": 1 }, + "end": { "line": line_one_based, "column": 1 } + }, + "title": title, + "icon": icon, + "invoke": { + "functionID": INVOKE_FUNCTION_ID, + "params": invoke_params, + } + }) + }) + .collect() +} + +fn format_action_title( + direction: &str, + relation: &str, + kind: JavaNavigationCandidateKind, + targets: &[NormalizedNavigationLocation], +) -> String { + let mut labels = Vec::new(); + for target in targets { + if let Some(label) = target.short_label() { + if !labels.contains(&label) { + labels.push(label); + } + } + } + let summary = match labels.len() { + 0 => String::new(), + 1..=3 => labels.join(", "), + n => format!("{} (+{})", labels[..2].join(", "), n - 2), + }; + let verb = match (direction, relation, kind) { + ("down", "interface", _) => "Implemented by", + ("down", _, _) => "Overridden by", + ("up", "interface", _) => "Implements", + ("up", _, JavaNavigationCandidateKind::Type) => "Extends", + _ => "Overrides", + }; + if summary.is_empty() { + format!("{verb} ({})", targets.len()) + } else { + format!("{verb} {summary}") + } +} + +fn lsp_request( + host: &Host, + reference: &WorkspaceContext, + method: &str, + params: Value, + timeout_milliseconds: u64, +) -> Result { + let answer = host.request( + REQUEST_METHOD, + json!({ + "context": reference.to_value(), + "serverID": SERVER_ID, + "method": method, + "params": params, + "timeoutMilliseconds": timeout_milliseconds, + }), + )?; + Ok(answer.get("value").cloned().unwrap_or(Value::Null)) +} + +fn is_transient_code(code: &str) -> bool { + matches!( + code, + "plugin.host.languageServerUnavailable" + | "plugin.host.busy" + | "plugin.host.timeout" + | "plugin.host.cancelled" + | "plugin.host.languageServerError" + ) +} + +fn is_refresh_notification(params: &Value) -> bool { + if params.get("serverID").and_then(Value::as_str) != Some(SERVER_ID) { + return false; + } + match params.get("method").and_then(Value::as_str) { + Some(LANGUAGE_STATUS_METHOD) => { + params.pointer("/params/type").and_then(Value::as_str) == Some(SERVICE_READY_TYPE) + } + Some("language/eventNotification") => { + let event = ¶ms["params"]["eventType"]; + matches!( + event.as_str(), + Some("ClasspathUpdated" | "ProjectsImported" | "ProjectsDeleted") + ) || matches!(event.as_u64(), Some(100 | 200 | 210)) + } + _ => false, + } +} + +fn workspace_context(context: &Context) -> Result<&WorkspaceContext, FunctionError> { + context + .workspace_context() + .ok_or_else(|| failure(NAV_CONTEXT_MISSING, "The call names no workspace.")) +} + +fn workspace_root(host: &Host, reference: &WorkspaceContext) -> Result { + let context = host.workspace().get_context(reference)?; + context + .pointer("/folders/0/path") + .and_then(Value::as_str) + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .ok_or_else(|| { + failure( + NAV_WORKSPACE_UNAVAILABLE, + "The workspace has no local folder.", + ) + }) +} + +fn failure(code: &'static str, message: impl Into) -> FunctionError { + PluginError::new(code, message).into() +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn capability_negotiation_picks_semantic_or_legacy_icons() { + let modern = ActionIconPalette::from_capabilities(&json!({ + "services": { + "editor": { + "options": { + "actionIcons": [ + "run", + "debug", + "navigate-super", + "navigate-implementations", + "navigate-implemented", + "navigate-implementing", + "navigate-overridden", + "navigate-overriding" + ] + } + } + } + })); + assert!(modern.semantic); + assert_eq!(modern.icon("down", "interface"), "navigate-implemented"); + assert_eq!(modern.icon("up", "interface"), "navigate-implementing"); + assert_eq!(modern.icon("down", "inheritance"), "navigate-overridden"); + assert_eq!(modern.icon("up", "inheritance"), "navigate-overriding"); + + let legacy = ActionIconPalette::from_capabilities(&json!({ + "services": { "editor": { "options": { "actionIcons": ["navigate-super", "navigate-implementations"] } } } + })); + assert!(!legacy.semantic); + assert_eq!(legacy.icon("down", "interface"), "navigate-implementations"); + assert_eq!(legacy.icon("up", "inheritance"), "navigate-super"); + } + + #[test] + fn build_navigation_actions_keeps_dual_lanes_and_merges_class_supers() { + let doc_uri = "file:///workspace/CustomGreeter.java"; + let resolved = vec![ + ResolvedCandidate { + candidate: JavaNavigationCandidate { + line: 10, + utf16_column: 6, + direction: "up", + relation: "inheritance", + kind: JavaNavigationCandidateKind::Type, + super_positions: vec![(10, 28)], + }, + targets: vec![NormalizedNavigationLocation { + uri: "file:///workspace/BaseGreeter.java".into(), + start_line: 0, + start_character: 6, + end_line: 0, + end_character: 17, + display_name: None, + }], + }, + ResolvedCandidate { + candidate: JavaNavigationCandidate { + line: 10, + utf16_column: 6, + direction: "up", + relation: "interface", + kind: JavaNavigationCandidateKind::Type, + super_positions: vec![(10, 51)], + }, + targets: vec![NormalizedNavigationLocation { + uri: "file:///workspace/Greeter.java".into(), + start_line: 0, + start_character: 10, + end_line: 0, + end_character: 17, + display_name: None, + }], + }, + ResolvedCandidate { + candidate: JavaNavigationCandidate { + line: 12, + utf16_column: 18, + direction: "up", + relation: "interface", + kind: JavaNavigationCandidateKind::Method, + super_positions: Vec::new(), + }, + targets: vec![NormalizedNavigationLocation { + uri: "file:///workspace/BaseGreeter.java".into(), + start_line: 2, + start_character: 18, + end_line: 2, + end_character: 23, + display_name: Some("BaseGreeter.greet()".into()), + }], + }, + ResolvedCandidate { + candidate: JavaNavigationCandidate { + line: 12, + utf16_column: 18, + direction: "down", + relation: "inheritance", + kind: JavaNavigationCandidateKind::Method, + super_positions: Vec::new(), + }, + targets: vec![ + NormalizedNavigationLocation { + uri: doc_uri.into(), + start_line: 12, + start_character: 18, + end_line: 12, + end_character: 23, + display_name: None, + }, + NormalizedNavigationLocation { + uri: "file:///workspace/FormalGreeter.java".into(), + start_line: 5, + start_character: 18, + end_line: 5, + end_character: 23, + display_name: None, + }, + ], + }, + ]; + + let actions = + build_navigation_actions(doc_uri, resolved, ActionIconPalette { semantic: true }); + + assert_eq!(actions.len(), 3); + // Line 10 class gets single merged up action preferring `navigate-implementing` and carrying both super positions. + assert_eq!(actions[0]["icon"], "navigate-implementing"); + assert_eq!(actions[0]["range"]["start"]["line"], 11); + assert_eq!(actions[0]["title"], "Implements BaseGreeter, Greeter"); + assert_eq!( + actions[0]["invoke"]["params"]["superPositions"], + json!([[10, 28], [10, 51]]) + ); + // Line 12 method keeps separate down and up icons (BTreeMap sorts "down" before "up"). + assert_eq!(actions[1]["icon"], "navigate-overridden"); + assert_eq!(actions[1]["title"], "Overridden by FormalGreeter"); + assert_eq!(actions[2]["icon"], "navigate-implementing"); + assert_eq!(actions[2]["title"], "Implements BaseGreeter.greet()"); + } + + #[test] + fn title_formatting_caps_labels_and_rejects_malformed_invoke_params() { + let targets: Vec<_> = (1..=4) + .map(|idx| NormalizedNavigationLocation { + uri: format!("file:///workspace/Impl{idx}.java"), + start_line: 0, + start_character: 0, + end_line: 0, + end_character: 5, + display_name: None, + }) + .collect(); + let summary = format_action_title( + "down", + "interface", + JavaNavigationCandidateKind::Type, + &targets, + ); + assert_eq!(summary, "Implemented by Impl1, Impl2 (+2)"); + + assert!(InvokeRequest::from_value(&json!({})).is_err()); + assert!(InvokeRequest::from_value(&json!({ + "uri": "file:///workspace/A.java", + "line": 1, + "utf16Column": 2, + "kind": "unknown", + "direction": "down" + })) + .is_err()); + } +} diff --git a/backend/tests/session.rs b/backend/tests/session.rs index 705807c..f3b69bc 100644 --- a/backend/tests/session.rs +++ b/backend/tests/session.rs @@ -88,6 +88,59 @@ impl Host { self.invoke_with_logs(id, function, params).0 } + fn respond(&mut self, id: Value, result: Value) { + let body = json!({"jsonrpc": "2.0", "id": id, "result": result}).to_string(); + self.input + .as_mut() + .expect("open input") + .write_all(format!("Content-Length: {}\r\n\r\n{body}", body.len()).as_bytes()) + .expect("write response to backend"); + } + + fn notify(&mut self, method: &str, params: Value) { + let body = json!({"jsonrpc": "2.0", "method": method, "params": params}).to_string(); + self.input + .as_mut() + .expect("open input") + .write_all(format!("Content-Length: {}\r\n\r\n{body}", body.len()).as_bytes()) + .expect("write notification to backend"); + } + + fn run_until( + &mut self, + mut stop: impl FnMut(&Value) -> bool, + mut on_host_request: impl FnMut(&str, &Value) -> Value, + ) -> (Value, Vec) { + let mut logs = Vec::new(); + loop { + let frame = self + .frames + .recv_timeout(WAIT) + .expect("a frame from the backend in time"); + if frame.get("method").and_then(Value::as_str) == Some("lithe/log") { + logs.push(frame["params"].clone()); + } else if let Some(method) = frame.get("method").and_then(Value::as_str) { + let req_id = frame["id"].clone(); + let answer = on_host_request(method, &frame["params"]); + let done = stop(&frame); + self.respond(req_id, answer); + if done { + return (frame, logs); + } + } else if stop(&frame) { + return (frame, logs); + } + } + } + + fn run_until_answer( + &mut self, + id: i64, + on_host_request: impl FnMut(&str, &Value) -> Value, + ) -> (Value, Vec) { + self.run_until(|frame| frame["id"] == id, on_host_request) + } + /// Sends `initialize` as a host that offers plugin functions and /// `litheLogging` 0, and returns the answer. fn initialize(&mut self) -> Value { @@ -277,3 +330,194 @@ fn binary_content_callback_is_available_before_provider_registration() { "{initialized}" ); } + +#[test] +fn navigation_collect_and_invoke_round_trip_with_quiet_collect_logging() { + let mut host = Host::start(); + let initialized = host.initialize(); + let encoded = initialized.to_string(); + assert!(encoded.contains("java.navigation.collect"), "{encoded}"); + assert!(encoded.contains("java.navigation.invoke"), "{encoded}"); + + let context_ref = json!({ + "contextID": "ctx-nav", + "generation": 1 + }); + let full_context = json!({ + "contextID": "ctx-nav", + "generation": 1, + "folders": [{"rootID": "r1", "path": "/workspace/nav"}] + }); + host.notify("initialized", json!({})); + host.notify( + "lithe/host/languageServer/didChangeState", + json!({ + "context": context_ref, + "serverID": "java", + "generation": 1, + "state": "running" + }), + ); + + // Wait until navigation actions registration occurs (meaning didChangeState processed "running"). + host.run_until( + |frame| { + frame.get("method").and_then(Value::as_str) == Some("lithe/host/editor/registerActions") + && frame.pointer("/params/id").and_then(Value::as_str) == Some("java.navigation") + }, + |method, _params| match method { + "lithe/host/workspace/listContexts" => json!({"contexts": [full_context]}), + "lithe/host/workspace/getContext" => full_context.clone(), + "lithe/host/editor/registerActions" => json!({"subscriptionID": "sub-nav-1"}), + "lithe/host/documents/registerContentProvider" => { + json!({"subscriptionID": "sub-content-1"}) + } + _ => json!({}), + }, + ); + + let source = "interface Greeter { void greet(); }\nclass Impl implements Greeter {\n public void greet() {}\n}\n"; + let mut seen_methods = Vec::new(); + host.request( + 10, + "lithe/function/invoke", + json!({ + "functionID": "java.navigation.collect", + "operationID": "op-nav-collect", + "context": context_ref, + "params": { + "document": {"path": "src/App.java"}, + "text": source + } + }), + ); + let (collect_resp, collect_logs) = host.run_until_answer(10, |method, params| { + seen_methods.push(method.to_owned()); + match method { + "lithe/host/workspace/listContexts" => json!({"contexts": [full_context]}), + "lithe/host/workspace/getContext" => full_context.clone(), + "lithe/host/getCapabilities" => json!({ + "services": { + "editor": { + "options": { + "actionIcons": [ + "navigate-implemented", + "navigate-implementing", + "navigate-overridden", + "navigate-overriding" + ] + } + } + } + }), + "lithe/host/editor/registerActions" => json!({"subscriptionID": "sub-nav-1"}), + "lithe/host/languageServer/request" => { + match params.get("method").and_then(Value::as_str) { + Some("textDocument/definition") => json!({ + "value": [{ + "uri": "file:///workspace/nav/src/Greeter.java", + "range": {"start": {"line": 0, "character": 10}, "end": {"line": 0, "character": 17}} + }] + }), + Some("textDocument/implementation") => json!({ + "value": [{ + "uri": "file:///workspace/nav/src/Impl.java", + "range": {"start": {"line": 1, "character": 6}, "end": {"line": 1, "character": 10}} + }] + }), + Some("java/findLinks") => json!({ + "value": [{ + "displayName": "Greeter.greet()", + "location": { + "uri": "file:///workspace/nav/src/Greeter.java", + "range": {"start": {"line": 0, "character": 25}, "end": {"line": 0, "character": 30}} + } + }] + }), + _ => json!({"value": []}), + } + } + _ => json!({}), + } + }); + + let actions = collect_resp["result"]["actions"] + .as_array() + .unwrap_or_else(|| panic!("expected actions array, got {collect_resp}")); + assert!( + !actions.is_empty(), + "expected navigation actions: {collect_resp}" + ); + assert!( + actions.iter().any(|a| a["icon"] == "navigate-implemented"), + "expected navigate-implemented: {actions:?}" + ); + assert!( + actions.iter().any(|a| a["icon"] == "navigate-implementing"), + "expected navigate-implementing: {actions:?}" + ); + assert!( + !collect_logs + .iter() + .any(|log| log["kind"] == "operationFinished" + && log["operation"] == "java.navigation.collect"), + "high-frequency collect must suppress INFO operationFinished: {collect_logs:?}" + ); + + let first_action = actions + .iter() + .find(|a| a["icon"] == "navigate-implementing") + .expect("implementing action"); + host.request( + 11, + "lithe/function/invoke", + json!({ + "functionID": "java.navigation.invoke", + "operationID": "op-nav-invoke", + "context": context_ref, + "params": { + "data": first_action["invoke"]["params"] + } + }), + ); + let (invoke_resp, invoke_logs) = host.run_until_answer(11, |method, params| match method { + "lithe/host/languageServer/request" + if params.get("method").and_then(Value::as_str) == Some("textDocument/definition") => + { + json!({ + "value": [{ + "uri": "file:///workspace/nav/src/Greeter.java", + "range": {"start": {"line": 0, "character": 10}, "end": {"line": 0, "character": 17}} + }] + }) + } + "lithe/host/languageServer/request" => json!({ + "value": [{ + "displayName": "Greeter.greet()", + "location": { + "uri": "file:///workspace/nav/src/Greeter.java", + "range": {"start": {"line": 0, "character": 25}, "end": {"line": 0, "character": 30}} + } + }] + }), + _ => json!({}), + }); + + let locations = invoke_resp["result"]["reveal"]["locations"] + .as_array() + .expect("reveal locations"); + assert_eq!(locations.len(), 1, "{invoke_resp}"); + assert_eq!( + locations[0]["uri"], + "file:///workspace/nav/src/Greeter.java" + ); + assert!( + invoke_logs + .iter() + .any(|log| log["kind"] == "operationFinished" + && log["operation"] == "java.navigation.invoke"), + "user click invoke must record operationFinished INFO: {invoke_logs:?}" + ); + let _ = seen_methods; + assert_eq!(host.close(), 1); +} diff --git a/crates/java-domain/src/lsp/languages/java_navigation_syntax.rs b/crates/java-domain/src/lsp/languages/java_navigation_syntax.rs index bc0132f..4a942fc 100644 --- a/crates/java-domain/src/lsp/languages/java_navigation_syntax.rs +++ b/crates/java-domain/src/lsp/languages/java_navigation_syntax.rs @@ -2,6 +2,13 @@ use tree_sitter::{Node, Parser}; +/// Whether a syntax navigation candidate sits on a type or method declaration. +#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)] +pub enum JavaNavigationCandidateKind { + Type, + Method, +} + /// One declaration whose semantic parent or implementation relation must be verified by JDT LS. #[derive(Debug, Clone, Eq, PartialEq)] pub struct JavaNavigationCandidate { @@ -9,9 +16,13 @@ pub struct JavaNavigationCandidate { pub utf16_column: i64, pub direction: &'static str, pub relation: &'static str, + pub kind: JavaNavigationCandidateKind, + /// Zero-based `(line, utf16_column)` positions of supertype identifiers in + /// `extends` / `implements` clauses for `Type` + `"up"` candidates. + pub super_positions: Vec<(i64, i64)>, } -/// Extracts real Java method declarations without guessing across statement text. +/// Extracts real Java type and method declarations without guessing across statement text. /// /// Syntax only selects bounded candidates. A candidate never becomes a visible /// marker until JDT LS confirms at least one target, so incomplete or erroneous @@ -35,6 +46,7 @@ pub fn navigation_candidates(source: &str) -> Vec { .then_with(|| left.utf16_column.cmp(&right.utf16_column)) .then_with(|| left.direction.cmp(right.direction)) .then_with(|| left.relation.cmp(right.relation)) + .then_with(|| left.kind.cmp(&right.kind)) }); candidates.dedup(); candidates @@ -45,8 +57,17 @@ fn collect_candidates( source: &[u8], candidates: &mut Vec, ) { - if node.kind() == "method_declaration" { - collect_method_candidates(node, source, candidates); + match node.kind() { + "interface_declaration" + | "class_declaration" + | "enum_declaration" + | "record_declaration" => { + collect_type_candidates(node, source, candidates); + } + "method_declaration" => { + collect_method_candidates(node, source, candidates); + } + _ => {} } let mut cursor = node.walk(); for child in node.children(&mut cursor) { @@ -54,6 +75,170 @@ fn collect_candidates( } } +fn collect_type_candidates( + type_decl: Node<'_>, + source: &[u8], + candidates: &mut Vec, +) { + let Some(name) = type_decl.child_by_field_name("name") else { + return; + }; + let point = name.start_position(); + let line = i64::try_from(point.row).unwrap_or(i64::MAX); + let col = utf16_column(source, point.row, point.column); + + let modifiers = type_modifiers_text(type_decl, source); + let is_final = modifiers.split_whitespace().any(|value| value == "final"); + + match type_decl.kind() { + "interface_declaration" => { + candidates.push(JavaNavigationCandidate { + line, + utf16_column: col, + direction: "down", + relation: "interface", + kind: JavaNavigationCandidateKind::Type, + super_positions: Vec::new(), + }); + let supers = collect_super_positions(type_decl, "extends_interfaces", source); + if !supers.is_empty() { + candidates.push(JavaNavigationCandidate { + line, + utf16_column: col, + direction: "up", + relation: "interface", + kind: JavaNavigationCandidateKind::Type, + super_positions: supers, + }); + } + } + "class_declaration" => { + if !is_final { + candidates.push(JavaNavigationCandidate { + line, + utf16_column: col, + direction: "down", + relation: "inheritance", + kind: JavaNavigationCandidateKind::Type, + super_positions: Vec::new(), + }); + } + let superclass_positions = collect_super_positions(type_decl, "superclass", source); + if !superclass_positions.is_empty() { + candidates.push(JavaNavigationCandidate { + line, + utf16_column: col, + direction: "up", + relation: "inheritance", + kind: JavaNavigationCandidateKind::Type, + super_positions: superclass_positions, + }); + } + let interface_positions = collect_super_positions(type_decl, "interfaces", source); + if !interface_positions.is_empty() { + candidates.push(JavaNavigationCandidate { + line, + utf16_column: col, + direction: "up", + relation: "interface", + kind: JavaNavigationCandidateKind::Type, + super_positions: interface_positions, + }); + } + } + "enum_declaration" | "record_declaration" => { + let interface_positions = collect_super_positions(type_decl, "interfaces", source); + if !interface_positions.is_empty() { + candidates.push(JavaNavigationCandidate { + line, + utf16_column: col, + direction: "up", + relation: "interface", + kind: JavaNavigationCandidateKind::Type, + super_positions: interface_positions, + }); + } + } + _ => {} + } +} + +fn collect_super_positions( + type_decl: Node<'_>, + clause_kind: &str, + source: &[u8], +) -> Vec<(i64, i64)> { + let mut positions = Vec::new(); + let mut cursor = type_decl.walk(); + for child in type_decl.children(&mut cursor) { + if child.kind() == clause_kind + || child.kind() == "super_interfaces" && clause_kind == "interfaces" + { + extract_type_identifier_positions(child, source, &mut positions); + } + } + if positions.is_empty() { + if let Some(clause) = type_decl.child_by_field_name(clause_kind) { + extract_type_identifier_positions(clause, source, &mut positions); + } + } + positions +} + +fn extract_type_identifier_positions(clause: Node<'_>, source: &[u8], out: &mut Vec<(i64, i64)>) { + let mut stack = vec![clause]; + while let Some(node) = stack.pop() { + match node.kind() { + "type_identifier" => { + let point = node.start_position(); + out.push(( + i64::try_from(point.row).unwrap_or(i64::MAX), + utf16_column(source, point.row, point.column), + )); + } + "generic_type" => { + // Only inspect the base type before `type_arguments`, not generic args. + let mut cursor = node.walk(); + for child in node.children(&mut cursor) { + if child.kind() != "type_arguments" { + stack.push(child); + } + } + } + "scoped_type_identifier" => { + // In `pkg.Outer.Inner`, only resolve the rightmost type identifier. + let mut cursor = node.walk(); + if let Some(last_ident) = node + .children(&mut cursor) + .filter(|child| child.kind() == "type_identifier") + .last() + { + let point = last_ident.start_position(); + out.push(( + i64::try_from(point.row).unwrap_or(i64::MAX), + utf16_column(source, point.row, point.column), + )); + } + } + "type_arguments" => {} + _ => { + let mut cursor = node.walk(); + let mut children: Vec<_> = node.children(&mut cursor).collect(); + children.reverse(); + stack.extend(children); + } + } + } +} + +fn type_modifiers_text<'a>(type_decl: Node<'_>, source: &'a [u8]) -> &'a str { + type_decl + .children(&mut type_decl.walk()) + .find(|child| child.kind() == "modifiers") + .and_then(|value| value.utf8_text(source).ok()) + .unwrap_or_default() +} + fn collect_method_candidates( method: Node<'_>, source: &[u8], @@ -75,25 +260,47 @@ fn collect_method_candidates( "inheritance" }; let point = name.start_position(); - let position = JavaNavigationCandidate { + let base = JavaNavigationCandidate { line: i64::try_from(point.row).unwrap_or(i64::MAX), utf16_column: utf16_column(source, point.row, point.column), direction: "down", relation, + kind: JavaNavigationCandidateKind::Method, + super_positions: Vec::new(), }; if is_possible_override_target(modifier_text, enclosing_type, source) { - candidates.push(position.clone()); + candidates.push(base.clone()); } - if has_override_annotation(modifiers, source) { + let is_private_or_static = modifier_text + .split_whitespace() + .any(|modifier| matches!(modifier, "private" | "static")); + if !is_private_or_static + && (has_override_annotation(modifiers, source) + || enclosing_type.is_some_and(|ty| type_declares_supertypes(ty, source))) + { candidates.push(JavaNavigationCandidate { direction: "up", relation: super_relation(enclosing_type, source), - ..position + ..base }); } } +fn type_declares_supertypes(enclosing_type: Node<'_>, source: &[u8]) -> bool { + let header_end = enclosing_type + .child_by_field_name("body") + .map(|body| body.start_byte()) + .unwrap_or(enclosing_type.end_byte()); + let header = source + .get(enclosing_type.start_byte()..header_end) + .and_then(|value| std::str::from_utf8(value).ok()) + .unwrap_or_default(); + header + .split(|character: char| !character.is_ascii_alphanumeric() && character != '_') + .any(|word| matches!(word, "extends" | "implements")) +} + fn enclosing_type(mut node: Node<'_>) -> Option> { while let Some(parent) = node.parent() { if matches!( @@ -215,20 +422,96 @@ class Response { let candidates = navigation_candidates(source); + assert!(candidates.iter().any(|candidate| { + candidate.line == 1 + && candidate.kind == JavaNavigationCandidateKind::Type + && candidate.direction == "down" + && candidate.relation == "interface" + })); assert!(candidates.iter().any(|candidate| { candidate.line == 2 + && candidate.kind == JavaNavigationCandidateKind::Method && candidate.direction == "down" && candidate.relation == "interface" })); + // Line 8: class Response (`down`), Line 9: upload() (`down`); `new Response()` is ignored. assert_eq!( candidates .iter() - .filter(|candidate| candidate.line >= 9) + .filter(|candidate| candidate.line >= 8) .count(), - 1 + 2 ); } + #[test] + fn type_declarations_and_methods_without_override_annotation_produce_candidates() { + let source = r#" +interface Extended extends com.example.BaseInterface {} + +abstract class AbstractImpl extends BaseClass implements Greeter, Marker { + public String greet(String name) { + return name; + } + + private void helper() {} + static void util() {} +} +"#; + + let candidates = navigation_candidates(source); + + assert!(candidates.iter().any(|candidate| { + candidate.line == 1 + && candidate.kind == JavaNavigationCandidateKind::Type + && candidate.direction == "down" + && candidate.relation == "interface" + })); + let iface_up = candidates + .iter() + .find(|candidate| { + candidate.line == 1 + && candidate.kind == JavaNavigationCandidateKind::Type + && candidate.direction == "up" + }) + .expect("interface extends candidate"); + assert_eq!(iface_up.relation, "interface"); + // Should point at `BaseInterface`, skipping `com.example.` and ``. + assert_eq!(iface_up.super_positions, vec![(1, 39)]); + + let class_up_inheritance = candidates + .iter() + .find(|candidate| { + candidate.line == 3 + && candidate.kind == JavaNavigationCandidateKind::Type + && candidate.direction == "up" + && candidate.relation == "inheritance" + }) + .expect("class extends candidate"); + assert_eq!(class_up_inheritance.super_positions, vec![(3, 36)]); + + let class_up_interface = candidates + .iter() + .find(|candidate| { + candidate.line == 3 + && candidate.kind == JavaNavigationCandidateKind::Type + && candidate.direction == "up" + && candidate.relation == "interface" + }) + .expect("class implements candidate"); + assert_eq!(class_up_interface.super_positions, vec![(3, 66), (3, 75)]); + + assert!(candidates.iter().any(|candidate| { + candidate.line == 4 + && candidate.kind == JavaNavigationCandidateKind::Method + && candidate.direction == "up" + && candidate.relation == "interface" + })); + assert!(!candidates + .iter() + .any(|candidate| { matches!(candidate.line, 8 | 9) && candidate.direction == "up" })); + } + #[test] fn override_methods_get_up_and_possible_down_candidates() { let source = r#" diff --git a/crates/java-domain/src/lsp/languages/jdt_navigation.rs b/crates/java-domain/src/lsp/languages/jdt_navigation.rs index 186f1e8..a0b50cb 100644 --- a/crates/java-domain/src/lsp/languages/jdt_navigation.rs +++ b/crates/java-domain/src/lsp/languages/jdt_navigation.rs @@ -4,12 +4,164 @@ use super::java_navigation_syntax::navigation_candidates; use crate::protocol::JavaNavigationMarkerResponse; use serde_json::json; use serde_json::Value; -use std::collections::VecDeque; +use std::collections::{HashSet, VecDeque}; use std::time::Instant; /// Maximum semantic verification work accepted for one document version. pub const MAX_JAVA_NAVIGATION_TASKS: usize = 64; +/// Normalized 0-based LSP location returned by `textDocument/implementation`, +/// `textDocument/definition`, or `java/findLinks`. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct NormalizedNavigationLocation { + pub uri: String, + pub start_line: u32, + pub start_character: u32, + pub end_line: u32, + pub end_character: u32, + pub display_name: Option, +} + +impl NormalizedNavigationLocation { + /// Converts this normalized target to an LSP `Location` JSON object for + /// `editor/registerActions` `reveal.locations`. + pub fn to_lsp_location_value(&self) -> Value { + json!({ + "uri": self.uri, + "range": { + "start": { "line": self.start_line, "character": self.start_character }, + "end": { "line": self.end_line, "character": self.end_character }, + } + }) + } + + /// Short human-readable label (preferring JDT's `displayName`, otherwise the + /// URI's file stem — never exposing filesystem paths). + pub fn short_label(&self) -> Option { + if let Some(name) = self + .display_name + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + { + return Some(name.to_owned()); + } + let parsed = url::Url::parse(&self.uri).ok()?; + let segment = parsed + .path_segments() + .and_then(|mut segments| segments.next_back()) + .filter(|segment| !segment.is_empty())?; + let stem = segment + .strip_suffix(".java") + .or_else(|| segment.strip_suffix(".class")) + .unwrap_or(segment); + (!stem.is_empty()).then(|| stem.to_owned()) + } +} + +/// Normalizes JDT LS navigation responses across all three wire shapes: +/// 1. LSP `Location` (`{uri, range}`) +/// 2. LSP `LocationLink` (`{targetUri, targetSelectionRange | targetRange}`) +/// 3. JDT `java/findLinks` (`{location: {uri, range}, displayName?, kindName?}`) +/// +/// Supports `file:` and `jdt:` (and any valid non-empty URI with a scheme), +/// deduplicates by `(uri, start.line, start.character)`, and accepts either a +/// JSON array or a single JSON object. +pub fn extract_normalized_locations(value: &Value) -> Vec { + let items: Vec<&Value> = match value { + Value::Array(items) => items.iter().collect(), + Value::Object(_) => vec![value], + _ => return Vec::new(), + }; + let mut out = Vec::with_capacity(items.len()); + let mut seen = HashSet::new(); + for item in items { + if let Some(loc) = parse_navigation_location(item) { + let key = (loc.uri.clone(), loc.start_line, loc.start_character); + if seen.insert(key) { + out.push(loc); + } + } + } + out +} + +fn parse_navigation_location(item: &Value) -> Option { + let display_name = item + .get("displayName") + .and_then(Value::as_str) + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(str::to_owned); + + if let Some(inner) = item.get("location").filter(|value| value.is_object()) { + if let Some(mut loc) = parse_direct_location(inner) { + if loc.display_name.is_none() { + loc.display_name = display_name; + } + return Some(loc); + } + } + if let Some(mut loc) = parse_direct_location(item) { + if loc.display_name.is_none() { + loc.display_name = display_name; + } + return Some(loc); + } + let uri = item + .get("targetUri") + .and_then(Value::as_str) + .map(str::trim) + .filter(|uri| is_valid_navigation_uri(uri))?; + let range = item + .get("targetSelectionRange") + .filter(|value| value.is_object()) + .or_else(|| item.get("targetRange").filter(|value| value.is_object()))?; + let (start_line, start_character, end_line, end_character) = parse_lsp_range(range)?; + Some(NormalizedNavigationLocation { + uri: uri.to_owned(), + start_line, + start_character, + end_line, + end_character, + display_name, + }) +} + +fn parse_direct_location(item: &Value) -> Option { + let uri = item + .get("uri") + .and_then(Value::as_str) + .map(str::trim) + .filter(|uri| is_valid_navigation_uri(uri))?; + let range = item.get("range").filter(|value| value.is_object())?; + let (start_line, start_character, end_line, end_character) = parse_lsp_range(range)?; + Some(NormalizedNavigationLocation { + uri: uri.to_owned(), + start_line, + start_character, + end_line, + end_character, + display_name: None, + }) +} + +fn parse_lsp_range(range: &Value) -> Option<(u32, u32, u32, u32)> { + let start = range.get("start")?; + let end = range.get("end").unwrap_or(start); + let start_line = u32::try_from(start.get("line")?.as_u64()?).ok()?; + let start_character = u32::try_from(start.get("character")?.as_u64()?).ok()?; + let end_line = u32::try_from(end.get("line")?.as_u64()?).ok()?; + let end_character = u32::try_from(end.get("character")?.as_u64()?).ok()?; + Some((start_line, start_character, end_line, end_character)) +} + +fn is_valid_navigation_uri(uri: &str) -> bool { + !uri.is_empty() + && url::Url::parse(uri) + .is_ok_and(|parsed| !parsed.scheme().is_empty() && !parsed.path().is_empty()) +} + /// Bounded multi-request projection of JDT LS data into visible gutter markers. pub struct JavaNavigationMarkerBatch { tasks: VecDeque, @@ -27,6 +179,11 @@ pub enum JavaNavigationMarkerTask { ResolveCodeLens(Value), FindImplementations(super::java_navigation_syntax::JavaNavigationCandidate), FindSuperImplementation(super::java_navigation_syntax::JavaNavigationCandidate), + FindTypeSuperDefinition { + candidate: super::java_navigation_syntax::JavaNavigationCandidate, + super_line: i64, + super_utf16_column: i64, + }, } impl JavaNavigationMarkerBatch { @@ -43,13 +200,24 @@ impl JavaNavigationMarkerBatch { .collect::>(); // Parent checks run before child checks so an override arrow can appear // even when the fixed task budget is exhausted by a very large type. - tasks.extend( - candidates - .iter() - .filter(|candidate| candidate.direction == "up") - .cloned() - .map(JavaNavigationMarkerTask::FindSuperImplementation), - ); + for candidate in candidates + .iter() + .filter(|candidate| candidate.direction == "up") + { + if candidate.super_positions.is_empty() { + tasks.push_back(JavaNavigationMarkerTask::FindSuperImplementation( + candidate.clone(), + )); + } else { + for &(super_line, super_utf16_column) in &candidate.super_positions { + tasks.push_back(JavaNavigationMarkerTask::FindTypeSuperDefinition { + candidate: candidate.clone(), + super_line, + super_utf16_column, + }); + } + } + } tasks.extend( candidates .into_iter() @@ -88,7 +256,8 @@ impl JavaNavigationMarkerBatch { } } JavaNavigationMarkerTask::FindImplementations(candidate) - | JavaNavigationMarkerTask::FindSuperImplementation(candidate) => { + | JavaNavigationMarkerTask::FindSuperImplementation(candidate) + | JavaNavigationMarkerTask::FindTypeSuperDefinition { candidate, .. } => { let count = raw_location_count(result); if count > 0 { self.semantic_markers.push(JavaNavigationMarkerResponse { @@ -155,16 +324,26 @@ impl JavaNavigationMarkerTask { } }), ), + Self::FindTypeSuperDefinition { + super_line, + super_utf16_column, + .. + } => ( + "textDocument/definition", + json!({ + "textDocument": { "uri": uri }, + "position": { + "line": super_line, + "character": super_utf16_column + } + }), + ), } } } fn raw_location_count(result: Option<&Value>) -> usize { - match result { - Some(Value::Array(locations)) => locations.len(), - Some(Value::Object(_)) => 1, - _ => 0, - } + result.map_or(0, |value| extract_normalized_locations(value).len()) } /// Keeps only JDT LS implementation lenses; reference lenses never drive gutter icons. @@ -347,4 +526,76 @@ mod tests { assert!(!is_resolved_implementation_lens(&filtered[0])); assert!(is_resolved_implementation_lens(&filtered[1])); } + + #[test] + fn extract_normalized_locations_handles_all_three_jdt_shapes_and_jdt_uris() { + let payload = json!([ + { + "uri": "file:///workspace/src/ImplA.java", + "range": { "start": { "line": 4, "character": 6 }, "end": { "line": 4, "character": 11 } } + }, + { + "targetUri": "jdt://contents/rt.jar/java.lang/Runnable.class?foo=1", + "targetRange": { "start": { "line": 0, "character": 0 }, "end": { "line": 20, "character": 1 } }, + "targetSelectionRange": { "start": { "line": 2, "character": 17 }, "end": { "line": 2, "character": 25 } } + }, + { + "displayName": "Base.greet(String)", + "kindName": "superImplementation", + "location": { + "uri": "file:///workspace/src/ImplA.java", + "range": { "start": { "line": 4, "character": 6 }, "end": { "line": 4, "character": 11 } } + } + }, + { + "displayName": "Greeter.greet(String)", + "location": { + "uri": "file:///workspace/src/Greeter.java", + "range": { "start": { "line": 1, "character": 11 }, "end": { "line": 1, "character": 16 } } + } + }, + { + "uri": "relative/ignored.java", + "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 1 } } + } + ]); + + let normalized = extract_normalized_locations(&payload); + + assert_eq!(normalized.len(), 3); + assert_eq!(normalized[0].short_label().as_deref(), Some("ImplA")); + assert_eq!( + normalized[1].uri, + "jdt://contents/rt.jar/java.lang/Runnable.class?foo=1" + ); + assert_eq!(normalized[1].start_line, 2); + assert_eq!(normalized[1].short_label().as_deref(), Some("Runnable")); + assert_eq!( + normalized[2].short_label().as_deref(), + Some("Greeter.greet(String)") + ); + } + + #[test] + fn batch_plans_type_super_definitions_alongside_methods() { + let source = "class Sub extends Base implements Greeter {\n void run() {}\n}\n"; + let now = Instant::now(); + let mut batch = JavaNavigationMarkerBatch::new(&[], source, now, now); + + let first = batch.take_next().expect("super definition task"); + let (method, params) = first.request("file:///Sub.java"); + assert_eq!(method, "textDocument/definition"); + assert_eq!(params["position"]["line"], 0); + + batch.record_active_result(Some(&json!([ + { + "uri": "file:///Base.java", + "range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 10 } } + } + ]))); + + let second = batch.take_next().expect("interface super definition task"); + let (method2, _) = second.request("file:///Sub.java"); + assert_eq!(method2, "textDocument/definition"); + } } diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 8ac73b1..e94d482 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -82,3 +82,10 @@ | --- | --- | --- | --- | --- | | JSP/JSPF/Tag/Tagf 识别;在宿主 HTML 语法之上注入 JSP 指令、脚本片段、注释、EL 和标签库标签着色;注释与括号设置 | implemented / verified | implemented / verified | implemented / verified | `grammars/jsp.tmLanguage.json`;`scripts/grammar/host-jsp.mjs` 用宿主 TextMate 分词器(宿主 commit 见 `grammar-host.json`)逐项检查 24 处着色,2026-11-18 macOS arm64 本机与 CI Linux 通过。分词器与平台无关;原生编辑器窗口内的实际显示待实机验收 | | JSP/EL 语义补全、诊断、页面断点 | not-implemented | not-implemented | not-implemented | JDT LS 仅为 Java 服务,未来需 JSP 专属语言服务 | + +## 双向继承/实现跳转与左侧行首导航图标 + +| 能力 | macOS | Windows | Linux | 证据 | +| --- | --- | --- | --- | --- | +| 声明 `textDocument/codeLens`、`codeLens/resolve`、`textDocument/implementation`、`textDocument/definition`、`java/findLinks` 会话请求方法 | implemented / pending | implemented / pending | implemented / pending | `io.github.lithe-idea.java-support/plugin.json`、`backend/tests/repository_pins.rs` | +| 后端 `java.navigation.collect` / `java.navigation.invoke` 与三态 JDT 返回规范化:按宿主 `actionIcons` 协商渲染 `navigate-implemented`/`navigate-implementing`(绿 I)与 `navigate-overridden`/`navigate-overriding`(蓝 O),点击返回 `reveal.locations` | implemented / pending | implemented / pending | implemented / pending | `crates/java-domain/src/lsp/languages/java_navigation_syntax.rs`、`jdt_navigation.rs`、`backend/src/navigation.rs`、`backend/tests/session.rs`(`cargo clippy --workspace --all-targets` 与 `cargo test --workspace` 通过;真实 JDT LS 与原生桌面端联调待补) | diff --git a/docs/releases/v4.3.0.md b/docs/releases/v4.3.0.md new file mode 100644 index 0000000..bd9186f --- /dev/null +++ b/docs/releases/v4.3.0.md @@ -0,0 +1,21 @@ +# Java Support 4.3.0 + +## 中文 + +- 接口、抽象类、重写方法与实现类/子类之间新增双向跳转,支持 `Go to Implementation` 与 `Go to Super Declaration`(含未显式标注 `@Override` 的继承方法与泛型父类/接口声明)。 +- 编辑器左侧行号栏新增 IntelliJ IDEA 风格语义导航图标(绿色 `I↓` / `I↑` 表示接口实现关系,蓝色 `O↓` / `O↑` 表示继承与重写关系),支持悬停查看目标并点击跳转;在不支持细分图标的旧版宿主上自动回退为通用导航图标。 + +### 兼容性 + +请使用支持 `toolDefinitions: 1`、`sourceSettings: 1`、`managedRuntimes: 1` 和 `ui: 0` 的 Lithe 桌面端;细分绿色 `I` / 蓝色 `O` 左侧行号栏图标与双向实现跳转需要 Lithe 桌面端 0.8.17 及以上版本。较早的宿主会自动回退显示通用导航图标,或继续使用兼容的插件版本。 + +--- + +## English + +- Add bidirectional navigation between interfaces, superclasses, overridden methods, and their implementations/subclasses, supporting `Go to Implementation` and `Go to Super Declaration` (including generic supertypes and methods without `@Override`). +- Show IDEA-style gutter navigation icons (`I↓` / `I↑` in green for interface implementations, `O↓` / `O↑` in blue for inheritance overrides) with hover tooltips and one-click/multi-target navigation, falling back to generic navigation icons on older Lithe hosts. + +### Compatibility + +Use a Lithe desktop host that supports `toolDefinitions: 1`, `sourceSettings: 1`, `managedRuntimes: 1`, and `ui: 0`. Distinct green `I` / blue `O` gutter icons and bidirectional implementation navigation require Lithe Desktop 0.8.17 or later; earlier hosts automatically fall back to generic navigation icons or can keep compatible plugin versions. diff --git a/io.github.lithe-idea.java-support/plugin.json b/io.github.lithe-idea.java-support/plugin.json index 421c1aa..5dc513c 100644 --- a/io.github.lithe-idea.java-support/plugin.json +++ b/io.github.lithe-idea.java-support/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.java-support", "displayName": "Java Support", - "version": "4.2.2", + "version": "4.3.0", "pluginAPIVersion": 0, "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 1, "sourceSettings": 1, "managedRuntimes": 1, "ui": 0}, "managedRuntimes": { @@ -806,7 +806,16 @@ "function": "java.resolveLaunch", "timeoutMilliseconds": 60000 }, - "requestMethods": ["java/classFileContents", "java/projectConfigurationsUpdate", "workspace/executeCommand"], + "requestMethods": [ + "java/classFileContents", + "java/projectConfigurationsUpdate", + "workspace/executeCommand", + "textDocument/codeLens", + "codeLens/resolve", + "textDocument/implementation", + "textDocument/definition", + "java/findLinks" + ], "commands": ["java.project.getAll", "java.project.getSettings", "java.project.getClasspaths", "lithe.java.projectModel.describe", "java.project.updateSettings", "vscode.java.buildWorkspace", "vscode.java.resolveClasspath", "vscode.java.resolveMainMethod", "vscode.java.test.findTestTypesAndMethods", "vscode.java.test.junit.argument"], "forwardNotifications": ["language/eventNotification", "language/progressReport", "language/status"], "state": {