diff options
Diffstat (limited to 'src/lsp/lsp_client.zig')
| -rw-r--r-- | src/lsp/lsp_client.zig | 952 |
1 files changed, 476 insertions, 476 deletions
diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index 76be6f45..cad75c57 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -411,11 +411,6 @@ fn record(si: usize, req: lsp.Req, us: u64, rows: usize, err: []const u8) void { log_total += 1; } -/// What answered a logged query: a server, or `scip`, the index. -fn sourceName(spec: u8) []const u8 { - return if (spec < specs.len) specs[spec].name else "scip"; -} - fn hideTime() bool { return @import("../Messages.zig").Message.noTime(); } @@ -437,6 +432,269 @@ const Trace = struct { // ------------------------------------------------------------------- query +/// What answered a logged query: a server, or `scip`, the index. +fn sourceName(spec: u8) []const u8 { + return if (spec < specs.len) specs[spec].name else "scip"; +} + +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.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); + var newer: usize = 0; + var pbuf: [4096]u8 = undefined; + for (ix.documents) |d| newer += @intFromBool(ix.stale(io, std.fmt.bufPrint(&pbuf, "{s}/{s}", .{ ix.root(), d.path }) catch continue)); + try out.print("scip: {s}, {d} KB, {d} documents, {d} symbols", .{ ix.path(), (ix.size + 999) / 1000, ix.documents.len, symbols }); + if (!hideTime()) { + const secs: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@divTrunc(ix.mtime, std.time.ns_per_s)) }; + const day = secs.getEpochDay().calculateYearDay(); + const md = day.calculateMonthDay(); + try out.print(", indexed {d}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} UTC", .{ day.year, md.month.numeric(), md.day_index + 1, secs.getDaySeconds().getHoursIntoDay(), secs.getDaySeconds().getMinutesIntoHour() }); + } + try out.print(", {d} files newer\n", .{newer}); + } else { + try out.print("scip: no index.scip above {s}", .{dir}); + if (specFor(path)) |si| try out.print("; Index runs {s}", .{if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer}); + try out.writeByte('\n'); + } else |e| try out.print("scip: index.scip above {s}: {s}\n", .{ dir, @errorName(e) }); + try out.print("language servers:\n", .{}); + for (&specs, 0..) |*s, i| { + const c = &conns[i]; + c.mu.lockUncancelable(io); + const state = c.state; + var rootbuf: [256]u8 = undefined; + const rootlen = @min(c.root.len, rootbuf.len); + @memcpy(rootbuf[0..rootlen], c.root[0..rootlen]); + const root = rootbuf[0..rootlen]; + const enc = c.caps.enc; + const ndocs = c.docs.items.len; + const ndiag = c.diags.items.len; + const pull = c.caps.pull; + const chier = c.caps.call_hier; + const thier = c.caps.type_hier; + c.mu.unlock(io); + 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) { + try out.print(" root {s} {s}", .{ root, @tagName(enc) }); + if (pull) try out.print(" pull-diags", .{}); + if (chier) try out.print(" call-hier", .{}); + if (thier) try out.print(" type-hier", .{}); + try out.print(" docs {d} diag-files {d}", .{ ndocs, ndiag }); + } + if (env_v) |v| try out.print(" [{s}={s}]", .{ s.env, if (v.len == 0) "(disabled)" else v }); + try out.print("\n ", .{}); + for (s.exts) |e| try out.print("{s} ", .{e}); + try out.print("\n", .{}); + } + + while (!log_mu.tryLock()) std.atomic.spinLoopHint(); + defer log_mu.unlock(); + try out.print("\nclient queries ({d} total, keeping {d}):\n", .{ log_total, log_cap }); + var shown: usize = 0; + for (0..log_cap) |i| { + const e = &log_buf[(log_next + i) % log_cap]; + if (!e.used) continue; + shown += 1; + if (hideTime()) { + try out.print(" {s:<18} {s:<14} {s:<20} {d:>4} row(s){s}{s}\n", .{ + @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.rows, + if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], + }); + } else { + try out.print(" {s:<18} {s:<14} {s:<20} {d:>7}us {d:>4} row(s){s}{s}\n", .{ + @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.us, e.rows, + if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], + }); + } + } + if (shown == 0) try out.print(" (none yet — press gd in a file with a server, then ask again)\n", .{}); +} + +/// The Index word's command line: the language's indexer, at the +/// 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.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.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}); +} + +fn nowUs() u64 { + var ts: libc.timespec = undefined; + _ = libc.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) *| 1_000_000 +| @as(u64, @intCast(ts.nsec)) / 1000; +} + +/// Byte offset -> LSP position. `lsp.lineCol` gives the line and the BYTE +/// column; only the column needs re-counting, and only when the server +/// refused utf-8. +fn posOf(src: []const u8, off: u32, enc: Enc) Pos { + const lc = lsp.lineCol(src, off); + if (enc == .utf8) return .{ .line = @intCast(lc.line), .ch = @intCast(lc.col) }; + const bol = @min(off, src.len) - lc.col; + var units: u32 = 0; + var i: usize = bol; + while (i < bol + lc.col) { + const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; + units += if (l == 4 and enc == .utf16) 2 else 1; + i += l; + } + return .{ .line = @intCast(lc.line), .ch = units }; +} + +fn emitOcc(cx: *Cx, ix: *const Scip.Index, o: u32, note: []const u8) Err!void { + const occ = ix.occurrences[o]; + try emitPath(cx, ix.documents[occ.doc].enc, try indexPath(cx.arena, ix, occ.doc), occ.range, note); +} + +/// A symbol's definitions, as rows: named by the symbol, as a type +/// hierarchy's are, or by their source lines. +fn emitDefinitions(cx: *Cx, ix: *Scip.Index, symbol: u32, named: bool) Err!void { + for (ix.of(symbol)) |o| if (ix.occurrences[o].roles & Scip.role_definition != 0) { + const sig = if (Scip.field(ix.infos.items[symbol], 7)) |f| (Scip.field(f.bytes, 5) orelse Scip.Field{ .num = 0 }).bytes else ""; + const note = if (!named) "" else if (sig.len == 0) displayName(ix, symbol) else try std.fmt.allocPrint(cx.arena, "{s} {s}", .{ displayName(ix, symbol), flat(cx.arena, sig) }); + try emitOcc(cx, ix, o, note); + }; +} + +/// The symbols `symbol`'s relationships name with flag `flag` set +/// (scip.proto Relationship: 2 is_reference, 3 is_implementation, 4 +/// is_type_definition), the ones the index knows. +fn related(a: std.mem.Allocator, ix: *const Scip.Index, symbol: u32, flag: u64) Err![]u32 { + var out: std.ArrayList(u32) = .empty; + var r: Scip.Reader = .{ .bytes = ix.infos.items[symbol] }; + while (r.next() catch null) |f| if (f.num == 4) { + const to = Scip.field(f.bytes, 1) orelse continue; + if ((Scip.field(f.bytes, flag) orelse continue).int == 0) continue; + if (ix.ids.get(to.bytes)) |id| try out.append(a, id); + }; + return out.items; +} + +/// The index's answer (Scip.zig), in the rows the server's would make: true +/// when it had one, false to ask the server: no index above the file, a +/// file it does not hold, unsaved changes it has not seen, nothing at the +/// cursor, a symbol it does not know, or a word only a server answers. +fn fromIndex(io: std.Io, arena: std.mem.Allocator, req: lsp.Req, kind: lsp.Kind, out: *std.Io.Writer, tr: *Trace) Err!bool { + switch (kind) { + .definition, .type_definition, .implementation, .references, .select_refs, .hover, .document_symbols, .workspace_symbols, .incoming_calls, .outgoing_calls, .callstack, .supertypes, .subtypes => {}, + else => return false, + } + if (req.dirty) { + tr.note("unsaved changes the index has not seen: the server", .{}); + 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; + }) orelse { + tr.note("no index.scip above {s}", .{dir}); + return false; + }; + const doc = ix.document(req.path) orelse { + 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.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 = .{ .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| { + if (kind == .document_symbols and o.doc != doc) continue; + // A name, never a local or a whole file's module. + if (o.roles & Scip.role_definition == 0 or o.range.sl != o.range.el or std.mem.startsWith(u8, ix.symbols.items[o.symbol], "local ")) continue; + const name = displayName(ix, o.symbol); + if (kind == .workspace_symbols and std.ascii.findIgnoreCase(name, req.arg) == null) continue; + try emitOcc(&cx, ix, @intCast(i), name); + } + tr.note("<- {d} row(s) from the index", .{cx.rows}); + return cx.rows > 0; + } + const pos = posOf(req.source, req.offset, enc); + const at = ix.at(doc, pos.line, pos.ch) orelse { + tr.note("no occurrence at {d}:{d} in {s}", .{ pos.line + 1, pos.ch + 1, ix.path() }); + return false; + }; + const sym = ix.occurrences[at].symbol; + tr.note("{s}: occurrence '{s}' at {d}:{d}", .{ ix.path(), ix.symbols.items[sym], pos.line + 1, pos.ch + 1 }); + switch (kind) { + .definition => try emitDefinitions(&cx, ix, sym, false), + .type_definition => for (try related(arena, ix, sym, 4)) |to| try emitDefinitions(&cx, ix, to, false), + .supertypes => for (try related(arena, ix, sym, 3)) |to| try emitDefinitions(&cx, ix, to, true), + .implementation, .subtypes => for (ix.infos.items, 0..) |_, from| { + if (std.mem.indexOfScalar(u32, try related(arena, ix, @intCast(from), 3), sym) != null) + try emitDefinitions(&cx, ix, @intCast(from), kind == .subtypes); + }, + .references, .select_refs => { + var also = try related(arena, ix, sym, 2); + also = try std.mem.concat(arena, u32, &.{ &.{sym}, also }); + for (also) |of| for (ix.of(of)) |o| if (kind == .references or ix.occurrences[o].doc == doc) try emitOcc(&cx, ix, o, ""); + }, + .hover => { + const info = ix.infos.items[sym]; + var said = false; + if (Scip.field(info, 7)) |sig| if (Scip.field(sig.bytes, 5)) |text| { + try out.writeAll(std.mem.trim(u8, text.bytes, " \t\r\n")); + said = true; + }; + var r: Scip.Reader = .{ .bytes = info }; + while (r.next() catch null) |f| if (f.num == 3) { + if (said) try out.writeAll("\n\n"); + try out.writeAll(std.mem.trim(u8, f.bytes, " \t\r\n")); + said = true; + }; + if (said) try out.writeByte('\n') else tr.note("no documentation for it in the index", .{}); + return said; + }, + .incoming_calls => for (try indexHops(arena, ix, sym)) |hop| for (hop.sites.items) |site| + try emitPath(&cx, ix.documents[hop.doc].enc, try indexPath(arena, ix, hop.doc), site, hop.call.name), + .outgoing_calls => for (ix.of(sym)) |d| { + // The calls inside its definition, each function once, at its + // own definition. + const def = ix.occurrences[d]; + if (def.roles & Scip.role_definition == 0) continue; + var seen: std.ArrayList(u32) = .empty; + const in = ix.documents[def.doc]; + for (ix.occurrences[in.first..][0..in.len]) |o| { + if (o.roles & Scip.role_definition != 0 or !Scip.holds(def.enclosing, o.range) or !Scip.callable(ix.infos.items[o.symbol])) continue; + if (std.mem.indexOfScalar(u32, seen.items, o.symbol) != null) continue; + try seen.append(arena, o.symbol); + try emitDefinitions(&cx, ix, o.symbol, true); + } + break; + }, + .callstack => { + const def = for (ix.of(sym)) |o| { + if (ix.occurrences[o].roles & Scip.role_definition != 0) break ix.occurrences[o]; + } else { + tr.note("no definition of it in the index", .{}); + return false; + }; + // The rows come from the tree alone: the core reads the sources. + cx.no_text = true; + const focus: CallTree.Call = .{ .uri = try indexUri(arena, ix, def.doc), .name = "", .at = def.range }; + try callTree(.{ .index = ix }, si, &cx, enc, focus, try indexHops(arena, ix, sym), tr, req.callstack_depth, req.budget); + return true; + }, + else => unreachable, + } + tr.note("<- {d} row(s) from the index", .{cx.rows}); + return cx.rows > 0; +} + 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); @@ -561,6 +819,108 @@ fn attempt(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.R c.timeouts = 0; } +/// didOpen the first time a file is seen, didChange when its bytes moved, +/// nothing when they did not — the common case between two presses of gd. +fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { + const hash = std.hash.Wyhash.hash(0, src); + var doc: ?*Doc = null; + for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { + doc = d; + break; + }; + if (doc) |d| if (d.hash == hash) return; + + var b: std.ArrayList(u8) = .empty; + if (doc) |d| { + d.version += 1; + d.hash = hash; + d.stale = true; + try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didChange\",\"params\":{{\"textDocument\":{{\"uri\":", .{}); + try jstr(&b, arena, uri); + try b.print(arena, ",\"version\":{d}}},\"contentChanges\":[{{\"text\":", .{d.version}); + try jstr(&b, arena, src); + try b.appendSlice(arena, "}]}}"); + } else { + if (c.docs.items.len >= 256) return; // a session does not open this many + const owned = try sa.dupe(u8, uri); + c.docs.append(sa, .{ .uri = owned, .version = 1, .hash = hash }) catch { + sa.free(owned); + return error.OutOfMemory; + }; + try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"textDocument\":{\"uri\":"); + try jstr(&b, arena, uri); + try b.print(arena, ",\"languageId\":\"{s}\",\"version\":1,\"text\":", .{specs[si].lang}); + try jstr(&b, arena, src); + try b.appendSlice(arena, "}}}"); + } + // A server busy with what it was sent last reads no more meanwhile + // (clangd parses its compile database at a first open): this waits as + // an answer does, for a cancel or a server that has stopped. + try send(c, io, b.items, nowMs() + wedge_ms); +} + +/// The current-buffer byte column for a (line, ch) position — used only for +/// rows that point at the asking position itself. +fn byteCol(src: []const u8, line: u32, ch: u32, enc: Enc) usize { + var bol: usize = 0; + var n: u32 = 0; + while (n < line) : (n += 1) + bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return ch) + 1; + const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; + return colBytes(src[bol..eol], ch, enc); +} + +fn hierText(arena: std.mem.Allocator, item: std.json.Value) []const u8 { + const name = str(get(item, "name")) orelse ""; + const detail = str(get(item, "detail")) orelse return name; + return std.fmt.allocPrint(arena, "{s} {s}", .{ name, flat(arena, detail) }) catch name; +} + +/// The two-step hierarchy kinds: prepare at the cursor, then follow every +/// item the server returned (usually one). Gated on the server capability so +/// an old server costs zero round trips. +fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { + const call_side = h == .incoming or h == .outgoing; + if (call_side and !c.caps.call_hier) { + tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name}); + return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); + } + if (!call_side and !c.caps.type_hier) { + tr.note("STOP: {s} does not advertise typeHierarchyProvider", .{specs[si].name}); + return lsp.none(cx.out, "{s} does not answer type hierarchy (no typeHierarchyProvider)", .{specs[si].name}); + } + const prepare: []const u8 = if (call_side) "textDocument/prepareCallHierarchy" else "textDocument/prepareTypeHierarchy"; + const follow: []const u8 = switch (h) { + .incoming => "callHierarchy/incomingCalls", + .outgoing => "callHierarchy/outgoingCalls", + .supers => "typeHierarchy/supertypes", + .subs => "typeHierarchy/subtypes", + }; + const b = try atPos(arena, uri, pos); + const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return; + for (items(prepared)) |item| { + const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return; + for (items(result)) |entry| switch (h) { + .incoming => { + // one row per CALL SITE, under the caller's name — that is + // what n/N want to walk + const from = get(entry, "from") orelse continue; + const fu = str(get(from, "uri")) orelse continue; + const name = str(get(from, "name")) orelse ""; + const ranges = items(get(entry, "fromRanges")); + if (ranges.len == 0) { + try emitRange(cx, c.caps.enc, fu, get(from, "selectionRange"), name); + } else for (ranges) |r| try emitRange(cx, c.caps.enc, fu, r, name); + }, + .outgoing => { + const to = get(entry, "to") orelse continue; + try emitRange(cx, c.caps.enc, str(get(to, "uri")) orelse continue, get(to, "selectionRange") orelse get(to, "range"), hierText(cx.arena, to)); + }, + .supers, .subs => try emitRange(cx, c.caps.enc, str(get(entry, "uri")) orelse continue, get(entry, "selectionRange") orelse get(entry, "range"), hierText(cx.arena, entry)), + }; + } +} + fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { // `explain` narrates the last query asked (a definition, `gd`, when // none was) — dispatch below on the effective kind so the trace @@ -832,6 +1192,43 @@ fn holdsWord(text: []const u8, word: []const u8) bool { return false; } +/// (line, character) -> byte offset, or null when the line does not exist or +/// the character runs past its end. End-of-line (character == line length) is +/// a real position — that is where an insert-at-EOL lands. +fn strictOffset(src: []const u8, line: u32, ch: u32, enc: Enc) ?usize { + var bol: usize = 0; + var n: u32 = 0; + while (n < line) : (n += 1) + bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return null) + 1; + const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; + if (enc == .utf8) { + if (ch > eol - bol) return null; + return bol + ch; + } + var units: u32 = 0; + var i: usize = bol; + while (i < eol and units < ch) { + const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; + units += if (l == 4 and enc == .utf16) 2 else 1; + i += l; + } + if (units < ch) return null; + return i; +} + +/// Whole-document Range -> half-open byte span for a MUTATING record. +/// STRICT: null unless both endpoints denote positions that exist in the +/// document — for edits, a clamped range is a wrong edit, and wrong edits +/// fail closed (the render paths keep their forgiving conversions; a row a +/// column off is an inconvenience, a splice a column off is corruption). +fn byteSpan(src: []const u8, range: ?std.json.Value, enc: Enc) ?struct { start: usize, end: usize } { + const r = rangeOf(range) orelse return null; + const start = strictOffset(src, r.sl, r.sc, enc) orelse return null; + const end = strictOffset(src, r.el, r.ec, enc) orelse return null; + if (end < start) return null; + return .{ .start = start, .end = end }; +} + /// A WorkspaceEdit that stays inside the asked-about file becomes `@put` /// records the core applies as one undo transaction; anything wider (a real /// multi-file rename, file creates/renames) becomes a PREVIEW — one location @@ -1226,51 +1623,6 @@ fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: u const Hier = enum { incoming, outgoing, supers, subs }; -/// The two-step hierarchy kinds: prepare at the cursor, then follow every -/// item the server returned (usually one). Gated on the server capability so -/// an old server costs zero round trips. -fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { - const call_side = h == .incoming or h == .outgoing; - if (call_side and !c.caps.call_hier) { - tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name}); - return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); - } - if (!call_side and !c.caps.type_hier) { - tr.note("STOP: {s} does not advertise typeHierarchyProvider", .{specs[si].name}); - return lsp.none(cx.out, "{s} does not answer type hierarchy (no typeHierarchyProvider)", .{specs[si].name}); - } - const prepare: []const u8 = if (call_side) "textDocument/prepareCallHierarchy" else "textDocument/prepareTypeHierarchy"; - const follow: []const u8 = switch (h) { - .incoming => "callHierarchy/incomingCalls", - .outgoing => "callHierarchy/outgoingCalls", - .supers => "typeHierarchy/supertypes", - .subs => "typeHierarchy/subtypes", - }; - const b = try atPos(arena, uri, pos); - const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return; - for (items(prepared)) |item| { - const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return; - for (items(result)) |entry| switch (h) { - .incoming => { - // one row per CALL SITE, under the caller's name — that is - // what n/N want to walk - const from = get(entry, "from") orelse continue; - const fu = str(get(from, "uri")) orelse continue; - const name = str(get(from, "name")) orelse ""; - const ranges = items(get(entry, "fromRanges")); - if (ranges.len == 0) { - try emitRange(cx, c.caps.enc, fu, get(from, "selectionRange"), name); - } else for (ranges) |r| try emitRange(cx, c.caps.enc, fu, r, name); - }, - .outgoing => { - const to = get(entry, "to") orelse continue; - try emitRange(cx, c.caps.enc, str(get(to, "uri")) orelse continue, get(to, "selectionRange") orelse get(to, "range"), hierText(cx.arena, to)); - }, - .supers, .subs => try emitRange(cx, c.caps.enc, str(get(entry, "uri")) orelse continue, get(entry, "selectionRange") orelse get(entry, "range"), hierText(cx.arena, entry)), - }; - } -} - /// Depth of a parsed json value, saturating just past `at`'s caller's cap — /// the guard that keeps server-controlled nesting away from Stringify's /// fixed-depth assertion. @@ -1292,161 +1644,8 @@ fn jsonDepth(v: std.json.Value, at: u32) u32 { }; } -fn hierText(arena: std.mem.Allocator, item: std.json.Value) []const u8 { - const name = str(get(item, "name")) orelse ""; - const detail = str(get(item, "detail")) orelse return name; - return std.fmt.allocPrint(arena, "{s} {s}", .{ name, flat(arena, detail) }) catch name; -} - // ---------------------------------------------------------------- the index -/// The index's answer (Scip.zig), in the rows the server's would make: true -/// when it had one, false to ask the server: no index above the file, a -/// file it does not hold, unsaved changes it has not seen, nothing at the -/// cursor, a symbol it does not know, or a word only a server answers. -fn fromIndex(io: std.Io, arena: std.mem.Allocator, req: lsp.Req, kind: lsp.Kind, out: *std.Io.Writer, tr: *Trace) Err!bool { - switch (kind) { - .definition, .type_definition, .implementation, .references, .select_refs, .hover, .document_symbols, .workspace_symbols, .incoming_calls, .outgoing_calls, .callstack, .supertypes, .subtypes => {}, - else => return false, - } - if (req.dirty) { - tr.note("unsaved changes the index has not seen: the server", .{}); - 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; - }) orelse { - tr.note("no index.scip above {s}", .{dir}); - return false; - }; - const doc = ix.document(req.path) orelse { - 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.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 = .{ .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| { - if (kind == .document_symbols and o.doc != doc) continue; - // A name, never a local or a whole file's module. - if (o.roles & Scip.role_definition == 0 or o.range.sl != o.range.el or std.mem.startsWith(u8, ix.symbols.items[o.symbol], "local ")) continue; - const name = displayName(ix, o.symbol); - if (kind == .workspace_symbols and std.ascii.findIgnoreCase(name, req.arg) == null) continue; - try emitOcc(&cx, ix, @intCast(i), name); - } - tr.note("<- {d} row(s) from the index", .{cx.rows}); - return cx.rows > 0; - } - const pos = posOf(req.source, req.offset, enc); - const at = ix.at(doc, pos.line, pos.ch) orelse { - tr.note("no occurrence at {d}:{d} in {s}", .{ pos.line + 1, pos.ch + 1, ix.path() }); - return false; - }; - const sym = ix.occurrences[at].symbol; - tr.note("{s}: occurrence '{s}' at {d}:{d}", .{ ix.path(), ix.symbols.items[sym], pos.line + 1, pos.ch + 1 }); - switch (kind) { - .definition => try emitDefinitions(&cx, ix, sym, false), - .type_definition => for (try related(arena, ix, sym, 4)) |to| try emitDefinitions(&cx, ix, to, false), - .supertypes => for (try related(arena, ix, sym, 3)) |to| try emitDefinitions(&cx, ix, to, true), - .implementation, .subtypes => for (ix.infos.items, 0..) |_, from| { - if (std.mem.indexOfScalar(u32, try related(arena, ix, @intCast(from), 3), sym) != null) - try emitDefinitions(&cx, ix, @intCast(from), kind == .subtypes); - }, - .references, .select_refs => { - var also = try related(arena, ix, sym, 2); - also = try std.mem.concat(arena, u32, &.{ &.{sym}, also }); - for (also) |of| for (ix.of(of)) |o| if (kind == .references or ix.occurrences[o].doc == doc) try emitOcc(&cx, ix, o, ""); - }, - .hover => { - const info = ix.infos.items[sym]; - var said = false; - if (Scip.field(info, 7)) |sig| if (Scip.field(sig.bytes, 5)) |text| { - try out.writeAll(std.mem.trim(u8, text.bytes, " \t\r\n")); - said = true; - }; - var r: Scip.Reader = .{ .bytes = info }; - while (r.next() catch null) |f| if (f.num == 3) { - if (said) try out.writeAll("\n\n"); - try out.writeAll(std.mem.trim(u8, f.bytes, " \t\r\n")); - said = true; - }; - if (said) try out.writeByte('\n') else tr.note("no documentation for it in the index", .{}); - return said; - }, - .incoming_calls => for (try indexHops(arena, ix, sym)) |hop| for (hop.sites.items) |site| - try emitPath(&cx, ix.documents[hop.doc].enc, try indexPath(arena, ix, hop.doc), site, hop.call.name), - .outgoing_calls => for (ix.of(sym)) |d| { - // The calls inside its definition, each function once, at its - // own definition. - const def = ix.occurrences[d]; - if (def.roles & Scip.role_definition == 0) continue; - var seen: std.ArrayList(u32) = .empty; - const in = ix.documents[def.doc]; - for (ix.occurrences[in.first..][0..in.len]) |o| { - if (o.roles & Scip.role_definition != 0 or !Scip.holds(def.enclosing, o.range) or !Scip.callable(ix.infos.items[o.symbol])) continue; - if (std.mem.indexOfScalar(u32, seen.items, o.symbol) != null) continue; - try seen.append(arena, o.symbol); - try emitDefinitions(&cx, ix, o.symbol, true); - } - break; - }, - .callstack => { - const def = for (ix.of(sym)) |o| { - if (ix.occurrences[o].roles & Scip.role_definition != 0) break ix.occurrences[o]; - } else { - tr.note("no definition of it in the index", .{}); - return false; - }; - // The rows come from the tree alone: the core reads the sources. - cx.no_text = true; - const focus: CallTree.Call = .{ .uri = try indexUri(arena, ix, def.doc), .name = "", .at = def.range }; - try callTree(.{ .index = ix }, si, &cx, enc, focus, try indexHops(arena, ix, sym), tr, req.callstack_depth, req.budget); - return true; - }, - else => unreachable, - } - tr.note("<- {d} row(s) from the index", .{cx.rows}); - return cx.rows > 0; -} - -/// A symbol's definitions, as rows: named by the symbol, as a type -/// hierarchy's are, or by their source lines. -fn emitDefinitions(cx: *Cx, ix: *Scip.Index, symbol: u32, named: bool) Err!void { - for (ix.of(symbol)) |o| if (ix.occurrences[o].roles & Scip.role_definition != 0) { - const sig = if (Scip.field(ix.infos.items[symbol], 7)) |f| (Scip.field(f.bytes, 5) orelse Scip.Field{ .num = 0 }).bytes else ""; - const note = if (!named) "" else if (sig.len == 0) displayName(ix, symbol) else try std.fmt.allocPrint(cx.arena, "{s} {s}", .{ displayName(ix, symbol), flat(cx.arena, sig) }); - try emitOcc(cx, ix, o, note); - }; -} - -fn emitOcc(cx: *Cx, ix: *const Scip.Index, o: u32, note: []const u8) Err!void { - const occ = ix.occurrences[o]; - try emitPath(cx, ix.documents[occ.doc].enc, try indexPath(cx.arena, ix, occ.doc), occ.range, note); -} - -/// The symbols `symbol`'s relationships name with flag `flag` set -/// (scip.proto Relationship: 2 is_reference, 3 is_implementation, 4 -/// is_type_definition), the ones the index knows. -fn related(a: std.mem.Allocator, ix: *const Scip.Index, symbol: u32, flag: u64) Err![]u32 { - var out: std.ArrayList(u32) = .empty; - var r: Scip.Reader = .{ .bytes = ix.infos.items[symbol] }; - while (r.next() catch null) |f| if (f.num == 4) { - const to = Scip.field(f.bytes, 1) orelse continue; - if ((Scip.field(f.bytes, flag) orelse continue).int == 0) continue; - if (ix.ids.get(to.bytes)) |id| try out.append(a, id); - }; - return out.items; -} - /// A symbol's name to show: its display name, else its string's last /// descriptor (`... lib/add().` is `add`). fn displayName(ix: *const Scip.Index, symbol: u32) []const u8 { @@ -1465,17 +1664,6 @@ fn indexUri(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u return b.items; } -/// The Index word's command line: the language's indexer, at the -/// 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.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.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}); -} - // ------------------------------------------------------------ row rendering /// Files read while answering ONE query, so a references list over a handful @@ -1523,6 +1711,33 @@ fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: [ return emitAt(cx, enc, uri, rangeOf(range) orelse return, note); } +/// `file:///a/b%20c` -> `/a/b c`. Rows carry real paths; look.zig opens them +/// and `%20` is not a filename. A decoded CONTROL byte rejects the whole uri: +/// a `%0A` in a path would split one location into two physical rows — a +/// server-forged extra row in the results buffer — and no path worth opening +/// has a newline, tab or NUL in it. +fn pathOf(arena: std.mem.Allocator, uri: []const u8) ?[]const u8 { + var rest = uri; + if (std.mem.startsWith(u8, rest, "file://")) { + rest = rest["file://".len..]; + if (rest.len > 0 and rest[0] != '/') return null; // an authority we cannot open + } else if (std.mem.indexOf(u8, rest, "://") != null) return null; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < rest.len) { + var byte: u8 = rest[i]; + if (rest[i] == '%' and i + 2 < rest.len) { + if (std.fmt.parseInt(u8, rest[i + 1 .. i + 3], 16)) |b| { + byte = b; + i += 3; + } else |_| i += 1; + } else i += 1; + if (byte < 0x20) return null; + out.append(arena, byte) catch return null; + } + return out.items; +} + fn emitAt(cx: *Cx, enc: Enc, uri: []const u8, r: Range, note: []const u8) Err!void { return emitPath(cx, enc, pathOf(cx.arena, uri) orelse return, r, note); } @@ -1577,54 +1792,6 @@ fn colBytes(lntext: []const u8, ch: u32, enc: Enc) usize { return i; } -/// The current-buffer byte column for a (line, ch) position — used only for -/// rows that point at the asking position itself. -fn byteCol(src: []const u8, line: u32, ch: u32, enc: Enc) usize { - var bol: usize = 0; - var n: u32 = 0; - while (n < line) : (n += 1) - bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return ch) + 1; - const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; - return colBytes(src[bol..eol], ch, enc); -} - -/// Whole-document Range -> half-open byte span for a MUTATING record. -/// STRICT: null unless both endpoints denote positions that exist in the -/// document — for edits, a clamped range is a wrong edit, and wrong edits -/// fail closed (the render paths keep their forgiving conversions; a row a -/// column off is an inconvenience, a splice a column off is corruption). -fn byteSpan(src: []const u8, range: ?std.json.Value, enc: Enc) ?struct { start: usize, end: usize } { - const r = rangeOf(range) orelse return null; - const start = strictOffset(src, r.sl, r.sc, enc) orelse return null; - const end = strictOffset(src, r.el, r.ec, enc) orelse return null; - if (end < start) return null; - return .{ .start = start, .end = end }; -} - -/// (line, character) -> byte offset, or null when the line does not exist or -/// the character runs past its end. End-of-line (character == line length) is -/// a real position — that is where an insert-at-EOL lands. -fn strictOffset(src: []const u8, line: u32, ch: u32, enc: Enc) ?usize { - var bol: usize = 0; - var n: u32 = 0; - while (n < line) : (n += 1) - bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return null) + 1; - const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; - if (enc == .utf8) { - if (ch > eol - bol) return null; - return bol + ch; - } - var units: u32 = 0; - var i: usize = bol; - while (i < eol and units < ch) { - const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; - units += if (l == 4 and enc == .utf16) 2 else 1; - i += l; - } - if (units < ch) return null; - return i; -} - /// Prose squashed onto the one line a row is: newlines and tabs to spaces, /// cut to a width a pane can show. fn flat(arena: std.mem.Allocator, s: []const u8) []const u8 { @@ -1669,6 +1836,53 @@ fn transportPair(sv: *[2]libc.fd_t) bool { // ----------------------------------------------------------- the connection +/// Where the project starts: helix's find_root rule. Walk UP from `dir`; the +/// TOP-MOST directory holding a language marker wins (a cargo workspace's +/// root Cargo.toml beats the member crate's), the CLOSEST `.git` is the +/// fallback, the asking directory the last resort. +fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 { + if (dir.len == 0 or dir[0] != '/') return "/"; + var top_marker: ?[]const u8 = null; + var git: ?[]const u8 = null; + var d = dir; + var buf: [4096:0]u8 = undefined; + while (true) { + for (markers) |marker| { + const p = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d, marker }, 0) catch continue; + 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 (libc.access(p.ptr, libc.F_OK) == 0) git = d; + } else |_| {} + } + d = std.Io.Dir.path.dirname(d) orelse break; + if (d.len <= 1) break; + } + return top_marker orelse git orelse dir; +} + +/// 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 (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 (libc.access(z.ptr, libc.X_OK) == 0) z else null; + } + 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 (libc.access(cand.ptr, libc.X_OK) == 0) return cand; + } + return null; +} + /// Spawn-or-return, and tell an existing server about a new project root. /// Returns the generation the caller's whole query is bound to. fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { @@ -1892,46 +2106,6 @@ fn provider(v: ?std.json.Value) bool { }; } -/// didOpen the first time a file is seen, didChange when its bytes moved, -/// nothing when they did not — the common case between two presses of gd. -fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { - const hash = std.hash.Wyhash.hash(0, src); - var doc: ?*Doc = null; - for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { - doc = d; - break; - }; - if (doc) |d| if (d.hash == hash) return; - - var b: std.ArrayList(u8) = .empty; - if (doc) |d| { - d.version += 1; - d.hash = hash; - d.stale = true; - try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didChange\",\"params\":{{\"textDocument\":{{\"uri\":", .{}); - try jstr(&b, arena, uri); - try b.print(arena, ",\"version\":{d}}},\"contentChanges\":[{{\"text\":", .{d.version}); - try jstr(&b, arena, src); - try b.appendSlice(arena, "}]}}"); - } else { - if (c.docs.items.len >= 256) return; // a session does not open this many - const owned = try sa.dupe(u8, uri); - c.docs.append(sa, .{ .uri = owned, .version = 1, .hash = hash }) catch { - sa.free(owned); - return error.OutOfMemory; - }; - try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"textDocument\":{\"uri\":"); - try jstr(&b, arena, uri); - try b.print(arena, ",\"languageId\":\"{s}\",\"version\":1,\"text\":", .{specs[si].lang}); - try jstr(&b, arena, src); - try b.appendSlice(arena, "}}}"); - } - // A server busy with what it was sent last reads no more meanwhile - // (clangd parses its compile database at a first open): this waits as - // an answer does, for a cancel or a server that has stopped. - try send(c, io, b.items, nowMs() + wedge_ms); -} - /// Send a request and wait on the mailbox. Returns the parsed `result`, or /// null for an error response / null result — both are legal "no answer". /// Runs with the conn mutex held; the mutex is released inside the wait. @@ -2378,83 +2552,6 @@ fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method // ------------------------------------------------------------- introspection -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.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); - var newer: usize = 0; - var pbuf: [4096]u8 = undefined; - for (ix.documents) |d| newer += @intFromBool(ix.stale(io, std.fmt.bufPrint(&pbuf, "{s}/{s}", .{ ix.root(), d.path }) catch continue)); - try out.print("scip: {s}, {d} KB, {d} documents, {d} symbols", .{ ix.path(), (ix.size + 999) / 1000, ix.documents.len, symbols }); - if (!hideTime()) { - const secs: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@divTrunc(ix.mtime, std.time.ns_per_s)) }; - const day = secs.getEpochDay().calculateYearDay(); - const md = day.calculateMonthDay(); - try out.print(", indexed {d}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} UTC", .{ day.year, md.month.numeric(), md.day_index + 1, secs.getDaySeconds().getHoursIntoDay(), secs.getDaySeconds().getMinutesIntoHour() }); - } - try out.print(", {d} files newer\n", .{newer}); - } else { - try out.print("scip: no index.scip above {s}", .{dir}); - if (specFor(path)) |si| try out.print("; Index runs {s}", .{if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer}); - try out.writeByte('\n'); - } else |e| try out.print("scip: index.scip above {s}: {s}\n", .{ dir, @errorName(e) }); - try out.print("language servers:\n", .{}); - for (&specs, 0..) |*s, i| { - const c = &conns[i]; - c.mu.lockUncancelable(io); - const state = c.state; - var rootbuf: [256]u8 = undefined; - const rootlen = @min(c.root.len, rootbuf.len); - @memcpy(rootbuf[0..rootlen], c.root[0..rootlen]); - const root = rootbuf[0..rootlen]; - const enc = c.caps.enc; - const ndocs = c.docs.items.len; - const ndiag = c.diags.items.len; - const pull = c.caps.pull; - const chier = c.caps.call_hier; - const thier = c.caps.type_hier; - c.mu.unlock(io); - 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) { - try out.print(" root {s} {s}", .{ root, @tagName(enc) }); - if (pull) try out.print(" pull-diags", .{}); - if (chier) try out.print(" call-hier", .{}); - if (thier) try out.print(" type-hier", .{}); - try out.print(" docs {d} diag-files {d}", .{ ndocs, ndiag }); - } - if (env_v) |v| try out.print(" [{s}={s}]", .{ s.env, if (v.len == 0) "(disabled)" else v }); - try out.print("\n ", .{}); - for (s.exts) |e| try out.print("{s} ", .{e}); - try out.print("\n", .{}); - } - - while (!log_mu.tryLock()) std.atomic.spinLoopHint(); - defer log_mu.unlock(); - try out.print("\nclient queries ({d} total, keeping {d}):\n", .{ log_total, log_cap }); - var shown: usize = 0; - for (0..log_cap) |i| { - const e = &log_buf[(log_next + i) % log_cap]; - if (!e.used) continue; - shown += 1; - if (hideTime()) { - try out.print(" {s:<18} {s:<14} {s:<20} {d:>4} row(s){s}{s}\n", .{ - @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.rows, - if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], - }); - } else { - try out.print(" {s:<18} {s:<14} {s:<20} {d:>7}us {d:>4} row(s){s}{s}\n", .{ - @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.us, e.rows, - if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], - }); - } - } - if (shown == 0) try out.print(" (none yet — press gd in a file with a server, then ask again)\n", .{}); -} - // ------------------------------------------------------------------ plumbing /// `"textDocument":{"uri":U}` — the params every request about a file @@ -2572,59 +2669,6 @@ fn nowMs() i64 { return @as(i64, @intCast(ts.sec)) * 1000 + @divTrunc(@as(i64, @intCast(ts.nsec)), 1_000_000); } -fn nowUs() u64 { - var ts: libc.timespec = undefined; - _ = libc.clock_gettime(.MONOTONIC, &ts); - return @as(u64, @intCast(ts.sec)) *| 1_000_000 +| @as(u64, @intCast(ts.nsec)) / 1000; -} - -/// 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 (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 (libc.access(z.ptr, libc.X_OK) == 0) z else null; - } - 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 (libc.access(cand.ptr, libc.X_OK) == 0) return cand; - } - return null; -} - -/// Where the project starts: helix's find_root rule. Walk UP from `dir`; the -/// TOP-MOST directory holding a language marker wins (a cargo workspace's -/// root Cargo.toml beats the member crate's), the CLOSEST `.git` is the -/// fallback, the asking directory the last resort. -fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 { - if (dir.len == 0 or dir[0] != '/') return "/"; - var top_marker: ?[]const u8 = null; - var git: ?[]const u8 = null; - var d = dir; - var buf: [4096:0]u8 = undefined; - while (true) { - for (markers) |marker| { - const p = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d, marker }, 0) catch continue; - 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 (libc.access(p.ptr, libc.F_OK) == 0) git = d; - } else |_| {} - } - d = std.Io.Dir.path.dirname(d) orelse break; - if (d.len <= 1) break; - } - return top_marker orelse git orelse dir; -} - /// A path as a `file://` URI, raw (no JSON quotes). Everything outside the /// unreserved set is percent-encoded; `/` stays a separator. fn uriOf(b: *std.ArrayList(u8), arena: std.mem.Allocator, path: []const u8) Err!void { @@ -2638,33 +2682,6 @@ fn uriOf(b: *std.ArrayList(u8), arena: std.mem.Allocator, path: []const u8) Err! } } -/// `file:///a/b%20c` -> `/a/b c`. Rows carry real paths; look.zig opens them -/// and `%20` is not a filename. A decoded CONTROL byte rejects the whole uri: -/// a `%0A` in a path would split one location into two physical rows — a -/// server-forged extra row in the results buffer — and no path worth opening -/// has a newline, tab or NUL in it. -fn pathOf(arena: std.mem.Allocator, uri: []const u8) ?[]const u8 { - var rest = uri; - if (std.mem.startsWith(u8, rest, "file://")) { - rest = rest["file://".len..]; - if (rest.len > 0 and rest[0] != '/') return null; // an authority we cannot open - } else if (std.mem.indexOf(u8, rest, "://") != null) return null; - var out: std.ArrayList(u8) = .empty; - var i: usize = 0; - while (i < rest.len) { - var byte: u8 = rest[i]; - if (rest[i] == '%' and i + 2 < rest.len) { - if (std.fmt.parseInt(u8, rest[i + 1 .. i + 3], 16)) |b| { - byte = b; - i += 3; - } else |_| i += 1; - } else i += 1; - if (byte < 0x20) return null; - out.append(arena, byte) catch return null; - } - return out.items; -} - /// A JSON string. Invalid UTF-8 becomes `?` one byte at a time rather than /// U+FFFD: a buffer being typed into may be invalid mid-keystroke, and a /// replacement that changed byte lengths would move every offset after it. @@ -2706,23 +2723,6 @@ fn jstr(b: *std.ArrayList(u8), arena: std.mem.Allocator, s: []const u8) Err!void const Pos = struct { line: u32, ch: u32 }; -/// Byte offset -> LSP position. `lsp.lineCol` gives the line and the BYTE -/// column; only the column needs re-counting, and only when the server -/// refused utf-8. -fn posOf(src: []const u8, off: u32, enc: Enc) Pos { - const lc = lsp.lineCol(src, off); - if (enc == .utf8) return .{ .line = @intCast(lc.line), .ch = @intCast(lc.col) }; - const bol = @min(off, src.len) - lc.col; - var units: u32 = 0; - var i: usize = bol; - while (i < bol + lc.col) { - const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; - units += if (l == 4 and enc == .utf16) 2 else 1; - i += l; - } - return .{ .line = @intCast(lc.line), .ch = units }; -} - // std.json.Value navigation: optional-in, optional-out, so a missing field // and a wrongly-typed one read the same and neither can panic on a server // that sends the unexpected. |
