feat(debugger): toggle an exception breakpoint from a throw or catch (#5206)

Alt+Enter on a throw statement or a catch parameter offers to create, enable or disable a Java exception breakpoint for that exception type. The type is resolved by the new openidea.java.exceptionType command in the java-usages bundle (1.17.0), and intention providers can now be asynchronous.

Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com>
This commit is contained in:
ntbang0901
2026-11-22 20:43:54 +08:00
committed by GitHub
parent ddf9cc3d70
commit 407f1c5235
22 changed files with 779 additions and 8 deletions
+1 -1
View File
@@ -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.16.0
Bundle-Version: 1.17.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+20 -1
View File
@@ -88,7 +88,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.16.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.17.0.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.
@@ -139,6 +139,9 @@ reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce2
Version 1.16.0 adds `openidea.java.generatedSources`, which puts Maven plugin output such as
protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
`a5feda1cae11bdea1044fb311404840b048601af037f65685973721f1eefff8b`.
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`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
@@ -169,6 +172,7 @@ python3 java/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar
OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar > /tmp/read-write-indexed.json
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
```
The harnesses select the JDT LS configuration for the current platform. The first
@@ -185,6 +189,21 @@ listing, moving, declaring abstract, pulling up to an interface, conflicts repor
before any change, and a class without supertypes. Each edit is applied to a copy of
the fixture and compiled with javac.
`exception-type.py` puts the caret on throws, catches (multi-catch too), qualified names, a
thrown variable or call, a nested, local, unresolved or non-Throwable class, an import and a
class declaration, and compares each answer with IntelliJ's.
## Exception class at a caret
`openidea.java.exceptionType(uri, line, column)` answers `{qualifiedName, displayName}` (the
binary name, `app.Outer$Failure`, and the simple name) or `null`, as IntelliJ's
`ControlExceptionBreakpointJVMSupport` decides: from the token right of the caret, else the one
left of it, the nearest enclosing reference, class or throw statement. A reference gives the class
it resolves to (a constructor's class; a variable, a method or a package gives nothing, and so does
a call with a qualifier, which UAST sees as a reference to its method), a class gives itself only on
its name, a throw statement the class of what it throws. The class must be a `Throwable` with a
qualified name: not unresolved, local, anonymous or a type variable.
## Class-hierarchy refactorings
`openidea.java.hierarchy.members(uri, line, column, kind)` describes the class at the
Binary file not shown.
+3
View File
@@ -30,5 +30,8 @@
<command id="openidea.java.hierarchy.members"/>
<command id="openidea.java.hierarchy.refactor"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.breakpoints.ExceptionTypeCommand">
<command id="openidea.java.exceptionType"/>
</delegateCommandHandler>
</extension>
</plugin>
@@ -0,0 +1,113 @@
package ai.openidea.breakpoints;
import ai.openidea.Documents;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.dom.*;
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;
/**
* The exception class a caret names, for the Create / Enable / Disable exception breakpoint intention.
*
* <p>{@code openidea.java.exceptionType(uri, line, column)} answers {@code {qualifiedName, displayName}}
* ({@code qualifiedName} is the binary name, {@code app.Outer$Failure}) or {@code null}. It follows
* IntelliJ's {@code ControlExceptionBreakpointJVMSupport}: from the token right of the caret, else the
* one left of it, the nearest enclosing reference, class or throw statement decides. A reference gives
* the class it resolves to (a constructor's class; a variable, a method or a package gives nothing), a
* class gives itself only on its name, and a throw statement the class of the thrown expression. The
* class must be a {@link Throwable} with a qualified name: not unresolved, local, anonymous or a type
* variable.
*/
public final class ExceptionTypeCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> 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 null;
CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor);
if (ast == null) return null;
int offset = JsonRpcHelpers.toOffset(root, line, column);
if (offset < 0) return null;
ITypeBinding found = classAt(ast, offset);
if (found == null && offset > 0) found = classAt(ast, offset - 1);
return found == null ? null : describe(found);
}
/** The exception class for the token holding the character at {@code offset}. */
static ITypeBinding classAt(CompilationUnit ast, int offset) {
if (offset >= ast.getStartPosition() + ast.getLength()) return null;
ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode();
ITypeBinding type = classReference(leaf);
return isException(type) ? type : null;
}
private static ITypeBinding classReference(ASTNode leaf) {
for (ASTNode n = leaf; n != null; n = n.getParent()) {
if (n instanceof AbstractTypeDeclaration declaration) {
return leaf == declaration.getName() ? declaration.resolveBinding() : null;
}
if (n instanceof AnonymousClassDeclaration) return null;
if (n instanceof ThrowStatement thrown) return thrown.getExpression().resolveTypeBinding();
if (isReference(n)) return referencedClass(n);
}
return null;
}
/**
* What UAST converts to a reference expression: a name that is not a declaration or a label, a
* field access, a call or instance creation with a qualifier, a method or constructor reference.
*/
private static boolean isReference(ASTNode n) {
if (n instanceof SimpleName name) {
if (name.isDeclaration()) return false;
StructuralPropertyDescriptor at = name.getLocationInParent();
return at != LabeledStatement.LABEL_PROPERTY && at != BreakStatement.LABEL_PROPERTY
&& at != ContinueStatement.LABEL_PROPERTY && at != MemberValuePair.NAME_PROPERTY;
}
return n instanceof QualifiedName || n instanceof FieldAccess || n instanceof SuperFieldAccess
|| n instanceof SuperMethodInvocation || n instanceof MethodReference || n instanceof MemberRef
|| n instanceof MethodRef || (n instanceof MethodInvocation call && call.getExpression() != null)
|| (n instanceof ClassInstanceCreation creation && creation.getExpression() != null);
}
private static ITypeBinding referencedClass(ASTNode reference) {
IBinding binding = switch (reference) {
case Name name -> name.resolveBinding();
case ClassInstanceCreation creation -> creation.resolveConstructorBinding();
case MethodReference method -> method.resolveMethodBinding();
case MethodInvocation call -> call.resolveMethodBinding();
case SuperMethodInvocation call -> call.resolveMethodBinding();
default -> null;
};
if (binding instanceof ITypeBinding type) return type;
if (binding instanceof IMethodBinding method && method.isConstructor()) return method.getDeclaringClass();
return null;
}
private static boolean isException(ITypeBinding type) {
if (type == null || type.isRecovered() || !type.isClass() || type.isLocal() || type.isAnonymous()) return false;
for (ITypeBinding t = type.getErasure(); t != null; t = t.getSuperclass()) {
if ("java.lang.Throwable".equals(t.getQualifiedName())) return true;
}
return false;
}
private static Map<String, String> describe(ITypeBinding type) {
ITypeBinding erased = type.getErasure();
String binary = erased.getBinaryName();
if (binary == null) return null;
Map<String, String> out = new LinkedHashMap<>();
out.put("qualifiedName", binary);
out.put("displayName", erased.getName());
return out;
}
}
+242
View File
@@ -0,0 +1,242 @@
"""The exception class at a caret, against a real JDT LS. Arguments: jdtls home, optional bundle jar.
Each case puts the caret at an offset inside a unique piece of text and compares the answer of
`openidea.java.exceptionType` with IntelliJ's ControlExceptionBreakpointJVMSupport: the class a
reference resolves to (a constructor's class), a class declaration's name, or the type a throw
statement throws, when that class is a Throwable with a qualified name.
"""
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-exception-type-'))
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/errors').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 = {
'errors/OrderException.java': '''package app.errors;
public class OrderException extends Exception {
public OrderException(String message) {
super(message);
}
}
''',
'Main.java': '''package app;
import app.errors.OrderException;
import java.io.IOException;
public class Main {
static class Failure extends RuntimeException {
}
static class NotAnException {
}
void place(Exception given, String msg) throws Exception {
try {
throw new OrderException("order " + msg);
} catch (OrderException | IllegalArgumentException e) {
throw given;
}
}
void qualified() {
throw new java.lang.IllegalStateException("qualified");
}
void nested() {
throw new Failure();
}
void missing() {
throw new Missing();
}
Object plain() {
return new NotAnException();
}
static Exception build(String why) {
return new IOException(why);
}
void call() throws Exception {
throw build("call");
}
void qualifiedCall() throws Exception {
throw Main.build("qualifiedCall");
}
<T extends Exception> void typeVariable(T t) throws T {
throw t;
}
void local() {
class Local extends RuntimeException {
}
throw new Local();
}
}
''',
}
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 exception_type(file, needle, at=0):
"""The answer with the caret `at` characters into the only line holding `needle`."""
lines = sources[file].splitlines()
found = [i for i, t in enumerate(lines) if needle in t]
assert len(found) == 1, (needle, found)
line = found[0]
column = lines[line].index(needle) + at
return request('workspace/executeCommand', {'command': 'openidea.java.exceptionType', 'arguments': [uri(file), line, column]})
ORDER = {'qualifiedName': 'app.errors.OrderException', 'displayName': 'OrderException'}
EXCEPTION = {'qualifiedName': 'java.lang.Exception', 'displayName': 'Exception'}
CASES = [
# throw new X(…): on the class, on `throw`, on `new`, inside a literal argument; a variable is not a class.
('throw new OrderException', 'OrderException', 10, ORDER),
('throw new OrderException', 'throw', 0, ORDER),
('throw new OrderException', 'new', 1, ORDER),
('throw new OrderException', '"order "', 2, ORDER),
('throw new OrderException', 'msg', 1, None),
# Multi-catch: each alternative; the caret right after a name takes the name to its left.
('catch (OrderException', 'OrderException', 3, ORDER),
('catch (OrderException', 'IllegalArgumentException', 0, {'qualifiedName': 'java.lang.IllegalArgumentException', 'displayName': 'IllegalArgumentException'}),
('catch (OrderException', 'OrderException', len('OrderException'), ORDER),
('catch (OrderException', 'catch', 1, None),
('catch (OrderException', '|', 0, None),
('catch (OrderException', ' e)', 1, None),
# A thrown variable: its declared type on `throw`, nothing on the variable.
('throw given', 'throw', 2, EXCEPTION),
('throw given', 'given', 2, None),
# A qualified name: the class, not its packages.
('java.lang.IllegalStateException', 'IllegalStateException', 4, {'qualifiedName': 'java.lang.IllegalStateException', 'displayName': 'IllegalStateException'}),
('java.lang.IllegalStateException', 'java', 1, None),
('java.lang.IllegalStateException', 'lang', 1, None),
# A nested class: its binary name, its simple name; also on its declaration and its superclass.
('throw new Failure', 'Failure', 2, {'qualifiedName': 'app.Main$Failure', 'displayName': 'Failure'}),
('static class Failure', 'Failure', 0, {'qualifiedName': 'app.Main$Failure', 'displayName': 'Failure'}),
('static class Failure', 'RuntimeException', 3, {'qualifiedName': 'java.lang.RuntimeException', 'displayName': 'RuntimeException'}),
('static class Failure', 'static', 1, None),
# A type that does not resolve, and a class that is not a Throwable.
('throw new Missing', 'Missing', 2, None),
('throw new Missing', 'throw', 1, None),
('static class NotAnException', 'NotAnException', 2, None),
('return new NotAnException', 'NotAnException', 2, None),
# A call: its return type on `throw`; the method name is not a class.
('throw build', 'throw', 0, EXCEPTION),
('throw build', 'build', 1, None),
('throw build', '"call"', 1, EXCEPTION),
# A qualified call is a reference to its method (UAST): nothing inside it, the qualifier's class aside.
('throw Main.build', '"qualifiedCall"', 1, None),
('throw Main.build', 'throw', 0, EXCEPTION),
# A type variable and a local class have no qualified name.
('throw t;', 'throw', 0, None),
('throw new Local', 'Local', 1, None),
# An import names the class too.
('import app.errors.OrderException', 'OrderException', 1, ORDER),
# Outside a throw, a reference or a class name: nothing.
('void nested()', 'nested', 1, None),
('public class Main', 'Main', 1, None),
]
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.exceptionType' 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 = []
for line_needle, needle, at, expected in CASES:
lines = sources['Main.java'].splitlines()
line = next(i for i, t in enumerate(lines) if line_needle in t)
column = lines[line].index(needle, lines[line].index(line_needle) if needle in line_needle else 0) + at
got = request('workspace/executeCommand', {'command': 'openidea.java.exceptionType', 'arguments': [uri('Main.java'), line, column]})
status = 'OK' if got == expected else 'FAIL'
if got != expected:
failed.append((line_needle, needle, at))
print(f'{status} {line_needle!r} at {needle!r}+{at}: {got}')
# A class declared in another file, read through the position in that file.
got = exception_type('errors/OrderException.java', 'class OrderException', 6)
print(('OK' if got == ORDER else 'FAIL'), 'declaration in its own file:', got)
if got != ORDER:
failed.append('declaration in its own file')
assert not failed, failed
print('exception-type: all cases passed')
finally:
proc.terminate()
proc.wait(timeout=20)
print('Evidence:', work, file=sys.stderr)