mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
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:
@@ -1176,6 +1176,22 @@ pub async fn lsp_prepare_rename(host: &Host, window: &str, doc: DocId, pos: Pos)
|
||||
host.project(window)?.lsp.prepare_rename(doc, pos).await
|
||||
}
|
||||
|
||||
/// The Throwable class the caret at `pos` names, for the exception breakpoint intention.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_exception_class_at(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Option<ExceptionClassRef>> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.exception_class_at(doc, pos, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// The class at `pos` and the members Pull Members Up / Push Members Down can move.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_hierarchy_members(
|
||||
@@ -2786,6 +2802,7 @@ ide_command::domain!(
|
||||
lsp_completion,
|
||||
lsp_document_highlights,
|
||||
lsp_document_links,
|
||||
lsp_exception_class_at,
|
||||
lsp_execute_code_action,
|
||||
lsp_execute_command,
|
||||
lsp_extract_interface,
|
||||
|
||||
@@ -21,6 +21,7 @@ const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
|
||||
|
||||
pub(crate) mod configuration;
|
||||
pub(crate) mod exception_breakpoints;
|
||||
mod exception_type;
|
||||
mod extract_interface;
|
||||
mod formatter;
|
||||
mod generated;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! The exception class at a caret, for the exception breakpoint intention, through the
|
||||
//! app-owned JDT extension (`java/java-usages`).
|
||||
use super::COMMAND_TIMEOUT;
|
||||
use crate::LspManager;
|
||||
use crate::types::ExceptionClassRef;
|
||||
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
|
||||
use serde_json::json;
|
||||
|
||||
const EXCEPTION_TYPE: &str = "openidea.java.exceptionType";
|
||||
|
||||
impl LspManager {
|
||||
/// The Throwable class the caret at `pos` names; `None` when there is none, or when no
|
||||
/// server of the document has the command.
|
||||
pub async fn exception_class_at(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Option<ExceptionClassRef>> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let mut targets = self.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == EXCEPTION_TYPE)).await;
|
||||
if targets.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let t = targets.swap_remove(0);
|
||||
let at = snap.position(&t, pos);
|
||||
let params = json!({
|
||||
"command": EXCEPTION_TYPE,
|
||||
"arguments": [snap.uri, at.line, at.character],
|
||||
});
|
||||
let found: Option<ExceptionClassRef> =
|
||||
self.call(&t, "workspace/executeCommand", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
}
|
||||
@@ -467,6 +467,16 @@ pub struct HierarchyMember {
|
||||
pub abstractable: bool,
|
||||
}
|
||||
|
||||
/// The exception class a caret names: a reference to it, its declaration, or a throw of it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExceptionClassRef {
|
||||
/// The binary name (`app.Outer$Failure`), as exception breakpoints take it.
|
||||
pub qualified_name: String,
|
||||
/// The simple name (`Failure`).
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
/// The class at a position and what can move: pull-up destinations, or the subclasses
|
||||
/// members are pushed into.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -3770,6 +3770,36 @@ async fn exception_breakpoints_send_the_whole_list_and_decode_states() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn exception_class_at_asks_the_extension_and_is_none_without_it() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.exceptionType"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let (doc, path) = h.open("Main.java", "class Main {\n void f() { throw new Failure(); }\n}");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
s.respond("workspace/executeCommand", json!({"qualifiedName": "app.Main$Failure", "displayName": "Failure"}));
|
||||
let found = h.mgr.exception_class_at(doc, Pos::new(1, 23), Default::default()).await.unwrap();
|
||||
assert_eq!(
|
||||
found,
|
||||
Some(ide_lsp::types::ExceptionClassRef {
|
||||
qualified_name: "app.Main$Failure".into(),
|
||||
display_name: "Failure".into()
|
||||
})
|
||||
);
|
||||
let asked = s.requested("workspace/executeCommand");
|
||||
assert_eq!(asked[0]["command"], "openidea.java.exceptionType");
|
||||
assert_eq!(asked[0]["arguments"], json!([uri_of(&path), 1, 23]));
|
||||
s.respond("workspace/executeCommand", json!(null));
|
||||
assert_eq!(h.mgr.exception_class_at(doc, Pos::new(0, 1), Default::default()).await.unwrap(), None);
|
||||
|
||||
let plain = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (doc, _) = plain.open("Main.java", "class Main {}");
|
||||
plain.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
assert_eq!(plain.mgr.exception_class_at(doc, Pos::new(0, 7), Default::default()).await.unwrap(), None);
|
||||
assert!(plain.launcher.state("jdtls").requested("workspace/executeCommand").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn debug_server_port_maps_to_module() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
|
||||
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.16.0",
|
||||
"1.17.0",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -349,6 +349,7 @@ lsp_code_lens trusted project_host bin
|
||||
lsp_completion trusted project_host bindings async
|
||||
lsp_document_highlights trusted project_host bindings async
|
||||
lsp_document_links trusted project_host bindings async
|
||||
lsp_exception_class_at trusted project_host bindings async
|
||||
lsp_execute_code_action trusted project_host bindings async
|
||||
lsp_execute_command trusted project_host bindings async
|
||||
lsp_extract_interface trusted project_host bindings async
|
||||
|
||||
@@ -846,6 +846,13 @@ export const commands = {
|
||||
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
|
||||
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
|
||||
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
|
||||
/** The Throwable class the caret at `pos` names, for the exception breakpoint intention. */
|
||||
lspExceptionClassAt: (request: RequestId, doc: DocId, pos: Pos) => typedError<{
|
||||
/** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */
|
||||
qualifiedName: string,
|
||||
/** The simple name (`Failure`). */
|
||||
displayName: string,
|
||||
} | null, IdeError>(__TAURI_INVOKE("lsp_exception_class_at", { request, doc, pos })),
|
||||
lspExecuteCodeAction: (request: RequestId, doc: DocId, action: CodeAction, answers: FormAnswer[]) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("lsp_execute_code_action", { request, doc, action, answers })),
|
||||
/**
|
||||
* Runs a server command (`workspace/executeCommand`), e.g. a completion item's
|
||||
@@ -6180,6 +6187,14 @@ export type ExceptionClassBreakpoint = {
|
||||
classExclusionFilters: string[],
|
||||
};
|
||||
|
||||
/** The exception class a caret names: a reference to it, its declaration, or a throw of it. */
|
||||
export type ExceptionClassRef = {
|
||||
/** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */
|
||||
qualifiedName: string,
|
||||
/** The simple name (`Failure`). */
|
||||
displayName: string,
|
||||
};
|
||||
|
||||
/** What a session's exception class breakpoints can do. */
|
||||
export type ExceptionClassSupport = {
|
||||
/** Whose class names the session takes: `java`. */
|
||||
|
||||
@@ -573,6 +573,31 @@ export function contributedIntentions(view: EditorView): ContributedIntention[]
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Providers of context actions that need an answer from the language server first. ⌥↵ waits for
|
||||
* them along with the server's code actions; the light bulb does too. `signal` aborts when the
|
||||
* answer is no longer wanted (the caret moved on).
|
||||
*/
|
||||
export const asyncIntentionProviders =
|
||||
Facet.define<(view: EditorView, signal: AbortSignal) => Promise<ContributedIntention[]>>();
|
||||
|
||||
export async function contributedIntentionsAsync(
|
||||
view: EditorView,
|
||||
signal: AbortSignal,
|
||||
): Promise<ContributedIntention[]> {
|
||||
const found = await Promise.all(
|
||||
view.state.facet(asyncIntentionProviders).map((p) =>
|
||||
Promise.resolve()
|
||||
.then(() => p(view, signal))
|
||||
.catch((e: unknown) => {
|
||||
if (!signal.aborted) console.error("intention provider failed", e);
|
||||
return [];
|
||||
}),
|
||||
),
|
||||
);
|
||||
return found.flat();
|
||||
}
|
||||
|
||||
// --- navigation history ------------------------------------------------------
|
||||
|
||||
/** One entry of the Back/Forward (⌘[ / ⌘]) history. 0-based line, UTF-16 col. */
|
||||
|
||||
@@ -54,6 +54,7 @@ const {
|
||||
withInspectionControls,
|
||||
} = await import("./intentions");
|
||||
const { useLspPopup, closePopup } = await import("./popupStore");
|
||||
const { asyncIntentionProviders } = await import("@/editor/api");
|
||||
const { setFileDiagnostics, toLintDiagnostics } = await import("./diagnostics");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
|
||||
@@ -195,6 +196,58 @@ describe("⌥↵ popup timing", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("context actions a feature finds through the language server", () => {
|
||||
const editor = (...providers: Parameters<typeof asyncIntentionProviders.of>[0][]) => {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "f(1);\n",
|
||||
extensions: [
|
||||
lspDoc.of({ doc: 1, path: "/p/A.java", language: "java", uiMode: null, readOnly: false }),
|
||||
...providers.map((p) => asyncIntentionProviders.of(p)),
|
||||
],
|
||||
}),
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
};
|
||||
const labels = () => (useLspPopup.getState().popup as { items: { label: string }[] }).items.map((i) => i.label);
|
||||
const intention = (label: string) => ({ id: label, label, run: () => {} });
|
||||
|
||||
it("waits for them and lists them with the server's actions", async () => {
|
||||
let answer!: (v: ReturnType<typeof intention>[]) => void;
|
||||
const view = editor(() => new Promise((r) => (answer = r)));
|
||||
lspCodeActions.mockResolvedValue({ status: "ok", data: [{ ...resolved, edit: null }] });
|
||||
const shown = showIntentions(view);
|
||||
await Promise.resolve();
|
||||
answer([intention("Create exception breakpoint on Failure")]);
|
||||
await shown;
|
||||
expect(labels()).toEqual(
|
||||
expect.arrayContaining(["Create exception breakpoint on Failure", "Introduce local variable"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("lists them alone when the server has nothing", async () => {
|
||||
const view = editor(async () => [intention("Disable exception breakpoint on Failure")]);
|
||||
lspCodeActions.mockResolvedValue({ status: "ok", data: [] });
|
||||
await showIntentions(view);
|
||||
expect(labels()).toEqual(["Disable exception breakpoint on Failure"]);
|
||||
});
|
||||
|
||||
it("keeps the other rows when one provider fails", async () => {
|
||||
const error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const view = editor(
|
||||
async () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
async () => [intention("Enable exception breakpoint on Failure")],
|
||||
);
|
||||
lspCodeActions.mockResolvedValue({ status: "ok", data: [] });
|
||||
await showIntentions(view);
|
||||
expect(labels()).toEqual(["Enable exception breakpoint on Failure"]);
|
||||
error.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("inspection controls in ⌥↵ (issue #42)", () => {
|
||||
const editorAt = (path: string) => {
|
||||
const view = new EditorView({
|
||||
|
||||
@@ -11,6 +11,7 @@ import { diff } from "@codemirror/merge";
|
||||
import { commands, isCancelled, type CodeAction, type Diagnostic } from "@/platform/ipc";
|
||||
import {
|
||||
contributedIntentions,
|
||||
contributedIntentionsAsync,
|
||||
contributedQuickFixes,
|
||||
intentionProviders,
|
||||
intentionsChanged,
|
||||
@@ -574,13 +575,18 @@ export async function showIntentions(view: EditorView) {
|
||||
display(itemsFor([]), true);
|
||||
}, INTENTIONS_POPUP_DELAY_MS);
|
||||
|
||||
const asked = new AbortController();
|
||||
try {
|
||||
let failure: unknown = null;
|
||||
// Like IDEA, only applicable intentions are listed (servers also report disabled refactorings).
|
||||
const actions = await fetchIntentions(view).catch((e: unknown) => {
|
||||
failure = e;
|
||||
return null;
|
||||
});
|
||||
const [actions, found] = await Promise.all([
|
||||
fetchIntentions(view).catch((e: unknown) => {
|
||||
failure = e;
|
||||
return null;
|
||||
}),
|
||||
contributedIntentionsAsync(view, asked.signal),
|
||||
]);
|
||||
local.push(...found);
|
||||
clearTimeout(timer);
|
||||
const items = actions ? itemsFor(actions) : withInspectionControls(view, listedIntentions(view, local));
|
||||
if (!items.length) {
|
||||
@@ -599,6 +605,8 @@ export async function showIntentions(view: EditorView) {
|
||||
clearTimeout(timer);
|
||||
if (ours()) closePopup();
|
||||
reportLspError(view, e, true);
|
||||
} finally {
|
||||
asked.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -704,6 +712,7 @@ const bulbField = StateField.define<Bulb | null>({
|
||||
const bulbPlugin = ViewPlugin.fromClass(
|
||||
class {
|
||||
private lookup = debounce(() => void this.run(), 500);
|
||||
private asked: AbortController | null = null;
|
||||
constructor(private view: EditorView) {
|
||||
this.lookup();
|
||||
}
|
||||
@@ -732,7 +741,9 @@ const bulbPlugin = ViewPlugin.fromClass(
|
||||
const typoFix = spellingIntentions(this.view).length > 0;
|
||||
const selection = state.selection.main;
|
||||
const ownFix = contributedQuickFixes(this.view, selection.from, selection.to).length > 0;
|
||||
const local = typoFix || ownFix || contributedIntentions(this.view).length > 0;
|
||||
this.asked?.abort();
|
||||
const asked = (this.asked = new AbortController());
|
||||
const found = contributedIntentionsAsync(this.view, asked.signal);
|
||||
const backoff = codeActionBackoff.active(doc.doc);
|
||||
let actions: CodeAction[] = [];
|
||||
if (!backoff) {
|
||||
@@ -742,6 +753,7 @@ const bulbPlugin = ViewPlugin.fromClass(
|
||||
if (isUnavailable(e)) codeActionBackoff.mark(doc.doc);
|
||||
}
|
||||
}
|
||||
const local = typoFix || ownFix || contributedIntentions(this.view).length > 0 || (await found).length > 0;
|
||||
if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection) || !this.view.hasFocus)
|
||||
return;
|
||||
const line = state.doc.lineAt(state.selection.main.head).number;
|
||||
@@ -759,6 +771,7 @@ const bulbPlugin = ViewPlugin.fromClass(
|
||||
}
|
||||
destroy() {
|
||||
this.lookup.cancel();
|
||||
this.asked?.abort();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { ExceptionClassRef } from "@/bindings";
|
||||
|
||||
const lspExceptionClassAt = vi.fn();
|
||||
const cancelRequest = vi.fn(async () => ({ status: "ok" as const, data: null }));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspExceptionClassAt, cancelRequest } };
|
||||
});
|
||||
|
||||
const { contributedIntentionsAsync } = await import("@/editor/api");
|
||||
const { exceptionBreakpointIntention } = await import("../editor/exceptionBreakpointIntention");
|
||||
const {
|
||||
addExceptionClass,
|
||||
loadExceptionClasses,
|
||||
removeAllExceptionClasses,
|
||||
updateExceptionClass,
|
||||
useExceptionClasses,
|
||||
} = await import("../breakpoints/exceptionClasses");
|
||||
|
||||
const FAILURE: ExceptionClassRef = { qualifiedName: "app.Main$Failure", displayName: "Failure" };
|
||||
const text = "class Main {\n void f() { throw new Failure(); }\n}\n";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
const editor = (language = "java", caret = text.indexOf("Failure")) => {
|
||||
const ctx = { doc: 7, path: "/p/Main.java", language, uiMode: null, readOnly: false };
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text,
|
||||
selection: { anchor: caret },
|
||||
extensions: exceptionBreakpointIntention(ctx),
|
||||
}),
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
};
|
||||
const offered = (view: EditorView) => contributedIntentionsAsync(view, new AbortController().signal);
|
||||
const answer = (data: ExceptionClassRef | null) => lspExceptionClassAt.mockResolvedValue({ status: "ok", data });
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
loadExceptionClasses("/p");
|
||||
removeAllExceptionClasses();
|
||||
});
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("Create / Enable / Disable exception breakpoint (IDEA's intention)", () => {
|
||||
it("asks the language server about the caret, in UTF-16 line and column", async () => {
|
||||
answer(FAILURE);
|
||||
await offered(editor());
|
||||
expect(lspExceptionClassAt).toHaveBeenCalledWith(expect.any(Number), 7, { line: 1, col: 23 });
|
||||
});
|
||||
|
||||
it("creates a breakpoint on caught and uncaught throws of the class", async () => {
|
||||
answer(FAILURE);
|
||||
const [action] = await offered(editor());
|
||||
expect(action).toMatchObject({ label: "Create exception breakpoint on Failure", icon: "breakpoint-exception" });
|
||||
await action!.run();
|
||||
expect(useExceptionClasses.getState().list).toEqual([
|
||||
expect.objectContaining({ className: "app.Main$Failure", caught: true, uncaught: true, enabled: true }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("disables an enabled breakpoint on the class and enables a disabled one, never removing it", async () => {
|
||||
answer(FAILURE);
|
||||
const bp = addExceptionClass("app.Main$Failure");
|
||||
const view = editor();
|
||||
const [disable] = await offered(view);
|
||||
expect(disable!.label).toBe("Disable exception breakpoint on Failure");
|
||||
await disable!.run();
|
||||
expect(useExceptionClasses.getState().list).toEqual([expect.objectContaining({ id: bp.id, enabled: false })]);
|
||||
const [enable] = await offered(view);
|
||||
expect(enable!.label).toBe("Enable exception breakpoint on Failure");
|
||||
await enable!.run();
|
||||
expect(useExceptionClasses.getState().list).toEqual([expect.objectContaining({ id: bp.id, enabled: true })]);
|
||||
});
|
||||
|
||||
it("acts on the first breakpoint of the class, as IDEA does", async () => {
|
||||
answer(FAILURE);
|
||||
const first = addExceptionClass("app.Main$Failure");
|
||||
updateExceptionClass(first.id, { enabled: false });
|
||||
const second = addExceptionClass("app.Main$Failure");
|
||||
const [action] = await offered(editor());
|
||||
expect(action!.label).toBe("Enable exception breakpoint on Failure");
|
||||
await action!.run();
|
||||
expect(useExceptionClasses.getState().list.map((b) => [b.id, b.enabled])).toEqual([
|
||||
[first.id, true],
|
||||
[second.id, true],
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers nothing where the caret names no exception class", async () => {
|
||||
answer(null);
|
||||
expect(await offered(editor())).toEqual([]);
|
||||
});
|
||||
|
||||
it("is not offered outside Java", async () => {
|
||||
answer(FAILURE);
|
||||
expect(await offered(editor("kotlin"))).toEqual([]);
|
||||
expect(lspExceptionClassAt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels the request when the answer is no longer wanted", async () => {
|
||||
lspExceptionClassAt.mockImplementation(() => new Promise(() => {}));
|
||||
const asked = new AbortController();
|
||||
const pending = contributedIntentionsAsync(editor(), asked.signal);
|
||||
await vi.waitFor(() => expect(lspExceptionClassAt).toHaveBeenCalled());
|
||||
asked.abort();
|
||||
expect(await pending).toEqual([]);
|
||||
expect(cancelRequest).toHaveBeenCalledWith(lspExceptionClassAt.mock.calls[0]![0]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* IDEA's Create / Enable / Disable exception breakpoint intention (ControlExceptionBreakpointIntentionAction)
|
||||
* on a reference to a Java exception class, its declaration or a throw of it. The language server
|
||||
* names the class; the breakpoint is one of the Java Exception Breakpoints, never removed here.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { asyncIntentionProviders, whenSynced, type ContributedIntention, type EditorDocContext } from "@/editor/api";
|
||||
import { call, commands, nextRequestId, type ExceptionClassRef } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { addExceptionClass, updateExceptionClass, useExceptionClasses } from "../breakpoints/exceptionClasses";
|
||||
|
||||
const firstNamed = (qualifiedName: string) =>
|
||||
useExceptionClasses.getState().list.find((b) => b.className.trim() === qualifiedName);
|
||||
|
||||
/** IDEA decides between creating and switching when it offers the action, and applies that on run. */
|
||||
function controlExceptionClass(qualifiedName: string, enable: boolean) {
|
||||
const existing = firstNamed(qualifiedName);
|
||||
if (existing) updateExceptionClass(existing.id, { enabled: enable });
|
||||
else if (enable) addExceptionClass(qualifiedName);
|
||||
}
|
||||
|
||||
function intentionFor(found: ExceptionClassRef): ContributedIntention {
|
||||
const name = found.displayName;
|
||||
const existing = firstNamed(found.qualifiedName);
|
||||
const enable = !existing?.enabled;
|
||||
return {
|
||||
id: "debugger.controlExceptionBreakpoint",
|
||||
label: !existing
|
||||
? tx`Create exception breakpoint on ${name}`
|
||||
: existing.enabled
|
||||
? tx`Disable exception breakpoint on ${name}`
|
||||
: tx`Enable exception breakpoint on ${name}`,
|
||||
icon: "breakpoint-exception",
|
||||
run: () => controlExceptionClass(found.qualifiedName, enable),
|
||||
};
|
||||
}
|
||||
|
||||
async function exceptionClassAt(ctx: EditorDocContext, view: EditorView, signal: AbortSignal) {
|
||||
await whenSynced(view);
|
||||
if (signal.aborted) return null;
|
||||
const head = view.state.selection.main.head;
|
||||
const line = view.state.doc.lineAt(head);
|
||||
const request = nextRequestId();
|
||||
const abandoned = new Promise<null>((resolve) =>
|
||||
signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
void commands.cancelRequest(request).catch(() => undefined);
|
||||
resolve(null);
|
||||
},
|
||||
{ once: true },
|
||||
),
|
||||
);
|
||||
const asked = call(commands.lspExceptionClassAt(request, ctx.doc, { line: line.number - 1, col: head - line.from }));
|
||||
// No Java server, an untrusted project, a cancelled request: no intention.
|
||||
return Promise.race([asked.catch(() => null), abandoned]);
|
||||
}
|
||||
|
||||
export function exceptionBreakpointIntention(ctx: EditorDocContext): Extension {
|
||||
if (ctx.language !== "java") return [];
|
||||
return asyncIntentionProviders.of(async (view, signal) => {
|
||||
const found = await exceptionClassAt(ctx, view, signal);
|
||||
return found && !signal.aborted ? [intentionFor(found)] : [];
|
||||
});
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import { breakpointGutter } from "./editor/breakpointGutter";
|
||||
import { executionPoint } from "./editor/execution";
|
||||
import { runToCursorInlay } from "./editor/runToCursor";
|
||||
import { installSmartStepPicking, smartStepTargets } from "./editor/smartStep";
|
||||
import { exceptionBreakpointIntention } from "./editor/exceptionBreakpointIntention";
|
||||
import { hotSwapMenuItems, onHotCodeReplace } from "./hotswap";
|
||||
import { installFlutterHotReloadOnSave } from "./flutterReload";
|
||||
import {
|
||||
@@ -156,6 +157,7 @@ export function activate(): () => void {
|
||||
selectionValueTooltip(),
|
||||
quickEvaluateMouse(),
|
||||
smartStepTargets(ctx),
|
||||
exceptionBreakpointIntention(ctx),
|
||||
],
|
||||
}),
|
||||
installSmartStepPicking(),
|
||||
|
||||
@@ -2070,6 +2070,9 @@
|
||||
"Add Request Breakpoint": "Add Request Breakpoint",
|
||||
"Java Exception Breakpoints": "Java Exception Breakpoints",
|
||||
"Add Java Exception Breakpoint": "Add Java Exception Breakpoint",
|
||||
"Create exception breakpoint on {name}": "Create exception breakpoint on {name}",
|
||||
"Enable exception breakpoint on {name}": "Enable exception breakpoint on {name}",
|
||||
"Disable exception breakpoint on {name}": "Disable exception breakpoint on {name}",
|
||||
"Any exception": "Any exception",
|
||||
"Enable Any exception": "Enable Any exception",
|
||||
"Stops at every exception thrown in a Java debug session.": "Stops at every exception thrown in a Java debug session.",
|
||||
|
||||
@@ -1493,6 +1493,9 @@
|
||||
"Exception breakpoints": "异常断点",
|
||||
"Java Exception Breakpoints": "Java 异常断点",
|
||||
"Add Java Exception Breakpoint": "添加 Java 异常断点",
|
||||
"Create exception breakpoint on {name}": "在 {name} 上创建异常断点",
|
||||
"Enable exception breakpoint on {name}": "启用 {name} 上的异常断点",
|
||||
"Disable exception breakpoint on {name}": "禁用 {name} 上的异常断点",
|
||||
"Any exception": "任何异常",
|
||||
"Enable Any exception": "启用“任何异常”",
|
||||
"Stops at every exception thrown in a Java debug session.": "在 Java 调试会话中抛出的每个异常处停止。",
|
||||
|
||||
Reference in New Issue
Block a user