From a09c9aa9ad22e3652d063ddd9dd0aa7d916ebd3e Mon Sep 17 00:00:00 2001 From: Waiting-Night <53596273+wangyuewen-china@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:06:54 +0800 Subject: [PATCH] fix(java): navigate inherited method references to their declarations (#6953) JDT's selection-based definition can answer the functional interface method (Function.apply) for a method reference whose method is inherited. Go to Definition on a Java method reference now asks the app-owned JDT command openidea.java.methodReferenceDefinition (java-usages 1.20.1) for the AST method binding; Lombok accessors without a source range fall back to their field or declaring type. The bundled jar is reproducible from source (SHA-256 a111a935...); tests/method-reference.py checks the command against a real JDT LS. Co-authored-by: wangyuewen-china <53596273+wangyuewen-china@users.noreply.github.com> --- crates/ide-lsp/src/jdtls.rs | 17 +- crates/ide-lsp/src/lib.rs | 75 +++++++- crates/ide-sdk/src/java.rs | 2 +- java/java-usages/MANIFEST.MF | 2 +- java/java-usages/README.md | 11 +- java/java-usages/openidea-java-usages.jar | Bin 193709 -> 200675 bytes java/java-usages/plugin.xml | 3 + .../MethodReferenceDefinitionCommand.java | 131 ++++++++++++++ java/java-usages/tests/method-reference.py | 167 ++++++++++++++++++ 9 files changed, 403 insertions(+), 5 deletions(-) create mode 100644 java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java create mode 100644 java/java-usages/tests/method-reference.py diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index ef6160a28..b4f67ca42 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -9,7 +9,8 @@ use crate::LspManager; use crate::server::{Running, Server}; use ide_core::error::{ErrorData, ErrorKind}; use ide_core::event::LspRefreshKind; -use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId}; +use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos}; +use lsp_types as lsp; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use specta::Type; @@ -20,6 +21,7 @@ use std::time::{Duration, Instant}; pub(crate) const SERVER: &str = "jdtls"; const GENERATED_SOURCES: &str = "openidea.java.generatedSources"; +const METHOD_REFERENCE_DEFINITION: &str = "openidea.java.methodReferenceDefinition"; pub(crate) mod configuration; pub(crate) mod exception_breakpoints; @@ -771,6 +773,19 @@ impl LspManager { } } + /// The declaration of a Java method named by `Type::method` / `expr::method` at `pos`. + /// JDT's selection-based definition can return the functional interface method when the + /// referenced method is inherited; the extension resolves the AST binding instead. + pub(crate) async fn java_method_reference_definition(&self, path: &Path, pos: Pos) -> IdeResult> { + let uri = crate::path_to_uri_string(path); + let value = self + .jdtls_command(path, METHOD_REFERENCE_DEFINITION, vec![json!(uri), json!(pos.line), json!(pos.col)]) + .await?; + let locations: Vec = serde_json::from_value(value).unwrap_or_default(); + let conv = self.conv(crate::text::Encoding::Utf16); + Ok(locations.iter().filter_map(|location| conv.location(location)).collect()) + } + /// The jdtls instance serving `path` (a module directory or source file), /// started if needed and waited for. async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc, Running)> { diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 46faba21d..febff3f13 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -327,6 +327,25 @@ fn goto_is_empty(r: &Option) -> bool { } } +/// Whether the caret is on the method name of a Java method reference (`Type::method`). +/// A method reference can name a functional interface's method through JDT's selection-based +/// definition when the referenced method is inherited, so ask the AST binding command instead. +fn java_method_reference_at(text: &DocText, pos: Pos) -> bool { + let line = text.line(pos.line as usize); + let mut utf16 = 0u32; + let mut at = line.len(); + for (i, c) in line.char_indices() { + if utf16 >= pos.col { + at = i; + break; + } + utf16 += c.len_utf16() as u32; + } + let before = line[..at].trim_end(); + let Some(colon) = before.rfind("::") else { return false }; + before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$') +} + fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError { match e { RpcError::Cancelled => IdeError::cancelled(), @@ -1793,7 +1812,31 @@ impl LspManager { } let (method, cap, feature) = goto_method(kind); let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?; - self.goto_in(&snap, &targets, method, pos, None, None).await + let result = self.goto_in(&snap, &targets, method, pos, None, None).await; + // JDT's selection-based definition can name the functional interface method for an + // inherited method reference. Ask the Java binding command when that is what came back, + // when the caret is on a method reference, or when the server found no target at all. + let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos); + if kind == GotoKind::Definition + && snap.language.as_str() == "java" + && (method_reference + || result.as_ref().is_ok_and(|locs| { + locs.is_empty() + || locs.iter().any(|l| { + let path = l.path.to_string_lossy().replace('\\', "/"); + let uri = l.uri.as_deref().unwrap_or_default(); + path.contains("java/util/function") + || path.contains("java.util.function") + || uri.contains("java/util/function") + || uri.contains("java.util.function") + }) + })) + && let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await + && !found.is_empty() + { + return Ok(found); + } + result } /// Go to Implementation, with the implementations found first passed to `partial` while @@ -4677,6 +4720,36 @@ mod code_action_tests { } } +#[cfg(test)] +mod java_method_reference_tests { + use super::java_method_reference_at; + use crate::text::DocText; + use ide_core::Pos; + + #[test] + fn finds_the_method_name_of_a_method_reference() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);"); + let col = "wrapper.set(XbkBtbOutNotice::get".len() as u32; + assert!(java_method_reference_at(&text, Pos::new(0, col))); + } + + #[test] + fn allows_whitespace_around_the_method_reference_operator() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice :: getUpdateTime, now);"); + let col = "wrapper.set(XbkBtbOutNotice :: get".len() as u32; + assert!(java_method_reference_at(&text, Pos::new(0, col))); + } + + #[test] + fn ignores_regular_calls_and_the_referenced_type() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);"); + let type_col = "wrapper.set(XbkBtbOutNotice".len() as u32; + assert!(!java_method_reference_at(&text, Pos::new(0, type_col))); + let call = DocText::new("wrapper.set(getUpdateTime(), now);"); + assert!(!java_method_reference_at(&call, Pos::new(0, "wrapper.set(get".len() as u32))); + } +} + #[cfg(test)] mod did_change_content_tests { use super::*; diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 4bbf32e26..ca3a00a6f 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.19.0", + "1.20.1", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/java/java-usages/MANIFEST.MF b/java/java-usages/MANIFEST.MF index b0de4c680..e3ffb7c09 100644 --- a/java/java-usages/MANIFEST.MF +++ b/java/java-usages/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA Java usages Bundle-SymbolicName: ai.openidea.usages;singleton:=true -Bundle-Version: 1.19.0 +Bundle-Version: 1.20.1 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core, org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime, diff --git a/java/java-usages/README.md b/java/java-usages/README.md index ac1f868a5..acc7e6c35 100644 --- a/java/java-usages/README.md +++ b/java/java-usages/README.md @@ -6,6 +6,10 @@ The app-owned OSGi command `openidea.java.usages` returns `{location, kind, acce `kind` retains field/getter/setter/unknown identity for compatibility. Optional `access` is read/write/readWrite/unknown. Missing access metadata is unknown; old servers and ordinary LSP locations remain visible under either filter. +`openidea.java.methodReferenceDefinition(uri, line, column)` resolves the method name +of a `Type::method` or `expr::method` reference through its AST binding and returns the +declaring method's location. This keeps inherited methods on their parent declaration +where JDT's selection-based definition may return the functional interface method. An absent or failing extension command uses standard LSP references, without access classification or toolbar controls. This includes errors during scope widening. The Rust bridge logs the failure once per project session. Cancelled requests and @@ -88,7 +92,7 @@ is not a claim of full IntelliJ feature parity. ## Rebuild and delivery The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as -`java-usages-1.18.0.jar`, and added alongside existing initialization bundles. +`java-usages-1.20.1.jar`, and added alongside existing initialization bundles. Users need no compiler, Maven or Python. Manifest/install version must change when replacing the bundle because OSGi caches bundles. @@ -142,6 +146,10 @@ protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception breakpoint intention; its reproducible SHA-256 is `d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`. +Version 1.20.1 adds `openidea.java.methodReferenceDefinition`, which resolves inherited Java method +references from their AST binding instead of JDT's selection result. Lombok-generated accessors +without a source range fall back to their field or declaring type; its reproducible SHA-256 is +`a111a9359b8f13dcd06e14e72fa287943cfe953325bff6f940912cae199caec7`. ```sh export PATH=/path/to/jdk25/bin:$PATH @@ -173,6 +181,7 @@ OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /pat python3 java/java-usages/tests/hierarchy.py /path/to/jdtls python3 java/java-usages/tests/implementations.py /path/to/jdtls python3 java/java-usages/tests/exception-type.py /path/to/jdtls +python3 java/java-usages/tests/method-reference.py /path/to/jdtls ``` The harnesses select the JDT LS configuration for the current platform. The first diff --git a/java/java-usages/openidea-java-usages.jar b/java/java-usages/openidea-java-usages.jar index c17b6e429788fef80bd56041d22067e88f7a6e20..bdafdf6678845e7c514d9f668e6da1ec79b5d5be 100644 GIT binary patch delta 3599 zcmb7Hdt6k<75?V#<1V{*VF5udAVNWbUEUB;%tMPW6cD3Cu@YTz!6nOrESiw2t7#rh z6WZ7@-avgMtu0Mc6Y}DbSfh#6wn^HUwrR8>k(wr&*eJ%7B*l<3yAVxk|LFbgojd2u zIcLs$X7`=3oZ6$rRV>iy$07J6t@z~pQ*ZBMfOyAg>rPAKx8?2B=jCMOZhigP*ICj_ z*S>gmT}6)yi1#{TbGow|n_OP^8kaNM>)hb3b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%?DH?Q;#H4u#t&n`Yn)f zL>okS!2%}f>DSqSzO7ioB)|g=N`?l;h%TstB}{zN-*Ykx$RL7_fq@IA5J)#LHa(br Vke^wEPl-W^ArNSW+Y2V3H~=ozaX0_~ diff --git a/java/java-usages/plugin.xml b/java/java-usages/plugin.xml index 98cab62c7..79aa04153 100644 --- a/java/java-usages/plugin.xml +++ b/java/java-usages/plugin.xml @@ -27,6 +27,9 @@ + + + diff --git a/java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java b/java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java new file mode 100644 index 000000000..d8d2d0f1d --- /dev/null +++ b/java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java @@ -0,0 +1,131 @@ +package ai.openidea.navigation; + +import ai.openidea.Documents; +import java.util.List; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.ITypeRoot; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ExpressionMethodReference; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.MethodReference; +import org.eclipse.jdt.core.dom.NodeFinder; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.SuperMethodReference; +import org.eclipse.jdt.core.dom.TypeMethodReference; +import org.eclipse.jdt.core.manipulation.CoreASTProvider; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; +import org.eclipse.jdt.ls.core.internal.JDTUtils; +import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers; +import org.eclipse.lsp4j.Location; + +/** + * Resolves a method reference (for example {@code Child::getGoodsSpace}) to the declaration + * of the referenced method. JDT's selection-based definition request can return the + * functional interface method ({@code Function.apply}) when the method is inherited; + * bindings retain the actual method identity instead. + */ +public final class MethodReferenceDefinitionCommand implements IDelegateCommandHandler { + @Override + public Object executeCommand(String command, List arguments, IProgressMonitor monitor) throws Exception { + Documents.awaitChanges(monitor); + String uri = (String) arguments.get(0); + int line = ((Number) arguments.get(1)).intValue(); + int column = ((Number) arguments.get(2)).intValue(); + ITypeRoot root = JDTUtils.resolveTypeRoot(uri); + if (root == null || !root.exists()) return List.of(); + CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor); + if (ast == null) return List.of(); + int offset = JsonRpcHelpers.toOffset(root, line, column); + if (offset < 0) return List.of(); + + MethodReference reference = enclosingReference(ast, offset); + if (reference == null) return List.of(); + SimpleName name = methodName(reference); + if (name == null) return List.of(); + int start = name.getStartPosition(); + if (offset < start || offset > start + name.getLength()) return List.of(); + + IMethodBinding binding = reference.resolveMethodBinding(); + if (binding == null) return List.of(); + IMethodBinding declaration = binding.getMethodDeclaration(); + if (declaration == null) return List.of(); + Location location = locationOf(declaration); + return location == null ? List.of() : List.of(location); + } + + /** + * The declaration's source location. Lombok-generated accessors have a binding and a Java + * element but no source range; then the field the accessor reads (or the declaring type) + * is the closest source declaration. Without this fallback the standard definition request + * stays at the functional interface method. + */ + private static Location locationOf(IMethodBinding declaration) throws Exception { + var element = declaration.getJavaElement(); + Location location = element == null ? null : JDTUtils.toLocation(element); + if (location != null) return location; + if (element instanceof IMember member && member.getClassFile() != null) + return JDTUtils.toLocation(member.getClassFile()); + + ITypeBinding owner = declaration.getDeclaringClass(); + if (owner == null) return null; + var ownerElement = owner.getJavaElement(); + if (!(ownerElement instanceof IType type) || !type.exists()) return null; + + for (IMethod method : type.getMethods()) { + if (!method.getElementName().equals(declaration.getName())) continue; + if (method.getNumberOfParameters() != declaration.getParameterTypes().length) continue; + location = JDTUtils.toLocation(method); + if (location != null) return location; + } + + String fieldName = propertyName(declaration.getName()); + if (fieldName != null) { + IField field = type.getField(fieldName); + if (field.exists()) { + location = JDTUtils.toLocation(field); + if (location != null) return location; + } + } + return JDTUtils.toLocation(type); + } + + /** The field name of a bean accessor (`getUpdateTime` / `setUpdateTime` / `isEnabled`). */ + private static String propertyName(String methodName) { + String rest; + if (methodName.startsWith("get") || methodName.startsWith("set")) { + rest = methodName.substring(3); + } else if (methodName.startsWith("is")) { + rest = methodName.substring(2); + } else { + return null; + } + if (rest.isEmpty()) return null; + if (rest.length() > 1 && Character.isUpperCase(rest.charAt(0)) && Character.isUpperCase(rest.charAt(1))) { + return rest; + } + return Character.toLowerCase(rest.charAt(0)) + rest.substring(1); + } + + private static MethodReference enclosingReference(CompilationUnit ast, int offset) { + ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode(); + for (ASTNode node = leaf; node != null; node = node.getParent()) { + if (node instanceof MethodReference reference) return reference; + } + return null; + } + + private static SimpleName methodName(MethodReference reference) { + return switch (reference) { + case TypeMethodReference type -> type.getName(); + case ExpressionMethodReference expression -> expression.getName(); + case SuperMethodReference superReference -> superReference.getName(); + default -> null; + }; + } +} diff --git a/java/java-usages/tests/method-reference.py b/java/java-usages/tests/method-reference.py new file mode 100644 index 000000000..a518a7964 --- /dev/null +++ b/java/java-usages/tests/method-reference.py @@ -0,0 +1,167 @@ +"""Go to Definition on a method reference, against a real JDT LS. Arguments: jdtls home, optional bundle jar. + +Each case puts the caret on a method reference's name and checks that +`openidea.java.methodReferenceDefinition` answers the referenced method's declaration (an inherited +method on its parent, not the functional interface method), and nothing elsewhere. +""" +import json +import pathlib +import platform +import queue +import subprocess +import sys +import tempfile +import threading +import time + +home = pathlib.Path(sys.argv[1]).resolve() +bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar' +work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-method-reference-')) +config = work / 'config' +config.mkdir() +system, machine = platform.system(), platform.machine().lower() +config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux') +config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name] +config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file()) +(config / 'config.ini').write_bytes(config_source.read_bytes()) +project = work / 'project' +(project / 'src/app').mkdir(parents=True) +(project / '.project').write_text('apporg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature') +(project / '.classpath').write_text('') +sources = { + 'Parent.java': '''package app; + +public class Parent { + public String getGoodsSpace() { + return "space"; + } + + public static String describe(Object o) { + return String.valueOf(o); + } +} +''', + 'Child.java': '''package app; + +public class Child extends Parent { + public int own() { + return 1; + } +} +''', + 'Main.java': '''package app; + +import java.util.List; +import java.util.function.Function; + +public class Main { + void run(List children) { + Function inherited = Child::getGoodsSpace; + Function own = Child::own; + Function statics = Child::describe; + children.forEach(System.out::println); + String plain = new Child().getGoodsSpace(); + } +} +''', +} +for name, text in sources.items(): + (project / 'src/app' / name).write_text(text) +uri = lambda name: (project / 'src/app' / name).as_uri() + +log = (work / 'stderr.log').open('w') +proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log) +messages = queue.Queue() +lock = threading.Lock() + + +def send(message): + data = json.dumps(message).encode() + with lock: + proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data) + proc.stdin.flush() + + +def read(): + while True: + headers = {} + while True: + line = proc.stdout.readline() + if not line: + return + if line == b'\r\n': + break + k, v = line.decode().split(':', 1) + headers[k.lower()] = v.strip() + message = json.loads(proc.stdout.read(int(headers['content-length']))) + if 'method' in message and 'id' in message: + send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None}) + else: + messages.put(message) + + +threading.Thread(target=read, daemon=True).start() +seq = 0 + + +def request(method, params): + global seq + seq += 1 + send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params}) + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + msg = messages.get(timeout=max(1, deadline - time.monotonic())) + if msg.get('id') == seq: + if 'error' in msg: + raise RuntimeError(msg['error']) + return msg.get('result') + raise TimeoutError(method) + + + + +def where(loc): + return (loc['uri'].rsplit('/', 1)[-1], loc['range']['start']['line']) + + +def line_of(file, needle): + return next(i for i, t in enumerate(sources[file].splitlines()) if needle in t) + + +CASES = [ + ('Child::getGoodsSpace', 'getGoodsSpace', 3, [('Parent.java', line_of('Parent.java', 'getGoodsSpace'))]), + ('Child::own', 'own', 1, [('Child.java', line_of('Child.java', 'own()'))]), + ('Child::describe', 'describe', 2, [('Parent.java', line_of('Parent.java', 'describe'))]), + ('Child::getGoodsSpace', 'Child', 2, []), + ('new Child().getGoodsSpace', 'getGoodsSpace', 2, []), +] + +try: + init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}}) + commands = init['capabilities']['executeCommandProvider']['commands'] + assert 'openidea.java.methodReferenceDefinition' in commands, commands + send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}}) + for name, text in sources.items(): + send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}}) + request('java/buildWorkspace', True) + failed = [] + lines = sources['Main.java'].splitlines() + for line_needle, needle, at, expected in CASES: + line = next(i for i, t in enumerate(lines) if line_needle in t) + column = lines[line].index(needle, lines[line].index(line_needle)) + at + got = request('workspace/executeCommand', {'command': 'openidea.java.methodReferenceDefinition', 'arguments': [uri('Main.java'), line, column]}) + got = [where(l) for l in got or []] + ok = got == expected + if not ok: + failed.append((line_needle, needle)) + print('OK' if ok else 'FAIL', repr(line_needle), 'at', repr(needle), got) + # The functional interface's method is what the standard request answers for the inherited case. + line = next(i for i, t in enumerate(lines) if 'Child::getGoodsSpace' in t) + std = request('textDocument/definition', {'textDocument': {'uri': uri('Main.java')}, 'position': {'line': line, 'character': lines[line].index('getGoodsSpace') + 3}}) + print('standard definition:', std) + assert not failed, failed + print('method-reference: all cases passed') +finally: + proc.terminate() + proc.wait(timeout=20) + print('Evidence:', work, file=sys.stderr)