diff options
Diffstat (limited to 'src/lsp')
| -rw-r--r-- | src/lsp/Ask.zig | 44 | ||||
| -rw-r--r-- | src/lsp/Scip.zig | 4 | ||||
| -rw-r--r-- | src/lsp/lsp_client.zig | 304 |
3 files changed, 173 insertions, 179 deletions
diff --git a/src/lsp/Ask.zig b/src/lsp/Ask.zig index 8ed0aecc..76c32f2d 100644 --- a/src/lsp/Ask.zig +++ b/src/lsp/Ask.zig @@ -45,22 +45,22 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) // file, place and argument -- from wherever it is run. const last_pane: ?usize = if (kind == .explain) (if (p.lsp_ask.last) |last| p.paneBySerial(last.serial) else null) else null; const id = last_pane orelse asked; - var said: [128]u8 = undefined; + var said: [160]u8 = undefined; if (!lsp.supports.contains(kind)) - return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no language server here answers it", .{lspWord(kind)}) catch "no language server answers it"); + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no language server here answers it", .{lspWord(kind)}) catch unreachable); // a word and 45 fit 160 const pane = p.panes[id] orelse return; if (kind != .status) { const f = pane.file orelse - return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks"); + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch unreachable); // a word and 45 fit 160 if (f.output != null) - return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks"); + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch unreachable); // a word and 45 fit 160 } - if (arg.len > 128) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: its argument is at most 128 bytes", .{lspWord(kind)}) catch "argument too long"); + if (arg.len > 128) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: its argument is at most 128 bytes", .{lspWord(kind)}) catch unreachable); // a word and 45 fit 160 if (kind == .rename) { const zig_buf = if (pane.file) |f| std.mem.endsWith(u8, f.path, ".zig") else true; if ((zig_buf and (!std.zig.isValidId(arg) or std.zig.isUnderscore(arg))) or (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) - return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name"); + return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch unreachable); // arg is 128 at most } var off = if (pane.file) |f| modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), @@ -83,7 +83,7 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) } } off = nearest orelse - return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no {s} in this file", .{ lspWord(kind), arg }) catch "no such symbol in this file"); + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no {s} in this file", .{ lspWord(kind), arg }) catch unreachable); // a word, 128 and 18 fit 160 arg = ""; } // Lspwhy asks the last query again, narrated: its kind and argument, @@ -93,7 +93,7 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) var at = off; if (kind == .explain) { if (p.lsp_ask.last) |last| { - sent = std.fmt.bufPrint(&explained, "{s} {s}", .{ @tagName(last.kind), last.arg.slice() }) catch ""; + sent = std.fmt.bufPrint(&explained, "{s} {s}", .{ @tagName(last.kind), last.arg.slice() }) catch unreachable; // a kind's name and 128 fit 160 if (last_pane != null) at = last.offset; } } else if (kind != .status) p.lsp_ask.last = .{ .kind = kind, .arg = .from(arg), .serial = pane.serial, .offset = @intCast(off) }; @@ -135,12 +135,10 @@ fn parseLspEdits(p: *Pardes, bytes: []const u8, fallback: ?[]const u8) ?[]LspEdi } var fields = std.mem.tokenizeScalar(u8, line, ' '); const head = fields.next() orelse return null; - const want: @TypeOf(form) = if (std.mem.eql(u8, head, "@put")) - .put - else if (std.mem.eql(u8, head, "@edit")) - .edit - else - return null; + const want: @TypeOf(form) = switch (std.meta.stringToEnum(enum { @"@put", @"@edit" }, head) orelse return null) { + .@"@put" => .put, + .@"@edit" => .edit, + }; if (form == .undecided) form = want; if (form != want) return null; const start = std.fmt.parseInt(usize, fields.next() orelse return null, 10) catch return null; @@ -277,11 +275,11 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { defer if (p.fs.failures != failures) p.noteLateFailure(w.pane); var said: [256]u8 = undefined; const rows = response orelse - return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: the language server did not answer", .{lspWord(w.kind)}) catch "no answer"); + return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: the language server did not answer", .{lspWord(w.kind)}) catch unreachable); // short // A backend that cannot answer it says why (`@none <why>`). if (std.mem.startsWith(u8, rows, "@none ")) { const why = std.mem.trimEnd(u8, rows["@none ".len..], "\n"); - return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), why[0..@min(why.len, 200)] }) catch "no answer"); + return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), why[0..@min(why.len, 200)] }) catch unreachable); // 200 fit 256 } // Index's answer is its indexer's command line, run in a command // pane (lsp_client.indexCommand). @@ -295,7 +293,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { if (applyLspEdits(p, pane, w.revision, edits)) { var buf: [64]u8 = undefined; const verb: []const u8 = if (w.kind == .rename) "renamed" else "formatted"; - p.setMessage(w.pane, std.fmt.bufPrint(&buf, "{s} {d} range(s)", .{ verb, edits.len }) catch verb); + p.setMessage(w.pane, std.fmt.bufPrint(&buf, "{s} {d} range(s)", .{ verb, edits.len }) catch unreachable); // short } return; } @@ -313,13 +311,13 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { const none: ?[]const u8 = switch (w.kind) { .completion, .format => null, .rename => "nothing here to rename", - .diagnostics, .workspace_diagnostics => return p.setMessage(w.pane, std.fmt.bufPrint(&said, "{s}: none", .{lspWord(w.kind)}) catch "none"), + .diagnostics, .workspace_diagnostics => return p.setMessage(w.pane, std.fmt.bufPrint(&said, "{s}: none", .{lspWord(w.kind)}) catch unreachable), // short .incoming_calls => "callers not found", .outgoing_calls => "callees not found", .hover => "nothing to show: not found", else => "not found", }; - if (none) |text| p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), text }) catch "nothing found"); + if (none) |text| p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), text }) catch unreachable); // short literals return; } @@ -350,7 +348,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { }; if (listing and !p.look_missed) { var where: [300]u8 = undefined; - p.setMessage(v.active, std.fmt.bufPrint(&where, "{s}: the one, {s}", .{ lspWord(w.kind), place[0..@min(place.len, 240)] }) catch lspWord(w.kind)); + p.setMessage(v.active, std.fmt.bufPrint(&where, "{s}: the one, {s}", .{ lspWord(w.kind), place[0..@min(place.len, 240)] }) catch unreachable); // 240 fit 300 } return; } @@ -371,7 +369,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { return; }; const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); - const content = p.gpa.dupe(u8, rows) catch return; + const content = p.gpa.dupe(u8, rows) catch |err| return p.reportError(w.pane, lspWord(w.kind), err); const serial_before = p.next_serial; p.fs.refilled = null; panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| { @@ -401,9 +399,9 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { // renameEdits) are no edits. const unrenamed = std.mem.count(u8, rows, ", which the server did not rename\n"); p.setMessage(w.pane, if (unrenamed > 0) - std.fmt.bufPrint(&said_buf, "Rename: previewed, not applied: the server renamed in this file only, and {d} other open file(s) say the name", .{unrenamed}) catch "Rename: previewed" + std.fmt.bufPrint(&said_buf, "Rename: previewed, not applied: the server renamed in this file only, and {d} other open file(s) say the name", .{unrenamed}) catch unreachable // 126 at most else - std.fmt.bufPrint(&said_buf, "Rename: {d} edit(s) across files, previewed, not applied", .{nrows}) catch "Rename: previewed"); + std.fmt.bufPrint(&said_buf, "Rename: {d} edit(s) across files, previewed, not applied", .{nrows}) catch unreachable); // short } if (panes.Output.traits(from).jumps) { const result = p.panes[pane.search_pane orelse return] orelse return; diff --git a/src/lsp/Scip.zig b/src/lsp/Scip.zig index 8deffe26..3d3cc648 100644 --- a/src/lsp/Scip.zig +++ b/src/lsp/Scip.zig @@ -67,7 +67,7 @@ pub const Index = struct { } pub fn root(ix: *const Index) []const u8 { - return std.fs.path.dirname(ix.path()) orelse "/"; + return std.Io.Dir.path.dirname(ix.path()) orelse "/"; } /// The document of the file at `abs`, or null. @@ -217,7 +217,7 @@ pub fn find(io: std.Io, dir: []const u8) Error!?*Index { for (0..8) |_| { const p = std.fmt.bufPrint(&buf, "{s}/index.scip", .{if (std.mem.eql(u8, d, "/")) "" else d}) catch return null; if (statPath(io, p, .{})) |st| return try use(io, p, st) else |_| {} - d = std.fs.path.dirname(d) orelse return null; + d = std.Io.Dir.path.dirname(d) orelse return null; } return null; } diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index 928d5475..ef531f30 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -356,7 +356,9 @@ const Chat = enum { fn post(si: usize, chat: Chat, comptime fmt: []const u8, args: anytype) void { var buf: [192]u8 = undefined; - const text = std.fmt.bufPrint(&buf, fmt, args) catch return; + var w: std.Io.Writer = .fixed(&buf); + w.print(fmt, args) catch {}; // a long one is cut at the row's end + const text = w.buffered(); while (!sink_mu.tryLock()) std.atomic.spinLoopHint(); defer sink_mu.unlock(); const cb = sink_cb orelse return; @@ -400,7 +402,7 @@ fn record(si: usize, req: lsp.Req, us: u64, rows: usize, err: []const u8) void { defer log_mu.unlock(); const e = &log_buf[log_next]; e.* = .{ .used = true, .kind = req.kind, .spec = @intCast(si), .us = us, .rows = rows }; - const base = std.fs.path.basename(req.path); + const base = std.Io.Dir.path.basename(req.path); e.file_len = @intCast(@min(base.len, e.file.len)); @memcpy(e.file[0..e.file_len], base[0..e.file_len]); e.err_len = @intCast(@min(err.len, e.err.len)); @@ -435,7 +437,7 @@ const Trace = struct { // ------------------------------------------------------------------- query -pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) !void { +pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) Err!void { const req = lsp.explaining(asked); if (req.kind == .status) return status(io, req.path, out); if (req.kind == .index) return indexCommand(req, out); @@ -462,14 +464,14 @@ pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io. tr.note("STOP: no language server spec matches {s}", .{ if (req.path.len == 0) "a pane with no file" else req.path, }); - if (req.kind != .explain) return lsp.none(out, "no language server for {s}", .{if (req.path.len == 0) "a pane with no file" else std.fs.path.basename(req.path)}); + if (req.kind != .explain) return lsp.none(out, "no language server for {s}", .{if (req.path.len == 0) "a pane with no file" else std.Io.Dir.path.basename(req.path)}); return traceOut(&tr, req, out, 0, 0); }; - tr.note("file {s} -> {s} (languageId {s})", .{ std.fs.path.basename(req.path), specs[si].name, specs[si].lang }); + tr.note("file {s} -> {s} (languageId {s})", .{ std.Io.Dir.path.basename(req.path), specs[si].name, specs[si].lang }); const t1 = nowUs(); var err_name: []const u8 = ""; - var failure: ?anyerror = null; + var failure: ?Err = null; answer(io, arena, si, req, &scratch, &tr) catch |e| { failure = e; err_name = @errorName(e); @@ -481,7 +483,7 @@ pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io. if (req.kind == .explain) return traceOut(&tr, req, out, rows, us); // No server to start for the language: said, not "did not answer". - if (failure) |err| if (err == error.NoServer) return lsp.none(out, "language server for {s} not found", .{std.fs.path.extension(req.path)}); + if (failure) |err| if (err == error.NoServer) return lsp.none(out, "language server for {s} not found", .{std.Io.Dir.path.extension(req.path)}); // Installed, but it failed a moment ago: said so, and when it is tried // again, not that it is not there. if (failure) |err| if (err == error.Backoff) { @@ -498,7 +500,7 @@ pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io. fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us: u64) std.Io.Writer.Error!void { if (req.kind != .explain) return; try out.print("lsp explain — the {s} query at byte {d} of {s}\n\n", .{ - @tagName(req.explains), req.offset, if (req.path.len == 0) "(no file)" else std.fs.path.basename(req.path), + @tagName(req.explains), req.offset, if (req.path.len == 0) "(no file)" else std.Io.Dir.path.basename(req.path), }); try out.writeAll(tr.buf[0..tr.len]); if (hideTime()) @@ -578,11 +580,11 @@ fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, var other: std.ArrayList(u8) = .empty; try uriOf(&other, arena, doc.path); try syncDoc(c, io, si, arena, other.items, doc.source); - tr.note("synced {s} first", .{std.fs.path.basename(doc.path)}); + tr.note("synced {s} first", .{std.Io.Dir.path.basename(doc.path)}); }; const pos = posOf(req.source, req.offset, c.caps.enc); - var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack }; + var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack }; for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source }); tr.note("server {s} (pid {d}), root {s}, {s} columns", .{ @tagName(c.state), c.pid, c.root, @tagName(c.caps.enc), @@ -653,7 +655,7 @@ fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, var also: std.ArrayList([]const u8) = .empty; const old = identAt(req.source, req.offset); if (old.len > 0) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path) and holdsWord(doc.source, old)) - also.append(arena, doc.path) catch {}; + try also.append(arena, doc.path); try renameEdits(&cx, c.caps.enc, uri.items, result, req.source, old, also.items); }, .format => { @@ -1167,7 +1169,7 @@ fn collectCallers(src: Calls, arena: std.mem.Allocator, focus: CallTree.Call, ho // ponytail: substring heuristic, "latest.zig" or "contest" count as tests too fn testCaller(caller: CallTree.Call) bool { return std.ascii.findIgnoreCase(caller.name, "test") != null or - std.ascii.findIgnoreCase(std.fs.path.basenamePosix(caller.uri), "test") != null; + std.ascii.findIgnoreCase(std.Io.Dir.path.basenamePosix(caller.uri), "test") != null; } fn callerLess(tree: *const CallTree, a: usize, b: usize) bool { @@ -1311,7 +1313,7 @@ fn fromIndex(io: std.Io, arena: std.mem.Allocator, req: lsp.Req, kind: lsp.Kind, tr.note("unsaved changes the index has not seen: the server", .{}); return false; } - const dir = std.fs.path.dirname(req.path) orelse return false; + const dir = std.Io.Dir.path.dirname(req.path) orelse return false; const ix = (Scip.find(io, dir) catch |e| { tr.note("index.scip above {s}: {s}", .{ dir, @errorName(e) }); return false; @@ -1320,17 +1322,17 @@ fn fromIndex(io: std.Io, arena: std.mem.Allocator, req: lsp.Req, kind: lsp.Kind, return false; }; const doc = ix.document(req.path) orelse { - tr.note("{s} holds no {s}", .{ ix.path(), std.fs.path.basename(req.path) }); + tr.note("{s} holds no {s}", .{ ix.path(), std.Io.Dir.path.basename(req.path) }); return false; }; const si = specFor(req.path) orelse 0; if (ix.stale(io, req.path)) { - tr.note("stale: {s} is newer than the index", .{std.fs.path.basename(req.path)}); - if (!ix.stale_said) post(si, .always, "{s} is older than {s}: Index makes it again", .{ ix.path(), std.fs.path.basename(req.path) }); + tr.note("stale: {s} is newer than the index", .{std.Io.Dir.path.basename(req.path)}); + if (!ix.stale_said) post(si, .always, "{s} is older than {s}: Index makes it again", .{ ix.path(), std.Io.Dir.path.basename(req.path) }); ix.stale_said = true; } const enc = ix.documents[doc].enc; - var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = kind == .callstack }; + var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = kind == .callstack }; for (req.others) |d| try cx.files.append(arena, .{ .path = d.path, .text = d.source }); if (kind == .document_symbols or kind == .workspace_symbols) { for (ix.occurrences, 0..) |o, i| { @@ -1467,10 +1469,10 @@ fn indexUri(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u /// project's root, where the index it writes answers for every file under /// it (`PARDES_SCIP_RS` and the like name another indexer). fn indexCommand(req: lsp.Req, out: *std.Io.Writer) !void { - const si = specFor(req.path) orelse return lsp.none(out, "no indexer for {s}", .{std.fs.path.basename(req.path)}); + const si = specFor(req.path) orelse return lsp.none(out, "no indexer for {s}", .{std.Io.Dir.path.basename(req.path)}); const cmd = if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer; try out.writeAll("@run cd '"); - for (rootOf(std.fs.path.dirname(req.path) orelse "/", specs[si].markers)) |ch| try if (ch == '\'') out.writeAll("'\\''") else out.writeByte(ch); + for (rootOf(std.Io.Dir.path.dirname(req.path) orelse "/", specs[si].markers)) |ch| try if (ch == '\'') out.writeAll("'\\''") else out.writeByte(ch); try out.print("' && {s}\n", .{cmd}); } @@ -1480,6 +1482,7 @@ fn indexCommand(req: lsp.Req, out: *std.Io.Writer) !void { /// of files reads each once, not once per row. The current buffer never needs /// reading: `req.source` IS its text, unsaved edits included. const Cx = struct { + io: std.Io, arena: std.mem.Allocator, base: []const u8, cur_path: []const u8, @@ -1497,22 +1500,16 @@ const Cx = struct { if (std.mem.eql(u8, path, cx.cur_path)) return cx.cur_src; for (cx.files.items) |f| if (std.mem.eql(u8, f.path, path)) return f.text; if (cx.files.items.len >= 32) return null; - var pathbuf: [4096]u8 = undefined; - const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return null; - const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY }); - if (fd < 0) return null; - defer _ = libc.close(fd); - var buf: std.ArrayList(u8) = .empty; + const file = std.Io.Dir.cwd().openFile(cx.io, path, .{}) catch return null; + defer file.close(cx.io); var chunk: [64 * 1024]u8 = undefined; - while (buf.items.len < max_doc_bytes) { - const n = libc.read(fd, &chunk, chunk.len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - return null; - } - if (n == 0) break; - buf.appendSlice(cx.arena, chunk[0..@intCast(n)]) catch return null; - } + var file_reader = file.reader(cx.io, &chunk); + var buf: std.ArrayList(u8) = .empty; + // A file past max_doc_bytes is its first max_doc_bytes. + file_reader.interface.appendRemaining(cx.arena, &buf, .limited(max_doc_bytes)) catch |err| switch (err) { + error.StreamTooLong => {}, + else => return null, + }; cx.files.append(cx.arena, .{ .path = path, .text = buf.items }) catch return null; return buf.items; } @@ -1553,7 +1550,7 @@ fn emitPath(cx: *Cx, enc: Enc, path: []const u8, r: Range, note: []const u8) Err const col = colBytes(lntext, r.sc, enc); const shown = if (cx.relative_parents) blk: { - const relative = std.fs.path.relativePosix(cx.arena, "/", cx.base, path) catch break :blk path; + const relative = std.Io.Dir.path.relativePosix(cx.arena, "/", cx.base, path) catch break :blk path; break :blk if (relative.len < path.len) relative else path; } else lsp.rel(cx.base, path); // A same-line exclusive end byte offset is also the displayed inclusive @@ -2259,124 +2256,123 @@ fn serverRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, sock: c_int, me } fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { - if (std.mem.eql(u8, method, "textDocument/publishDiagnostics")) { - const uri = str(get(params, "uri")) orelse return; - // keep the raw MESSAGE (params included); re-parsing it per query - // beats owning a parsed tree past this arena's life - const body = sa.dupe(u8, raw) catch return; - c.mu.lockUncancelable(io); - defer c.mu.unlock(io); - if (c.gen != g) { - sa.free(body); - return; - } - for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { - d.stale = false; - break; - }; - var slot: ?*DiagSet = null; - for (c.diags.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { - slot = d; - break; - }; - // Bounded in files and bytes: a new set that does not fit pushes - // out the oldest files' (the server sends a file's again when it - // changes); one bigger than the whole store is not kept. - if (body.len > max_diag_bytes) { - sa.free(body); - return; - } - if (slot) |d| { - c.diag_bytes -= d.body.len; - sa.free(d.body); - d.body = body; - c.diag_bytes += body.len; - } else { - while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) { - const old = c.diags.orderedRemove(0); - c.diag_bytes -= old.body.len; - sa.free(old.uri); - sa.free(old.body); - } - const owned = sa.dupe(u8, uri) catch { + const Method = enum { @"textDocument/publishDiagnostics", @"$/progress", @"window/showMessage", @"experimental/serverStatus" }; + switch (std.meta.stringToEnum(Method, method) orelse return) { + .@"textDocument/publishDiagnostics" => { + const uri = str(get(params, "uri")) orelse return; + // keep the raw MESSAGE (params included); re-parsing it per query + // beats owning a parsed tree past this arena's life + const body = sa.dupe(u8, raw) catch return; + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); + if (c.gen != g) { sa.free(body); return; + } + for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { + d.stale = false; + break; + }; + var slot: ?*DiagSet = null; + for (c.diags.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { + slot = d; + break; }; - c.diags.append(sa, .{ .uri = owned, .body = body }) catch { - sa.free(owned); + // Bounded in files and bytes: a new set that does not fit pushes + // out the oldest files' (the server sends a file's again when it + // changes); one bigger than the whole store is not kept. + if (body.len > max_diag_bytes) { sa.free(body); return; - }; - c.diag_bytes += body.len; - } - c.cond.broadcast(io); // waitFresh watches this - return; - } - if (std.mem.eql(u8, method, "$/progress")) { - const value = get(params, "value") orelse return; - const pkind = str(get(value, "kind")) orelse return; - const msg = str(get(value, "message")) orelse ""; - c.mu.lockUncancelable(io); - if (c.gen != g) { - c.mu.unlock(io); - return; - } - if (std.mem.eql(u8, pkind, "begin")) { - c.progress += 1; - const title = str(get(value, "title")) orelse ""; - c.title_len = @intCast(@min(title.len, c.title.len)); - @memcpy(c.title[0..c.title_len], title[0..c.title_len]); - var tbuf: [48]u8 = undefined; - const t = tbuf[0..c.title_len]; - @memcpy(t, c.title[0..c.title_len]); + } + if (slot) |d| { + c.diag_bytes -= d.body.len; + sa.free(d.body); + d.body = body; + c.diag_bytes += body.len; + } else { + while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) { + const old = c.diags.orderedRemove(0); + c.diag_bytes -= old.body.len; + sa.free(old.uri); + sa.free(old.body); + } + const owned = sa.dupe(u8, uri) catch { + sa.free(body); + return; + }; + c.diags.append(sa, .{ .uri = owned, .body = body }) catch { + sa.free(owned); + sa.free(body); + return; + }; + c.diag_bytes += body.len; + } + c.cond.broadcast(io); // waitFresh watches this + }, + .@"$/progress" => { + const value = get(params, "value") orelse return; + const pkind = str(get(value, "kind")) orelse return; + const msg = str(get(value, "message")) orelse ""; + c.mu.lockUncancelable(io); + if (c.gen != g) { + c.mu.unlock(io); + return; + } + if (std.mem.eql(u8, pkind, "begin")) { + c.progress += 1; + const title = str(get(value, "title")) orelse ""; + c.title_len = @intCast(@min(title.len, c.title.len)); + @memcpy(c.title[0..c.title_len], title[0..c.title_len]); + var tbuf: [48]u8 = undefined; + const t = tbuf[0..c.title_len]; + @memcpy(t, c.title[0..c.title_len]); + c.mu.unlock(io); + post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg }); + return; + } + if (std.mem.eql(u8, pkind, "report")) { + var tbuf: [48]u8 = undefined; + const t = tbuf[0..c.title_len]; + @memcpy(t, c.title[0..c.title_len]); + const pct = num(get(value, "percentage")); + c.mu.unlock(io); + if (pct) |p| + post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg }) + else + post(si, .chatty, "{s}: {s} {s}", .{ specs[si].name, t, msg }); + return; + } + // end + c.progress -= 1; + const idle = c.progress <= 0; + if (idle) c.progress = 0; c.mu.unlock(io); - post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg }); - return; - } - if (std.mem.eql(u8, pkind, "report")) { - var tbuf: [48]u8 = undefined; - const t = tbuf[0..c.title_len]; - @memcpy(t, c.title[0..c.title_len]); - const pct = num(get(value, "percentage")); + // the setpoint every burst of progress ends on; `.always` + the + // dedupe above means it lands exactly once however the reports raced + if (idle) post(si, .always, "{s}: ready", .{specs[si].name}); + }, + .@"window/showMessage" => { + const t = num(get(params, "type")) orelse 3; + if (t > 2) return; // info/log are the server's diary, not the user's + post(si, .always, "{s}: {s}", .{ specs[si].name, str(get(params, "message")) orelse "" }); + }, + // rust-analyzer's precise quiescence signal, opted into via + // experimental.serverStatusNotification + .@"experimental/serverStatus" => { + const health = str(get(params, "health")) orelse "ok"; + const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false; + c.mu.lockUncancelable(io); + if (c.gen == g) { + c.loading = !quiescent; + c.cond.broadcast(io); + } c.mu.unlock(io); - if (pct) |p| - post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg }) - else - post(si, .chatty, "{s}: {s} {s}", .{ specs[si].name, t, msg }); - return; - } - // end - c.progress -= 1; - const idle = c.progress <= 0; - if (idle) c.progress = 0; - c.mu.unlock(io); - // the setpoint every burst of progress ends on; `.always` + the - // dedupe above means it lands exactly once however the reports raced - if (idle) post(si, .always, "{s}: ready", .{specs[si].name}); - return; - } - if (std.mem.eql(u8, method, "window/showMessage")) { - const t = num(get(params, "type")) orelse 3; - if (t > 2) return; // info/log are the server's diary, not the user's - post(si, .always, "{s}: {s}", .{ specs[si].name, str(get(params, "message")) orelse "" }); - return; - } - // rust-analyzer's precise quiescence signal, opted into via - // experimental.serverStatusNotification - if (std.mem.eql(u8, method, "experimental/serverStatus")) { - const health = str(get(params, "health")) orelse "ok"; - const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false; - c.mu.lockUncancelable(io); - if (c.gen == g) { - c.loading = !quiescent; - c.cond.broadcast(io); - } - c.mu.unlock(io); - if (!std.mem.eql(u8, health, "ok")) - post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" }) - else if (quiescent) - post(si, .always, "{s}: ready", .{specs[si].name}); - return; + if (!std.mem.eql(u8, health, "ok")) + post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" }) + else if (quiescent) + post(si, .always, "{s}: ready", .{specs[si].name}); + }, } } @@ -2384,7 +2380,7 @@ fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method fn status(io: std.Io, path: []const u8, out: *std.Io.Writer) !void { // The index the file would ask first, what it holds and how old it is. - const dir = std.fs.path.dirname(path) orelse "/"; + const dir = std.Io.Dir.path.dirname(path) orelse "/"; if (Scip.find(io, dir)) |found| if (found) |ix| { var symbols: usize = 0; for (ix.infos.items) |info| symbols += @intFromBool(info.len > 0); @@ -2505,7 +2501,7 @@ fn frame(c: *Conn, io: std.Io, sock: c_int, body: []const u8, deadline: i64) Err /// dropped, and the server's request goes unanswered). fn answerServer(c: *Conn, io: std.Io, sock: c_int, body: []const u8) void { var hdr: [64]u8 = undefined; - const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return; + const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch unreachable; // a usize and 20 fit 64 c.replies_mu.lockUncancelable(io); const half = &c.replies[c.filling]; const len = &c.replies_len[c.filling]; @@ -2623,7 +2619,7 @@ fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 { if (libc.access(p.ptr, libc.F_OK) == 0) git = d; } else |_| {} } - d = std.fs.path.dirname(d) orelse break; + d = std.Io.Dir.path.dirname(d) orelse break; if (d.len <= 1) break; } return top_marker orelse git orelse dir; @@ -2797,7 +2793,7 @@ test "caller trees reverse incoming paths and merge shared callers and sites" { for (page.ranges.items) |site| try std.testing.expect(!site.focus); for (page.children.items) |id| try std.testing.expect(tree.nodes.items[id].ranges.items[0].focus); var out: std.Io.Writer.Allocating = .init(arena); - var cx: Cx = .{ .arena = arena, .base = "/", .cur_path = "/test.c", .cur_src = "main_call();\npage_left();\npage_right();\nleft_call();\nright_call();\n", .out = &out.writer }; + var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/", .cur_path = "/test.c", .cur_src = "main_call();\npage_left();\npage_right();\nleft_call();\nright_call();\n", .out = &out.writer }; try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0); const text = out.written(); try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, lsp.callstack_match)); @@ -2850,7 +2846,7 @@ test "callstack cross-crate paths remain resolvable without absolute path clutte \\{"start":{"line":1,"character":3},"end":{"line":1,"character":6}} , .{}); var out: std.Io.Writer.Allocating = .init(arena); - var cx: Cx = .{ .arena = arena, .base = "/workspace/merkle-tree/src", .cur_path = "", .cur_src = "", .out = &out.writer, .relative_parents = true }; + var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/workspace/merkle-tree/src", .cur_path = "", .cur_src = "", .out = &out.writer, .relative_parents = true }; try emitRange(&cx, .utf8, "file:///workspace/entry/src/entry.rs", range, "fn run()"); try std.testing.expectEqualStrings("../../entry/src/entry.rs:2:4-6 fn run()\n", out.written()); } @@ -2869,7 +2865,7 @@ test "LSP client rename and format propagate incomplete edit encoding" { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); var out: std.Io.Writer = .fixed(buffer[0..capacity]); - var cx: Cx = .{ .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = "abc xyz", .out = &out }; + var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = "abc xyz", .out = &out }; const result = if (rename) renameEdits(&cx, .utf8, uri, parsed.value, cx.cur_src, "abc", &.{}) else @@ -2894,7 +2890,7 @@ test "a rename answered for this file alone, while another open file says the ol defer arena.deinit(); var buffer: [512]u8 = undefined; var out: std.Io.Writer = .fixed(&buffer); - var cx: Cx = .{ .arena = arena.allocator(), .base = "/w", .cur_path = "/w/util.zig", .cur_src = "pub fn add() void {}", .out = &out }; + var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/w", .cur_path = "/w/util.zig", .cur_src = "pub fn add() void {}", .out = &out }; try renameEdits(&cx, .utf8, "file:///w/util.zig", parsed.value, cx.cur_src, "add", &.{"/w/main.zig"}); try std.testing.expectEqualStrings("util.zig:1:8-10 sum\nmain.zig: also says add, which the server did not rename\n", out.buffered()); try std.testing.expectEqualStrings("add", identAt("x = add(1);", 6)); @@ -3050,7 +3046,7 @@ test "LSP source snippets preserve indentation with UTF16 byte ranges and prose for ([_]bool{ false, true }) |prose| { var buffer: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buffer); - var cx: Cx = .{ .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = source, .out = &out }; + var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = source, .out = &out }; try emitRange(&cx, .utf16, "file:///file.c", parsed.value, if (prose) " explanatory label \t" else ""); const expected = try std.fmt.allocPrint(arena.allocator(), "file.c:1:17{s} {s}\n", .{ if (multiline) "" else "-22", |
