const std = @import("std"); const pardes = @import("core"); const filesystem = @import("core").filesystem; pub const Request = struct { id: u32, kind: pardes.lsp.Kind, pane: pardes.Pane.Id, offset: u32, arg: []const u8, }; pub const Task = struct { id: u32, future: std.Io.Future(void), }; /// One language query, owned by the worker that runs it. pub const Job = struct { callstack_depth: u8 = pardes.lsp.callstack_default_depth, dirty: bool = false, id: u32, kind: pardes.lsp.Kind, offset: u32, path: []u8, source: [:0]u8, arg: []u8, root: []u8, /// The other open files, for a query that can reach them. others: []pardes.lsp.Doc = &.{}, pub fn free(job: *Job, gpa: std.mem.Allocator) void { gpa.free(job.path); gpa.free(job.source); gpa.free(job.arg); gpa.free(job.root); for (job.others) |doc| { gpa.free(doc.path); gpa.free(doc.source); } gpa.free(job.others); gpa.destroy(job); } }; /// A pane's file's text, `0`-ended, owned. fn fileSource(gpa: std.mem.Allocator, f: ?*const pardes.panes.File.State) ![:0]u8 { const file = f orelse return gpa.dupeSentinel(u8, "", 0); const text = try pardes.panes.File.fileText(file, gpa); defer if (text.ptr != file.content.ptr) gpa.free(text); return gpa.dupeSentinel(u8, text, 0); } // Copy before starting a worker; the editor may replace any source slice afterward. pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request) !*Job { if (req.pane.index() >= core.panes.len) return error.NoPane; const pane = core.panes[req.pane.index()] orelse return error.NoPane; const file = pane.file; const job = try gpa.create(Job); errdefer gpa.destroy(job); const declared_path = if (file) |f| f.path else ""; const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path); errdefer gpa.free(path); // The file's text (File.fileText: the `Changes` layer's lines are none // of it), as every position sent with it is. const source = try fileSource(gpa, if (file) |*f| f else null); errdefer gpa.free(source); const arg = try gpa.dupe(u8, req.arg); errdefer gpa.free(arg); const declared_root = if (file) |f| pardes.panes.Dir.ofName(f.path) else pane.cwdSlice(); const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root); errdefer gpa.free(root); job.* = .{ .callstack_depth = core.settings.callstack_depth, .dirty = pardes.tagline.dirty(pane), .id = req.id, .kind = req.kind, .offset = req.offset, .path = path, .source = source, .arg = arg, .root = root, }; // ponytail: a copy of every open file per such query; a server // already told of one is sent nothing more (syncDoc). // Lspwhy too: the query it explains may be one of those, and its // trace shows each file synced first. if (pardes.lsp.reachesOtherFiles(req.kind) or req.kind == .explain) { var others: std.ArrayList(pardes.lsp.Doc) = .empty; errdefer { for (others.items) |doc| { gpa.free(doc.path); gpa.free(doc.source); } others.deinit(gpa); } var copied: usize = 0; for (core.panes, 0..) |slot, i| { const other = slot orelse continue; if (i == req.pane.index()) continue; const f = other.file orelse continue; if (f.output != null) continue; if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue; copied += f.content.len; const local = filesystem.localPath(f.path) orelse continue; const other_path = try gpa.dupe(u8, local); const other_source = fileSource(gpa, &f) catch |err| { gpa.free(other_path); return err; }; try others.append(gpa, .{ .path = other_path, .source = other_source }); } job.others = try others.toOwnedSlice(gpa); } return job; } // Null is failure; the receiver frees non-null rows with the job's allocator. pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void; /// Start `req` on a worker that hands its rows to `deliver`, the query /// in `task` canceled first. One that cannot start is answered (no rows) /// and reported here. pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, task: *?Task, req: Request, ctx: ?*anyopaque, deliver: Deliver) void { if (task.*) |*old| { old.future.cancel(io); task.* = null; } const job = snapshot(gpa, core, req) catch |err| { core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); return core.reportError(req.pane, "lsp", err); }; const future = io.concurrent(work, .{ io, gpa, job, ctx, deliver }) catch |err| { job.free(gpa); core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); return core.reportError(req.pane, "lsp", err); }; task.* = .{ .id = req.id, .future = future }; } /// The server start a file's opening asks for (`open`), one at a time: /// `busy` while its worker runs. pub const Opener = struct { future: ?std.Io.Future(void) = null, busy: std.atomic.Value(bool) = .init(false), }; /// Pane `pane`'s file just opened: the server of its language started and /// told of it (lsp_client.open) on a worker of its own, so its first query /// finds both done (that query paid a spawn and a handshake, 2.5 s of zls's /// over the comparison video's project). Not through `start`, whose cancel /// of the query in flight waits out a handshake on the loop, nor `work`, /// whose fixed region is the queries'. One at a time: a file opened while /// one is under way is let go, and told at its first query (syncDoc); one /// done is awaited (at once) before the next. pub fn open(io: std.Io, gpa: std.mem.Allocator, core: *const pardes.Pardes, opener: *Opener, pane: pardes.Pane.Id) void { if (opener.busy.load(.acquire)) return; if (opener.future) |*f| f.await(io); opener.future = null; const p = core.panes[pane.index()] orelse return; const f = p.file orelse return; if (!pardes.lsp.speaks(f.path)) return; const job = snapshot(gpa, core, .{ .id = 0, .kind = .definition, .pane = pane, .offset = 0, .arg = "" }) catch return; opener.busy.store(true, .release); opener.future = io.concurrent(tell, .{ io, gpa, job, &opener.busy }) catch { opener.busy.store(false, .release); return job.free(gpa); }; } fn tell(io: std.Io, gpa: std.mem.Allocator, job: *Job, busy: *std.atomic.Value(bool)) void { defer busy.store(false, .release); defer job.free(gpa); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); // A server that failed to start says so itself (`ensure`); one not // started for want of memory is started by the file's first query. pardes.lsp.open(io, arena.allocator(), .{ .kind = job.kind, .path = job.path, .source = job.source, .offset = 0, .root = job.root }) catch {}; } pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { defer job.free(gpa); // The query's memory is the fixed region memory.zig reserved at // startup: a hard bound, reused by each query in turn. const region = pardes.memory.takeLspQuery() orelse { deliver(ctx, job.id, null); return; }; var arena: std.heap.FixedBufferAllocator = .init(region); defer pardes.memory.giveLspQuery(arena.end_index); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); pardes.lsp.query(io, arena.allocator(), .{ .kind = job.kind, .path = job.path, .source = job.source, .offset = job.offset, .arg = job.arg, .root = job.root, .others = job.others, .callstack_depth = job.callstack_depth, .dirty = job.dirty, .budget = &arena, }, &out.writer) catch { deliver(ctx, job.id, null); return; }; const rows = out.toOwnedSlice() catch { deliver(ctx, job.id, null); return; }; deliver(ctx, job.id, rows); } test "a snapshot owns every byte the backend will read" { if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal pane's snapshot const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); core.settings.callstack_depth = 16; var needle: [6]u8 = "needle".*; const job = try snapshot(gpa, core, .{ .id = 7, .kind = .status, .pane = .at(core.view().active), .offset = 0, .arg = &needle, }); defer job.free(gpa); core.settings.callstack_depth = 2; try std.testing.expectEqual(@as(u8, 16), job.callstack_depth); try std.testing.expectEqual(@as(u32, 7), job.id); try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind); try std.testing.expectEqualStrings("needle", job.arg); try std.testing.expect(job.arg.ptr != &needle); try std.testing.expectEqualStrings("", job.path); try std.testing.expectEqual(@as(usize, 0), job.source.len); try std.testing.expectEqual(@as(u8, 0), job.source[0]); const pane = core.panes[core.view().active].?; try std.testing.expectEqualStrings(pane.cwdSlice(), job.root); if (job.root.len > 0) try std.testing.expect(job.root.ptr != pane.cwdSlice().ptr); } test "LSP snapshot frees every partially copied field on allocation failure" { const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer core.deinit(); _ = try core.setTestFile("const copied = true;\n"); const Snapshot = struct { fn check(gpa: std.mem.Allocator, p: *const pardes.Pardes) !void { const job = try snapshot(gpa, p, .{ .id = 7, .kind = .hover, .pane = .at(p.view().active), .offset = 6, .arg = "query", }); defer job.free(gpa); try std.testing.expectEqualStrings("const copied = true;\n", job.source); } }; try std.testing.checkAllAllocationFailures(std.testing.allocator, Snapshot.check, .{core}); } test "LSP snapshots translate explicit OS paths once and retain virtual names" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); const pane = try core.setTestFile("const value = true;\n"); for ([_]struct { path: []const u8, native: []const u8 }{ .{ .path = "/n/os/project/file.zig", .native = "/project/file.zig" }, .{ .path = "/n/os/n/os/project/file.zig", .native = "/n/os/project/file.zig" }, .{ .path = "/virtual/src/file.zig", .native = "/virtual/src/file.zig" }, }) |case| { const replacement = try gpa.dupe(u8, case.path); gpa.free(pane.file.?.path); pane.file.?.path = replacement; const job = try snapshot(gpa, core, .{ .id = 1, .kind = .hover, .pane = .at(core.view().active), .offset = 0, .arg = "" }); defer job.free(gpa); try std.testing.expectEqualStrings(case.native, job.path); try std.testing.expectEqualStrings(std.Io.Dir.path.dirname(case.native).?, job.root); try std.testing.expectEqualStrings(case.path, pane.file.?.path); } } test "a pane that is gone yields no job rather than a null deref" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); // The effect is drained after the core has moved on, so the pane it names // may already have been deleted. Every shell open-coded this check. const empty = for (core.panes, 0..) |slot, id| { if (slot == null) break @as(u8, @intCast(id)); } else return error.NoEmptyPane; try std.testing.expectError(error.NoPane, snapshot(gpa, core, .{ .id = 1, .kind = .definition, .pane = .at(empty), .offset = 0, .arg = "", })); } test "work consumes the job and hands its rows to the sink" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); const Sink = struct { var seen_id: u32 = 0; var seen_rows: ?[]u8 = null; fn take(_: ?*anyopaque, id: u32, rows: ?[]u8) void { seen_id = id; seen_rows = rows; } }; Sink.seen_id = 0; Sink.seen_rows = null; const job = try snapshot(gpa, core, .{ .id = 42, .kind = .status, .pane = .at(core.view().active), .offset = 0, .arg = "", }); work(std.testing.io, gpa, job, null, Sink.take); // `status` is the one kind that answers with no file and no cursor, which // is what makes it assertable here without a language server on the box. try std.testing.expectEqual(@as(u32, 42), Sink.seen_id); const rows = Sink.seen_rows orelse return error.SinkNeverCalled; defer gpa.free(rows); } test "LSP edit query failure leaves text and undo untouched before a successful retry" { if (!pardes.lsp.supports.contains(.format)) return; const Sink = struct { core: *pardes.Pardes, gpa: std.mem.Allocator, calls: usize = 0, failed: bool = false, fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { const self: *@This() = @ptrCast(@alignCast(ctx.?)); defer if (rows) |text| self.gpa.free(text); self.calls += 1; self.failed = rows == null; self.core.update(.{ .lsp_resp = .{ .id = id, .rows = rows } }); } }; const gpa = std.testing.allocator; for ([_]pardes.lsp.Kind{ .format, .rename }) |kind| { const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); const pane = try core.setTestFile("const value=1;\n"); const path = try gpa.dupe(u8, "/file.zig"); gpa.free(pane.file.?.path); pane.file.?.path = path; pane.body.cur_col = 6; const revision = pane.file.?.revision; const undo_len = pane.file.?.history.journal.done; var failing = std.testing.FailingAllocator.init(gpa, .{}); var sink: Sink = .{ .core = core, .gpa = failing.allocator() }; for ([_]bool{ true, false }) |fail| { failing.fail_index = std.math.maxInt(usize); core.lspRequest(core.view().active, kind, "renamed"); const job = try snapshot(failing.allocator(), core, .{ .id = core.lsp_ask.wait.?.id, .kind = kind, .pane = .at(core.view().active), .offset = 6, .arg = "renamed", }); if (fail) failing.fail_index = failing.alloc_index; work(std.testing.io, failing.allocator(), job, &sink, Sink.take); try std.testing.expectEqual(fail, sink.failed); try std.testing.expect(core.lsp_ask.wait == null); if (fail) { try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content); try std.testing.expectEqual(revision, pane.file.?.revision); try std.testing.expectEqual(undo_len, pane.file.?.history.journal.done); } else { try std.testing.expectEqualStrings(if (kind == .format) "const value = 1;\n" else "const renamed=1;\n", pane.file.?.content); try std.testing.expectEqual(undo_len + 1, pane.file.?.history.journal.done); } } try std.testing.expectEqual(@as(usize, 2), sink.calls); } } test "LSP work delivers failure when transferring result ownership cannot allocate" { if (!pardes.lsp.supports.contains(.status)) return; const TransferAllocator = struct { failed: bool = false, fail_copy: bool = false, fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.fail_copy) { self.failed = true; return null; } return std.testing.allocator.rawAlloc(len, alignment, ra); } fn resize(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { return std.testing.allocator.rawResize(bytes, alignment, len, ra); } fn remap(ctx: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); if (len < bytes.len) { self.fail_copy = true; return null; } return std.testing.allocator.rawRemap(bytes, alignment, len, ra); } fn free(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, ra: usize) void { std.testing.allocator.rawFree(bytes, alignment, ra); } }; const Sink = struct { calls: usize = 0, id: u32 = 0, rows: ?[]u8 = null, fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { const self: *@This() = @ptrCast(@alignCast(ctx.?)); self.calls += 1; self.id = id; self.rows = rows; } }; var allocator: TransferAllocator = .{}; const gpa: std.mem.Allocator = .{ .ptr = &allocator, .vtable = &.{ .alloc = TransferAllocator.alloc, .resize = TransferAllocator.resize, .remap = TransferAllocator.remap, .free = TransferAllocator.free, } }; const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer core.deinit(); const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = .at(core.view().active), .offset = 0, .arg = "" }); var sink: Sink = .{}; work(std.testing.io, gpa, job, &sink, Sink.take); if (sink.rows) |rows| gpa.free(rows); try std.testing.expect(allocator.failed); try std.testing.expectEqual(@as(usize, 1), sink.calls); try std.testing.expectEqual(@as(u32, 37), sink.id); try std.testing.expect(sink.rows == null); }