Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,86 @@ JDTLS uses **CamelCase fuzzy matching** for symbol queries. For example, searchi

## Debugger

### Main-method gutter actions

Java main-method gutter positions come from the Tree-sitter runnable queries.
The debug locator recognizes main tasks by their `ZED_JAVA_RUNNABLE=main`
environment marker, independently of the language server and debug adapter.
It then generates a launch configuration for the selected debug adapter.
Neither step calls a language server, starts a debug session, or runs the task's
shell command.

The locator supports the `Java` (JDTLS) and `Metals` debug adapters. With either
adapter selected, Java main-method gutter actions include `Debug: Run <class>`;
no `.zed/debug.json` is required. Other adapters need their own configuration
mapping.

If you disable the built-in Java tasks and provide your own main-method task,
add `"ZED_JAVA_RUNNABLE": "main"` to that task's `env` object to opt in. Its
environment variables are forwarded to the debug configuration, excluding this
marker. Test runnables are not handled by this locator.

### Main methods with JDTLS

Use the `Java` debug adapter with JDTLS enabled:

```jsonc
{
"languages": {
"Java": {
"language_servers": ["jdtls", "!metals"],
"debuggers": ["Java"]
}
}
}
```

The gutter scenario records `mainFile: "$ZED_FILE"`. When you start debugging,
the adapter asks JDTLS to resolve the main method in that file, preserves its
project identity, and builds before resolving the classpath and starting the
session. A failed or cancelled build stops the launch. JDTLS must have imported
the project for this launch step.
Build requests have a five-minute proxy timeout; other requests retain their
five-second timeout.

If a source file contains multiple main classes, the adapter reports an ambiguity
instead of choosing one. Create a configuration in `.zed/debug.json` with
`mainFile`, `mainClass`, and, if needed, `projectName` to select the entry.
Existing launch configurations without `mainFile` retain their current behavior.

### Main methods with Metals

If you use Metals instead of JDTLS, install the
[Scala extension](https://github.com/scalameta/metals-zed) and select its debug
adapter for Java:

```jsonc
{
"languages": {
"Java": {
"language_servers": ["metals", "!jdtls"],
"debuggers": ["Metals"]
}
}
}
```

With the Metals adapter selected, the gutter actions for Java main methods and
their classes include `Debug: Run <class>`. No `.zed/debug.json` is required.
The generated configuration contains `path: "$ZED_FILE"` and
`runType: "runOrTestFile"`. When you start debugging, the Metals adapter contacts
its language server to discover the main class and build target and prepare the
session through its existing build-server integration. Metals must have imported
your project for this launch step. Debugging uses Metals' file discovery rather
than the task's command or arguments.

This requires Metals to be available for Java in your Scala extension
installation, and its DAP proxy to be enabled. The Scala extension's
[debugging documentation](https://github.com/scalameta/metals-zed#debugging)
describes its setup and restrictions.

### Debugging with JDTLS

Debug support is enabled via our [Fork of Java Debug](https://github.com/zed-industries/java-debug), which the extension will automatically download and start for you. Please refer to the [Zed Documentation](https://zed.dev/docs/debugger#getting-started) for general information about how debugging works in Zed.

### Launch Mode
Expand Down
4 changes: 4 additions & 0 deletions debug_adapter_schemas/Java.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
"type": "string",
"description": "The fully qualified name of the class containing the main method. If not specified, the debugger automatically resolves the possible main class from the current project."
},
"mainFile": {
"type": "string",
"description": "The absolute path to a Java source file, or $ZED_FILE. Resolves the main class and project from this file and builds before launch. Use mainClass and projectName to disambiguate multiple entries."
},
"args": {
"oneOf": [
{
Expand Down
2 changes: 2 additions & 0 deletions extension.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ languages = ["Gradle", "Gradle KTS"]

[debug_adapters.Java]

[debug_locators.java]

[[capabilities]]
kind = "process:exec"
command = "*"
Expand Down
3 changes: 3 additions & 0 deletions languages/java/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
"tags": [
"java-main"
],
"env": {
"ZED_JAVA_RUNNABLE": "main"
},
"shell": {
"with_arguments": {
"program": "/bin/sh",
Expand Down
149 changes: 146 additions & 3 deletions proxy/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,28 @@ use std::{
use crate::pending::PendingResponses;
use proxy_common::encode_lsp;

pub const TIMEOUT: Duration = Duration::from_secs(5);
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5);
const BUILD_TIMEOUT: Duration = Duration::from_secs(300);

#[derive(Deserialize)]
struct HttpBody {
method: String,
params: Value,
}

impl HttpBody {
fn timeout(&self) -> Duration {
if self.method == "workspace/executeCommand"
&& self.params.get("command").and_then(Value::as_str)
== Some("vscode.java.buildWorkspace")
{
BUILD_TIMEOUT
} else {
DEFAULT_TIMEOUT
}
}
}

#[derive(Serialize)]
struct LspRequest {
jsonrpc: &'static str,
Expand Down Expand Up @@ -80,6 +94,7 @@ pub fn handle_http(
let seq = counter.fetch_add(1, Ordering::Relaxed);
let id = Value::String(format!("{owned_id_prefix}http-{seq}"));
let rx = pending.register(id.clone());
let timeout = req.timeout();

let lsp_req = LspRequest {
jsonrpc: "2.0",
Expand All @@ -94,7 +109,7 @@ pub fn handle_http(
};

let response = if request_sent {
match rx.recv_timeout(TIMEOUT) {
match rx.recv_timeout(timeout) {
Ok(resp) => resp,
Err(_) => {
pending.remove(&id);
Expand All @@ -112,7 +127,10 @@ pub fn handle_http(
"id": id,
"error": {
"code": -32803,
"message": "Request to language server timed out after 5000ms."
"message": format!(
"Request to language server timed out after {}ms.",
timeout.as_millis()
)
}
})
}
Expand All @@ -137,3 +155,128 @@ pub fn handle_http(
let _ = stream.write_all(http_resp.as_bytes());
let _ = stream.write_all(&resp_body);
}

#[cfg(test)]
mod tests {
use super::*;
use proxy_common::{parse_lsp_content, LspReader};
use serde_json::json;
use std::{
net::{TcpListener, TcpStream},
thread::{self, JoinHandle},
};

struct HttpExchange {
client: TcpStream,
lsp: LspReader<TcpStream>,
pending: Arc<PendingResponses>,
handler: JoinHandle<()>,
}

impl HttpExchange {
fn start(method: &str, params: Value) -> Self {
let (mut client, server) = connected_streams();
let (writer, lsp) = connected_streams();
let pending = Arc::new(PendingResponses::new());
let handler_pending = pending.clone();
let handler = thread::spawn(move || {
handle_http(
server,
Arc::new(Mutex::new(writer)),
handler_pending,
Arc::new(AtomicU64::new(1)),
"test-",
);
});
let body = json!({ "method": method, "params": params }).to_string();
write!(
client,
"POST / HTTP/1.1\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
)
.unwrap();

Self {
client,
lsp: LspReader::new(lsp),
pending,
handler,
}
}

fn next_lsp_message(&mut self) -> Value {
let message = self.lsp.read_message().unwrap().unwrap();
parse_lsp_content(&message).unwrap()
}

fn finish(mut self) -> Value {
let mut response = String::new();
self.client.read_to_string(&mut response).unwrap();
self.handler.join().unwrap();
let (headers, body) = response.split_once("\r\n\r\n").unwrap();
assert!(headers.starts_with("HTTP/1.1 200 OK"));
serde_json::from_str(body).unwrap()
}
}

fn connected_streams() -> (TcpStream, TcpStream) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
let (server, _) = listener.accept().unwrap();
for stream in [&client, &server] {
stream
.set_read_timeout(Some(Duration::from_secs(15)))
.unwrap();
}
(client, server)
}

#[test]
fn build_succeeding_after_the_default_timeout_returns_success() {
let mut exchange = HttpExchange::start(
"workspace/executeCommand",
json!({
"command": "vscode.java.buildWorkspace",
"arguments": ["{\"mainClass\":\"example.Main\",\"isFullBuild\":false}"],
}),
);
let request = exchange.next_lsp_message();

thread::sleep(DEFAULT_TIMEOUT + Duration::from_secs(1));
let response = json!({ "jsonrpc": "2.0", "id": request["id"], "result": 1 });
assert!(exchange.pending.route(&response));

assert_eq!(exchange.finish(), response);
}

#[test]
fn ordinary_request_timeout_cancels_the_request_and_reports_its_duration() {
let mut exchange = HttpExchange::start(
"workspace/executeCommand",
json!({ "command": "vscode.java.resolveMainMethod" }),
);
let request = exchange.next_lsp_message();

let cancellation = exchange.next_lsp_message();
let response = exchange.finish();

assert_eq!(cancellation["method"], "$/cancelRequest");
assert_eq!(cancellation["params"]["id"], request["id"]);
assert_eq!(response["id"], request["id"]);
assert_eq!(response["error"]["code"], -32803);
assert_eq!(
response["error"]["message"],
"Request to language server timed out after 5000ms."
);
}

#[test]
fn build_command_in_another_method_keeps_the_default_timeout() {
let request = HttpBody {
method: "textDocument/hover".into(),
params: json!({ "command": "vscode.java.buildWorkspace" }),
};

assert_eq!(request.timeout(), DEFAULT_TIMEOUT);
}
}
Loading