summaryrefslogtreecommitdiff
path: root/src/lsp
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-23 10:51:51 -0300
committerGabriel Schneider <[email protected]>2026-10-23 17:10:58 -0300
commit7b743fcc7d568f13512a59089c5214bb6fa3282f (patch)
treeab133f70ded7b9b415115345adfc6ff043117b03 /src/lsp
parentb8f076b63d6fcbb01539d5541520a32bccc0e219 (diff)
downloadpardes-7b743fcc7d568f13512a59089c5214bb6fa3282f.tar.gz
pardes-7b743fcc7d568f13512a59089c5214bb6fa3282f.zip
Audit (LSP, PDF): one client dispatch, docParams, renameEdits in one loop, std.c externs; one whole-page render, openBytes only
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src/lsp')
-rw-r--r--src/lsp/lsp.zig34
-rw-r--r--src/lsp/lsp_client.zig133
2 files changed, 71 insertions, 96 deletions
diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig
index 1c1b57a2..1263b583 100644
--- a/src/lsp/lsp.zig
+++ b/src/lsp/lsp.zig
@@ -91,39 +91,31 @@ test "an explain request narrates the query named in its arg, a definition by de
/// Every language, Zig's (zls) included, through the protocol client, which
/// runs its server as a child process. None on the web or the board.
-const backends = if (@import("pardes_config").platform == .web or @import("pardes_config").platform == .esp32p4)
- .{}
-else
- .{@import("lsp_client.zig")};
+const has_client = switch (@import("pardes_config").platform) {
+ .web, .esp32p4 => false,
+ else => true,
+};
+const client = if (has_client) @import("lsp_client.zig") else void;
pub const backend_name = "lsp-client";
-pub const supports: std.EnumSet(Kind) = blk: {
- var s: std.EnumSet(Kind) = .empty;
- for (0..backends.len) |i| s.setUnion(backends[i].supports);
- break :blk s;
-};
+pub const supports: std.EnumSet(Kind) = if (has_client) client.supports else .empty;
pub fn speaks(path: []const u8) bool {
- inline for (backends) |b| if (b.speaks(path)) return true;
- return false;
+ return has_client and client.speaks(path);
}
pub fn query(io: std.Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void {
if (req.kind == .status) {
try out.print("backend: {s}\n", .{backend_name});
- inline for (backends) |b| try b.query(io, gpa, arena, req, out);
+ if (has_client) try client.query(io, gpa, arena, req, out);
return;
}
- inline for (backends) |b| {
- if (b.speaks(req.path) and b.supports.contains(req.kind))
- return b.query(io, gpa, arena, req, out);
- }
- if (req.kind == .explain and backends.len > 0)
- return backends[0].query(io, gpa, arena, req, out);
+ if (has_client and (req.kind == .explain or (client.speaks(req.path) and client.supports.contains(req.kind))))
+ return client.query(io, gpa, arena, req, out);
// Nothing asked: said why, where an empty answer would read as nothing
// found.
- inline for (backends) |b| if (b.speaks(req.path))
+ if (speaks(req.path))
return none(out, "the language server for this file does not answer it", .{});
try none(out, "no language server for this file", .{});
}
@@ -136,7 +128,7 @@ pub fn none(out: *std.Io.Writer, comptime fmt: []const u8, args: anytype) std.Io
// Called on server reader threads; the sink must copy text before returning.
pub fn setStatusSink(ctx: ?*anyopaque, cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void) void {
- inline for (backends) |b| b.setStatusSink(ctx, cb);
+ if (has_client) client.setStatusSink(ctx, cb);
}
pub fn rel(base: []const u8, path: []const u8) []const u8 {
@@ -218,7 +210,7 @@ test "LSP encoders report every insufficient output capacity" {
}
test "a question no backend answers for a file says why rather than find nothing" {
- if (backends.len == 0) return;
+ if (!has_client) return;
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var buf: [256]u8 = undefined;
diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig
index e356c979..5baf7129 100644
--- a/src/lsp/lsp_client.zig
+++ b/src/lsp/lsp_client.zig
@@ -52,26 +52,15 @@ const libc = std.c;
const lsp = @import("lsp.zig");
extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
-extern "c" fn chdir(path: [*:0]const u8) c_int;
-extern "c" fn _exit(status: c_int) noreturn;
-extern "c" fn setsid() libc.pid_t;
-extern "c" fn access(path: [*:0]const u8, mode: c_int) c_int;
-/// std.posix.getenv is gone in 0.16 and std.process.Environ wants an Io
-extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8;
extern "c" fn usleep(usec: c_uint) c_int;
extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int;
// test-only libc (the seam's own tests build a real directory tree)
extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8;
-extern "c" fn mkdir(path: [*:0]const u8, mode: libc.mode_t) c_int;
extern "c" fn system(cmd: [*:0]const u8) c_int;
-const X_OK: c_int = 1;
-const POLLIN: i16 = 0x001;
-const POLLOUT: i16 = 0x004;
-/// linux MSG_NOSIGNAL; darwin has no such flag and gets SO_NOSIGPIPE on the
-/// socket instead (0x1022), set right after socketpair. Both numbers are ABI.
-const msg_nosignal: c_int = if (builtin.os.tag.isDarwin()) 0 else 0x4000;
-const so_nosigpipe: c_int = 0x1022;
+/// darwin has no MSG_NOSIGNAL and gets SO_NOSIGPIPE on the socket instead,
+/// set right after socketpair.
+const msg_nosignal = if (builtin.os.tag.isDarwin()) 0 else libc.MSG.NOSIGNAL;
/// One language server this client knows how to run. Adding a language is
/// adding a row; nothing below the table branches on a language.
@@ -167,7 +156,7 @@ fn specFor(path: []const u8) ?usize {
for (&specs, 0..) |*s, i| {
for (s.exts) |e| {
if (!std.mem.endsWith(u8, path, e)) continue;
- if (getenv(s.env)) |v| if (v[0] == 0) return null; // "" disables
+ if (libc.getenv(s.env)) |v| if (v[0] == 0) return null; // "" disables
return i;
}
}
@@ -602,10 +591,7 @@ fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req,
try out.writeByte('\n');
},
.document_symbols => {
- var b: std.ArrayList(u8) = .empty;
- try app(&b, arena, "\"textDocument\":{\"uri\":");
- try jstr(&b, arena, uri.items);
- try app(&b, arena, "}");
+ const b = try docParams(arena, uri.items);
const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return;
try walkSymbols(&cx, c.caps.enc, uri.items, result, 0);
},
@@ -636,18 +622,14 @@ fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req,
try renameEdits(&cx, c.caps.enc, uri.items, result, req.source, old, also.items);
},
.format => {
- var b: std.ArrayList(u8) = .empty;
- try app(&b, arena, "\"textDocument\":{\"uri\":");
- try jstr(&b, arena, uri.items);
- try app(&b, arena, "},\"options\":{\"tabSize\":4,\"insertSpaces\":true}");
+ var b = try docParams(arena, uri.items);
+ try app(&b, arena, ",\"options\":{\"tabSize\":4,\"insertSpaces\":true}");
const result = (try call(c, io, arena, "textDocument/formatting", b.items, deadline)) orelse return;
try formatEdits(&cx, c.caps.enc, result, req.source);
},
.code_action => {
- var b: std.ArrayList(u8) = .empty;
- try app(&b, arena, "\"textDocument\":{\"uri\":");
- try jstr(&b, arena, uri.items);
- try b.print(arena, "}},\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch });
+ var b = try docParams(arena, uri.items);
+ try b.print(arena, ",\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch });
const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return;
for (items(result)) |ca| {
const title = str(get(ca, "title")) orelse continue;
@@ -726,10 +708,7 @@ fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth:
/// sent, so `]d` right after an edit sees the new truth, not the old one.
fn diagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void {
if (c.caps.pull) {
- var b: std.ArrayList(u8) = .empty;
- try app(&b, arena, "\"textDocument\":{\"uri\":");
- try jstr(&b, arena, uri);
- try app(&b, arena, "}");
+ const b = try docParams(arena, uri);
const result = (try call(c, io, arena, "textDocument/diagnostic", b.items, deadline)) orelse return;
for (items(get(result, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena);
return;
@@ -826,6 +805,8 @@ fn renameEdits(cx: *Cx, enc: Enc, self_uri: []const u8, result: std.json.Value,
var edits: std.ArrayList(PutEdit) = .empty;
var foreign = false;
+ // (uri, edits) per file, from either shape of a WorkspaceEdit
+ var files: std.ArrayList(struct { []const u8, ?std.json.Value }) = .empty;
if (get(result, "documentChanges")) |dcs| {
for (items(dcs)) |dc| {
if (get(dc, "kind") != null) {
@@ -833,32 +814,25 @@ fn renameEdits(cx: *Cx, enc: Enc, self_uri: []const u8, result: std.json.Value,
continue;
}
const u = str(get(get(dc, "textDocument"), "uri")) orelse continue;
- const in_self = std.mem.eql(u8, u, self_uri);
- if (!in_self) foreign = true;
- for (items(get(dc, "edits"))) |ed| {
- if (in_self) {
- // one malformed edit poisons the WHOLE mutating response:
- // applying the valid remainder would be a partial edit set
- const span = byteSpan(src, get(ed, "range"), enc) orelse return;
- const text = str(get(ed, "newText")) orelse return;
- edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text }) catch return error.OutOfMemory;
- } else try emitRange(cx, enc, u, get(ed, "range"), flat(cx.arena, str(get(ed, "newText")) orelse ""));
- }
+ files.append(cx.arena, .{ u, get(dc, "edits") }) catch return error.OutOfMemory;
}
} else if (get(result, "changes")) |ch| if (ch == .object) {
var it = ch.object.iterator();
- while (it.next()) |e| {
- const in_self = std.mem.eql(u8, e.key_ptr.*, self_uri);
- if (!in_self) foreign = true;
- for (items(e.value_ptr.*)) |ed| {
- if (in_self) {
- const span = byteSpan(src, get(ed, "range"), enc) orelse return;
- const text = str(get(ed, "newText")) orelse return;
- edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text }) catch return error.OutOfMemory;
- } else try emitRange(cx, enc, e.key_ptr.*, get(ed, "range"), flat(cx.arena, str(get(ed, "newText")) orelse ""));
- }
- }
+ while (it.next()) |e| files.append(cx.arena, .{ e.key_ptr.*, e.value_ptr.* }) catch return error.OutOfMemory;
};
+ for (files.items) |f| {
+ const in_self = std.mem.eql(u8, f[0], self_uri);
+ if (!in_self) foreign = true;
+ for (items(f[1])) |ed| {
+ if (in_self) {
+ // one malformed edit poisons the WHOLE mutating response:
+ // applying the valid remainder would be a partial edit set
+ const span = byteSpan(src, get(ed, "range"), enc) orelse return;
+ const text = str(get(ed, "newText")) orelse return;
+ edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text }) catch return error.OutOfMemory;
+ } else try emitRange(cx, enc, f[0], get(ed, "range"), flat(cx.arena, str(get(ed, "newText")) orelse ""));
+ }
+ }
// Answered for this file alone while other open files say the old
// name: previewed, never applied, each such file named in a row.
@@ -1492,7 +1466,7 @@ fn transportPair(sv: *[2]libc.fd_t) bool {
// number itself, which the child's 3..1024 sweep closes anyway.
setCloexec(sv[1]);
const one: c_int = 1;
- _ = libc.setsockopt(sv[0], libc.SOL.SOCKET, so_nosigpipe, @ptrCast(&one), @sizeOf(c_int));
+ _ = libc.setsockopt(sv[0], libc.SOL.SOCKET, libc.SO.NOSIGPIPE, @ptrCast(&one), @sizeOf(c_int));
}
return true;
}
@@ -1560,6 +1534,8 @@ fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Re
return error.NoServer;
}
if (!exit_hook.swap(true, .acq_rel)) _ = atexit(killAllAtExit);
+ // ponytail: hand-rolled, not std.process.spawn: 0.17's has no setsid
+ // (only setpgid), no signal mask/disposition reset and no fd sweep.
const pid = libc.fork();
if (pid < 0) {
_ = libc.close(sv[0]);
@@ -1572,7 +1548,7 @@ fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Re
// Between fork and exec, in a process with threads: only async-
// signal-safe calls, no allocation, no locks. (Same rule as tty.zig's
// forkShell.)
- _ = setsid(); // Ctrl-C in pardes's terminal is not the server's business
+ _ = libc.setsid(); // Ctrl-C in pardes's terminal is not the server's business
@import("../host_io.zig").resetChildSignals();
_ = libc.dup2(sv[1], 0);
_ = libc.dup2(sv[1], 1);
@@ -1580,7 +1556,7 @@ fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Re
if (devnull >= 0) _ = libc.dup2(devnull, 2);
var fd: c_int = 3;
while (fd < 1024) : (fd += 1) _ = libc.close(fd);
- _ = chdir(root_z.ptr);
+ _ = libc.chdir(root_z.ptr);
var argv: [8:null]?[*:0]const u8 = @splat(null);
argv[0] = exe.ptr;
// args are comptime literals; the buffers live until execv
@@ -1591,7 +1567,7 @@ fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Re
argv[1 + i] = z.ptr;
}
_ = execv(exe.ptr, &argv);
- _exit(127);
+ libc._exit(127);
}
_ = libc.close(sv[1]);
@@ -1937,7 +1913,7 @@ fn reader(io: std.Io, si: usize, g: u32, sock: c_int) void {
const bigger = sa.realloc(buf, buf.len * 2) catch break :outer;
buf = bigger;
}
- var pfd = [_]libc.pollfd{.{ .fd = sock, .events = POLLIN, .revents = 0 }};
+ var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.IN, .revents = 0 }};
const pr = libc.poll(&pfd, 1, 1000);
if (pr < 0) {
if (libc.errno(pr) == .INTR) continue;
@@ -2225,7 +2201,7 @@ fn status(io: std.Io, req: lsp.Req, out: *std.Io.Writer) !void {
const chier = c.caps.call_hier;
const thier = c.caps.type_hier;
c.mu.unlock(io);
- const env_v = if (getenv(s.env)) |v| std.mem.span(v) else null;
+ const env_v = if (libc.getenv(s.env)) |v| std.mem.span(v) else null;
// Never spawned is not off: the first query of its files starts it.
try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) });
if (state == .ready or state == .starting) {
@@ -2270,14 +2246,21 @@ fn app(b: *std.ArrayList(u8), arena: std.mem.Allocator, s: []const u8) Err!void
b.appendSlice(arena, s) catch return error.OutOfMemory;
}
-/// `"textDocument":{"uri":U},"position":{...}` — the params shared by every
-/// position request.
-fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList(u8) {
+/// `"textDocument":{"uri":U}` — the params every request about a file
+/// starts with.
+fn docParams(arena: std.mem.Allocator, uri: []const u8) Err!std.ArrayList(u8) {
var b: std.ArrayList(u8) = .empty;
try app(&b, arena, "\"textDocument\":{\"uri\":");
try jstr(&b, arena, uri);
- b.print(arena, "}},\"position\":{{\"line\":{d},\"character\":{d}}}", .{ pos.line, pos.ch }) catch return error.OutOfMemory;
- // the extra `}` above closed textDocument; nothing to fix up
+ try app(&b, arena, "}");
+ return b;
+}
+
+/// `"textDocument":{"uri":U},"position":{...}` — the params shared by every
+/// position request.
+fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList(u8) {
+ var b = try docParams(arena, uri);
+ b.print(arena, ",\"position\":{{\"line\":{d},\"character\":{d}}}", .{ pos.line, pos.ch }) catch return error.OutOfMemory;
return b;
}
@@ -2353,7 +2336,7 @@ fn sockWrite(io: ?std.Io, sock: c_int, bytes: []const u8, deadline: i64, started
if (deadline - nowMs() <= 0) return error.Timeout;
if (io) |cancel_io| cancel_io.checkCancel() catch return error.Canceled;
} else if (nowMs() - deadline > wedge_ms) return error.Dead;
- var pfd = [_]libc.pollfd{.{ .fd = sock, .events = POLLOUT, .revents = 0 }};
+ var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.OUT, .revents = 0 }};
const pr = libc.poll(&pfd, 1, 500);
if (pr < 0) {
if (libc.errno(pr) == .INTR) continue;
@@ -2387,17 +2370,17 @@ fn nowUs() u64 {
/// The spec's binary: the env override when set, else `bin`, PATH-searched
/// unless it names a path.
fn binOf(spec: *const Spec, buf: *[4096:0]u8) ?[:0]const u8 {
- const name = if (getenv(spec.env)) |v| std.mem.span(v) else spec.bin;
+ const name = if (libc.getenv(spec.env)) |v| std.mem.span(v) else spec.bin;
if (name.len == 0) return null;
if (std.mem.indexOfScalar(u8, name, '/') != null) {
const z = std.fmt.bufPrintSentinel(buf, "{s}", .{name}, 0) catch return null;
- return if (access(z.ptr, X_OK) == 0) z else null;
+ return if (libc.access(z.ptr, libc.X_OK) == 0) z else null;
}
- const path = if (getenv("PATH")) |p| std.mem.span(p) else "/usr/local/bin:/usr/bin:/bin";
+ const path = if (libc.getenv("PATH")) |p| std.mem.span(p) else "/usr/local/bin:/usr/bin:/bin";
var it = std.mem.tokenizeScalar(u8, path, ':');
while (it.next()) |dir| {
const cand = std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch continue;
- if (access(cand.ptr, X_OK) == 0) return cand;
+ if (libc.access(cand.ptr, libc.X_OK) == 0) return cand;
}
return null;
}
@@ -2415,14 +2398,14 @@ fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 {
while (true) {
for (markers) |marker| {
const p = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d, marker }, 0) catch continue;
- if (access(p.ptr, 0) == 0) {
+ if (libc.access(p.ptr, libc.F_OK) == 0) {
top_marker = d;
break;
}
}
if (git == null) {
if (std.fmt.bufPrintSentinel(&buf, "{s}/.git", .{d}, 0)) |p| {
- if (access(p.ptr, 0) == 0) git = d;
+ if (libc.access(p.ptr, libc.F_OK) == 0) git = d;
} else |_| {}
}
d = std.fs.path.dirname(d) orelse break;
@@ -2795,7 +2778,7 @@ test "rootOf takes the top-most marker and falls back to git then dir" {
var pb: [128:0]u8 = undefined;
for ([_][]const u8{ "/ws", "/ws/member", "/ws/member/src" }) |d| {
const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, d }, 0);
- try std.testing.expect(mkdir(z.ptr, 0o700) == 0);
+ try std.testing.expect(libc.mkdir(z.ptr, 0o700) == 0);
}
for ([_][]const u8{ "/ws/Cargo.toml", "/ws/member/Cargo.toml" }) |f| {
const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, f }, 0);
@@ -2816,7 +2799,7 @@ test "specFor routes extensions and honours the disable env" {
try std.testing.expect(specFor("/x/main.rs") != null);
try std.testing.expect(specFor("/x/README.md") == null);
try std.testing.expectEqualStrings("rust-analyzer", specs[specFor("/x/main.rs").?].name);
- if (getenv("PARDES_LSP_ZIG") == null) try std.testing.expectEqualStrings("zls", specs[specFor("/x/main.zig").?].name);
+ if (libc.getenv("PARDES_LSP_ZIG") == null) try std.testing.expectEqualStrings("zls", specs[specFor("/x/main.zig").?].name);
}
test "the transport this host actually gives us is a pair, and both ends are close-on-exec" {
@@ -2894,7 +2877,7 @@ test "Lspinfo before any query says a server is not started yet, not off" {
}
test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" {
- if (getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest;
+ if (libc.getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest;
const io = std.testing.io;
const si = specFor("/x/a.zig").?;
const c = &conns[si];
@@ -2923,7 +2906,7 @@ test "reaping a server takes what it started with it: its process group goes, it
const pid = libc.fork();
if (pid < 0) return error.SkipZigTest;
if (pid == 0) {
- _ = setsid();
+ _ = libc.setsid();
const child = libc.fork();
if (child == 0) {
while (true) _ = usleep(100_000);