дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 22:32:35 +02:00
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 <[email protected]>
168 рядки
7.1 KiB
Python
168 рядки
7.1 KiB
Python
"""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('<projectDescription><name>app</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
|
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
|
|
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<Child> children) {
|
|
Function<Child, String> inherited = Child::getGoodsSpace;
|
|
Function<Child, Integer> own = Child::own;
|
|
Function<Object, String> 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)
|