diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 22:03:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 22:23:51 -0300 |
| commit | 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch) | |
| tree | 813596ea84318a7bae4fd7416ba463de8e3b7107 /core/lsp/lsp.zig | |
| parent | 92d553123673376adf6126ab90d49a22c5b833d2 (diff) | |
| download | pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip | |
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/lsp/lsp.zig')
| -rw-r--r-- | core/lsp/lsp.zig | 207 |
1 files changed, 207 insertions, 0 deletions
diff --git a/core/lsp/lsp.zig b/core/lsp/lsp.zig new file mode 100644 index 00000000..7a636f72 --- /dev/null +++ b/core/lsp/lsp.zig @@ -0,0 +1,207 @@ +const std = @import("std"); + +/// The core's side of a question to the servers (Ask.zig). +pub const Ask = @import("Ask.zig"); + +pub const Kind = enum { + definition, + declaration, + type_definition, + implementation, + references, + hover, + document_symbols, + workspace_symbols, + diagnostics, + workspace_diagnostics, + rename, + code_action, + format, + select_refs, + completion, + callstack, + incoming_calls, + outgoing_calls, + supertypes, + subtypes, + status, + explain, + /// The Index word: the command line that makes the file's `index.scip`. + index, +}; + +pub const callstack_match = "@callstack-match "; +pub const callstack_default_depth: u8 = 8; +pub const callstack_max_depth: u8 = 64; + +pub const Req = struct { + callstack_depth: u8 = callstack_default_depth, + kind: Kind, + /// The pane holds changes not saved: what the index says of the file + /// on disk may be wrong of them, so the server answers (Scip.zig). + dirty: bool = false, + path: []const u8, + source: [:0]const u8, + offset: u32, + arg: []const u8 = "", + root: []const u8 = "", + /// The other files open in the editor, for a query whose answer can + /// reach them (a rename, references): the server is told of each first, + /// or it answers from what it has seen and misses the rest. + others: []const Doc = &.{}, + /// For `explain`: the query it narrates, read from `arg` (`<kind> + /// <arg>`) by `explaining`; a definition when none was asked before. + explains: Kind = .definition, + /// The fixed region `arena` allocates from, when it is one: a walk that + /// can grow (Callstack) reads how much is left and stops in time. + budget: ?*const std.heap.FixedBufferAllocator = null, +}; + +pub const Doc = struct { path: []const u8, source: [:0]const u8 }; + +/// Whether a query's answer can name places in other files, so every open +/// file of the server's language is synced before it is asked. +pub fn reachesOtherFiles(kind: Kind) bool { + return switch (kind) { + .rename, .references, .implementation, .workspace_symbols, .callstack, .incoming_calls, .outgoing_calls, .supertypes, .subtypes => true, + else => false, + }; +} + +/// An `explain` request made the one it narrates: `explains` and `arg` set +/// from its `<kind> <arg>`; any other request as it is. +pub fn explaining(req: Req) Req { + if (req.kind != .explain) return req; + var r = req; + const sp = std.mem.indexOfScalar(u8, req.arg, ' ') orelse req.arg.len; + const named = std.meta.stringToEnum(Kind, req.arg[0..sp]) orelse .definition; + r.explains = if (named == .explain or named == .status or named == .index) .definition else named; + r.arg = if (sp < req.arg.len) req.arg[sp + 1 ..] else ""; + return r; +} + +/// Every language, Zig's (zls) included, through the protocol client, which +/// runs its server as a child process. +const client = @import("dev").lsp_client; + +pub const supports: std.EnumSet(Kind) = client.supports; + +pub fn speaks(path: []const u8) bool { + return client.speaks(path); +} + +/// Every question, a file no server speaks for included: the client says +/// why it asked nothing, where an empty answer would read as nothing found. +pub fn query(io: std.Io, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { + return client.query(io, arena, req, out); +} + +/// The one line the client answers with when it cannot answer at all, and +/// why: the core says it rather than "nothing found". +pub fn none(out: *std.Io.Writer, comptime fmt: []const u8, args: anytype) std.Io.Writer.Error!void { + try out.print("@none " ++ fmt ++ "\n", args); +} + +// 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 { + client.setStatusSink(ctx, cb); +} + +pub fn rel(base: []const u8, path: []const u8) []const u8 { + if (base.len == 0) return path; + const prefix = std.mem.trimEnd(u8, base, "/"); + if (path.len > prefix.len and std.mem.startsWith(u8, path, prefix) and path[prefix.len] == '/') + return path[prefix.len + 1 ..]; + return path; +} + +pub fn row(out: *std.Io.Writer, path: []const u8, line: usize, col: usize, text: []const u8) std.Io.Writer.Error!void { + try out.print("{s}:{d}:{d} {s}\n", .{ + path, line + 1, col + 1, std.mem.trim(u8, text, " \t\r\n"), + }); +} + +// Input positions are zero-based and end-exclusive; displayed spans are one-based and inclusive. +pub fn spanRow(out: *std.Io.Writer, path: []const u8, line: usize, col: usize, end_line: usize, end_col: usize, text: []const u8) std.Io.Writer.Error!void { + return sourceSpanRow(out, path, line, col, end_line, end_col, std.mem.trim(u8, text, " \t\r\n")); +} + +/// Source bytes keep their indentation and trailing spaces so byte columns +/// still identify the same token in the displayed snippet. +pub fn sourceSpanRow(out: *std.Io.Writer, path: []const u8, line: usize, col: usize, end_line: usize, end_col: usize, text: []const u8) std.Io.Writer.Error!void { + try out.print("{s}:{d}:{d}", .{ path, line + 1, col + 1 }); + if (end_line == line and end_col > col) try out.print("-{d}", .{end_col}); + try out.print(" {s}\n", .{std.mem.trimEnd(u8, text, "\r\n")}); +} + +pub fn edit(out: *std.Io.Writer, start: usize, end: usize) std.Io.Writer.Error!void { + try out.print("@edit {d} {d}\n", .{ start, end }); +} + +pub fn put(out: *std.Io.Writer, start: usize, end: usize, text: []const u8) std.Io.Writer.Error!void { + try out.print("@put {d} {d} ", .{ start, end }); + for (text) |c| { + if (c == '%' or c < 0x21) + try out.print("%{X:0>2}", .{c}) + else + try out.writeByte(c); + } + try out.writeByte('\n'); +} + +pub fn lineCol(source: []const u8, offset: usize) struct { line: usize, col: usize } { + const upto = source[0..@min(offset, source.len)]; + const line = std.mem.count(u8, upto, "\n"); + const bol = if (std.mem.lastIndexOfScalar(u8, upto, '\n')) |i| i + 1 else 0; + return .{ .line = line, .col = upto.len - bol }; +} + +test "an explain request narrates the query named in its arg, a definition by default" { + const base: Req = .{ .kind = .explain, .path = "/x.zig", .source = "", .offset = 0 }; + var r = base; + r.arg = "hover "; + try std.testing.expectEqual(Kind.hover, explaining(r).explains); + r.arg = "rename newName"; + try std.testing.expectEqual(Kind.rename, explaining(r).explains); + try std.testing.expectEqualStrings("newName", explaining(r).arg); + try std.testing.expectEqual(Kind.definition, explaining(base).explains); +} + +test "LSP encoders report every insufficient output capacity" { + const cases = [_]struct { kind: enum { row, span, source_span, edit, put }, expected: []const u8 }{ + .{ .kind = .row, .expected = "file:1:3 hi\n" }, + .{ .kind = .span, .expected = "file:1:3-5 hi\n" }, + .{ .kind = .source_span, .expected = "file:1:3-5 \t hi \t\n" }, + .{ .kind = .edit, .expected = "@edit 1 3\n" }, + .{ .kind = .put, .expected = "@put 1 3 hé%20%25%0A\n" }, + }; + for (cases) |case| { + var buf: [128]u8 = undefined; + for (0..case.expected.len + 1) |capacity| { + var out: std.Io.Writer = .fixed(buf[0..capacity]); + const result = switch (case.kind) { + .row => row(&out, "file", 0, 2, " hi \n"), + .span => spanRow(&out, "file", 0, 2, 0, 5, " hi \n"), + .source_span => sourceSpanRow(&out, "file", 0, 2, 0, 5, "\t hi \t\r\n"), + .edit => edit(&out, 1, 3), + .put => put(&out, 1, 3, "hé %\n"), + }; + if (capacity < case.expected.len) { + try std.testing.expectError(error.WriteFailed, result); + } else { + try result; + try std.testing.expectEqualStrings(case.expected, out.buffered()); + } + } + } +} + +test "a question for a file no language server speaks for says why rather than find nothing" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var buf: [256]u8 = undefined; + var out: std.Io.Writer = .fixed(&buf); + // A file no server speaks for is answered, not left empty. + try query(std.testing.io, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); + try std.testing.expectStringStartsWith(out.buffered(), "@none "); +} |
