summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-26 02:28:09 -0300
committerGabriel Schneider <[email protected]>2026-11-26 02:49:36 -0300
commit148e48dd9b8cd7e66aa1521daa49a64852b1650e (patch)
treeedf3c1ca188018164a0713917ca0e336cecd14cd
parent1ce3bcb6178b720058518a12e45f25769be7d39c (diff)
downloadpardes-148e48dd9b8cd7e66aa1521daa49a64852b1650e.tar.gz
pardes-148e48dd9b8cd7e66aa1521daa49a64852b1650e.zip
syntax, Query, Pick, Names, Band, Stream, File, colors: the Symbols picker grouped by kind, a kind mark on each row (UX DESIGN N, binding; the user: "The lsp symbols should be more organized: types first then functions then fields and the rest (and some indicator to tell the kind)", "For the symbols picker"): the rows are the file's own parse's, as before, now from a symbol walk of their own (syntax.zig `SymbolWalk`, in the same walk of the tree as the sticky headers' declarations, which keep theirs: contextFromTree), by one kind table a grammar (`symbol_rules`: Zig, C, C++, Rust, Go, Python, JavaScript, Java, C#, Kotlin, Scala, Ruby, PHP, bash, Haskell, OCaml, Erlang, Elixir, Clojure, Fortran, Ada, Pascal, PowerShell; JSON, CSS, HTML, Markdown and Typst have no declarations to list), each node's kind as given or found where its grammar cannot say it (Zig's `const S = struct`, `error{...}`, `@This()`, `@Type(...)` a type and `@import(...)` a module, JavaScript's `const f = () => ...` a function, C's declaration a function where a declarator is one's and a const where `const` says so, a Python class's or Kotlin's binding a field in a type); fields and consts are listed now (the sticky headers' declarations had neither), a function's consts and vars never (its locals), each named in the types, functions and modules it is in (`Counts.lines`, `torque.Parser.Parse`; an anonymous struct's members in its owner's, a Rust `impl S`'s in `S`, no row of its own); a row is `t Counts = struct`: its kind's mark (t type, f function, m field, c const, v var, n module, · other), its qualified name, two blanks and what its name's line says after the name (its body's `{`, a trailing `,` or `;` dropped), its line the dim meta at the right end (Band's); the mark in the keyword's ink (colors.Roles.kind, the theme's keyword pushed to 4.5:1 on every tag ground and the selection, as the key ink is), the qualifier and the words after the name dim; with the field empty the rows are types, functions, fields, then the rest (consts, vars, modules, other as one group), each in the text's order; typed, they stay grouped and are scored within each group (Names: `Cand.group`, `before` orders by it, then by `better`), the cursor starts on the best match wherever its group puts it (Names.bestRow, Pick.toBest: after a key, when the parse lands, and following the best while the rest are scored), and the count says where it is; the name alone is matched (`u8` in a signature matches nothing); no header rows: every row is a symbol, ordinary text, and C-q keeps them in a +Search with the mark a word; the query pane's `Symbols` rows the same (Query.gather), its current the best; the parse's answer carries the symbols beside the declarations (Stream.Batch.symbols, an input every replica takes), ContextCache keeps both for the revision (derived, made again at a load), and every producer makes both (the worker, a sticky header's refresh, a load), so a text at a revision has the same symbols everywhere; syntax.zig's tests ran in no test program (core-test's filter `syntax context nested` matched nothing on the base): core/root.zig imports it now, and its 34 pass; RUN (TEST FIRST): syntax.zig "syntax symbols: a Zig file's types, functions, fields and the rest ...", "... C, C++, Rust, Go, Python and JavaScript by their kind tables ...", "... every kind table names nodes of its grammar ..." (23 tables), Pick.zig "Symbols (UX DESIGN N): a Zig file's rows types, functions, fields, then the rest ... the mark in the keyword's ink, the qualifier and the rest dim", "Symbols (UX DESIGN N3): typed, the rows stay grouped ... the cursor starts on the best match ...; the name alone is matched, never the signature", "Symbols (UX DESIGN N): a C++ file's rows ...", "Symbols: every row is ordinary text ..."; on the base the rows were ` 2 pub const Counts = struct {` in the text's order, no mark, no field, the cursor on the first row; core-test -Dtest-filter=ymbols 18/18, core-test 1135/1308 (173 skipped); the stack's suites, the dump fuzz, the soak and the pictures are on the change after this one
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBFhdevVu48bvL9kCE
-rw-r--r--core/Band.zig9
-rw-r--r--core/File.zig36
-rw-r--r--core/Names.zig31
-rw-r--r--core/Pick.zig255
-rw-r--r--core/Query.zig49
-rw-r--r--core/Stream.zig25
-rw-r--r--core/colors.zig6
-rw-r--r--core/draw.zig1
-rw-r--r--core/dump.zig13
-rw-r--r--core/root.zig1
-rw-r--r--core/syntax.zig707
11 files changed, 1066 insertions, 67 deletions
diff --git a/core/Band.zig b/core/Band.zig
index 8ee5c9f0..0424315a 100644
--- a/core/Band.zig
+++ b/core/Band.zig
@@ -40,6 +40,9 @@ pub const Row = struct {
on: bool = false,
/// Its first `key` bytes are a key: the key ink, bold.
key: u8 = 0,
+ /// Its first `kind` bytes are a symbol's kind mark (`t`, `f`, `m`):
+ /// the keyword's ink (UX DESIGN N4).
+ kind: u8 = 0,
/// Its first `chord` bytes are a chord (Help's `SPC h t`): the key ink
/// at the text's weight.
chord: u8 = 0,
@@ -53,8 +56,9 @@ pub const Row = struct {
index: u16 = 0,
/// Marked in a picker's list: `•` before it.
mark: bool = false,
- /// Its first `pre` bytes are a place (`file:line`, `@p3`): the name's
- /// tint; the `faint` bytes after them dimmed (a path's directory).
+ /// Its first `pre` bytes are a place (`file:line`, `@p3`) or a kind
+ /// mark: the name's tint; the `faint` bytes after them dimmed (a path's
+ /// directory, a symbol's qualifier).
pre: u16 = 0,
faint: u16 = 0,
/// Said at the row's right end in the dim ink, two cells off its text
@@ -644,6 +648,7 @@ fn cutRow(arena: std.mem.Allocator, tab: u16, row: Row, room: u16) !Row {
fit.text = try std.mem.concat(arena, u8, &.{ row.text[0..cut], if (room > 0) "…" else "" });
for (row.marks) |m| if (m < cut) try marks.append(arena, m);
fit.key = @intCast(@min(row.key, cut));
+ fit.kind = @intCast(@min(row.kind, cut));
fit.pre = @intCast(@min(row.pre, cut));
fit.faint = @intCast(@min(row.faint, cut -| fit.pre));
}
diff --git a/core/File.zig b/core/File.zig
index 0f9178ac..49d22fdc 100644
--- a/core/File.zig
+++ b/core/File.zig
@@ -60,35 +60,39 @@ pub const History = struct {
}
};
-/// Owned syntax results: a text's declarations at a revision.
+/// Owned syntax results: a text's declarations and symbols at a revision.
pub const ContextCache = struct {
/// Its revision is dumped and digested: a worker's parse is an input,
/// which a client joined since never saw, and a step reads what it
- /// left (Query.ownerDecls). The declarations are made again from the
- /// text at a load (`reload`), with the allocator that made them.
- pub const replica = .{ .local = .{"allocator"}, .derived = .{"declarations"} };
+ /// left (Query.ownerDecls, the Symbols source). The declarations and
+ /// symbols are made again from the text at a load (`reload`), with the
+ /// allocator that made them.
+ pub const replica = .{ .local = .{"allocator"}, .derived = .{ "declarations", "symbols" } };
allocator: ?std.mem.Allocator = null,
declarations: []syntax.ContextDeclaration = &.{},
+ symbols: []syntax.Symbol = &.{},
revision: ?u32 = null,
pub fn deinit(self: *ContextCache) void {
- if (self.allocator) |gpa| gpa.free(self.declarations);
+ if (self.allocator) |gpa| {
+ gpa.free(self.declarations);
+ gpa.free(self.symbols);
+ }
self.* = .{};
}
- /// A loaded text's (its revision the dump's): its declarations parsed
- /// again where they are of the text it has.
+ /// A loaded text's (its revision the dump's): its context parsed
+ /// again where it is of the text it has.
pub fn reload(self: *ContextCache, gpa: std.mem.Allocator, path: []const u8, content: []const u8, revision: u32) void {
const at = self.revision orelse return;
if (at != revision) return;
- const declarations = syntax.contextDeclarations(gpa, path, content) catch return;
- self.replace(gpa, declarations, at);
+ self.replace(gpa, syntax.context(gpa, path, content) catch return, at);
}
- /// Takes ownership of declarations allocated by gpa.
- pub fn replace(self: *ContextCache, gpa: std.mem.Allocator, declarations: []syntax.ContextDeclaration, revision: u32) void {
+ /// Takes ownership of a context allocated by gpa.
+ pub fn replace(self: *ContextCache, gpa: std.mem.Allocator, made: syntax.Context, revision: u32) void {
self.deinit();
- self.* = .{ .allocator = gpa, .declarations = declarations, .revision = revision };
+ self.* = .{ .allocator = gpa, .declarations = made.declarations, .symbols = made.symbols, .revision = revision };
}
};
@@ -2490,8 +2494,7 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void {
pub fn refreshContext(p: *Pardes, pane: *Pane, f: *State) void {
if (!f.tree_context or !supportsContext(pane) or f.context.revision == f.revision) return;
// The file's declarations, in its lines (the layer's are none of it).
- const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, fileText(f, p.scratch.allocator()) catch return) catch return;
- f.context.replace(p.tree_sitter_gpa, declarations, f.revision);
+ f.context.replace(p.tree_sitter_gpa, syntax.context(p.tree_sitter_gpa, f.path, fileText(f, p.scratch.allocator()) catch return) catch return, f.revision);
}
pub fn refreshHighlights(p: *Pardes) void {
@@ -3615,12 +3618,13 @@ test "context cache frees each allocation with its original allocator" {
defer std.testing.expect(second.deinit() == .ok) catch @panic("second allocator leaked");
var cache: ContextCache = .{};
defer cache.deinit();
- cache.replace(first.allocator(), try first.allocator().alloc(syntax.ContextDeclaration, 1), 1);
- cache.replace(second.allocator(), try second.allocator().alloc(syntax.ContextDeclaration, 2), 2);
+ cache.replace(first.allocator(), .{ .declarations = try first.allocator().alloc(syntax.ContextDeclaration, 1), .symbols = try first.allocator().alloc(syntax.Symbol, 1) }, 1);
+ cache.replace(second.allocator(), .{ .declarations = try second.allocator().alloc(syntax.ContextDeclaration, 2), .symbols = try second.allocator().alloc(syntax.Symbol, 2) }, 2);
try std.testing.expectEqual(@as(?u32, 2), cache.revision);
cache.deinit();
try std.testing.expect(cache.allocator == null);
try std.testing.expectEqual(@as(usize, 0), cache.declarations.len);
+ try std.testing.expectEqual(@as(usize, 0), cache.symbols.len);
}
/// The inks of row `row`'s first `n` text cells of pane `id` as `s` draws them.
diff --git a/core/Names.zig b/core/Names.zig
index d063bd17..415064ad 100644
--- a/core/Names.zig
+++ b/core/Names.zig
@@ -50,6 +50,9 @@ pub const Cand = struct {
/// What the row is of: a line of the owner (Symbols, 1-based), a
/// pane's serial (Panes); 0 for a path.
ref: u32 = 0,
+ /// Its group: the hits stay in their groups' order, scored within
+ /// each (a Symbols row's kind, UX DESIGN N3); 0 for every other source.
+ group: u8 = 0,
};
pub const Hit = struct { cand: u32, score: i32 };
@@ -187,9 +190,17 @@ pub fn reachTo(n: *Names, rows: usize) void {
n.gen +%= 1;
}
-/// Hit `a` goes before `b`: the higher score, then the shorter key, then
-/// the candidate added first.
+/// Hit `a` goes before `b`: the lower group, then `better`.
fn before(cands: []const Cand, a: Hit, b: Hit) bool {
+ const ga = cands[a.cand].group;
+ const gb = cands[b.cand].group;
+ if (ga != gb) return ga < gb;
+ return better(cands, a, b);
+}
+
+/// Hit `a` matched better than `b`: the higher score, then the shorter
+/// key, then the candidate added first.
+fn better(cands: []const Cand, a: Hit, b: Hit) bool {
if (a.score != b.score) return a.score > b.score;
const la = cands[a.cand].key_len;
const lb = cands[b.cand].key_len;
@@ -230,6 +241,22 @@ fn sink(heap: []Hit, cands: []const Cand, from: usize) void {
}
}
+/// The row of the hit the query matched best, wherever its group puts it:
+/// where a list's cursor starts (UX DESIGN N3); 0 for an empty query,
+/// whose rows are the source's order. Its rows up to it are sorted once
+/// `reachTo` has gone past it.
+pub fn bestRow(n: *const Names) usize {
+ const hits = n.hits.items;
+ if (hits.len == 0 or std.mem.trim(u8, n.queryText(), " ").len == 0) return 0;
+ var top = hits[0];
+ for (hits[1..]) |h| if (better(n.cands.items, h, top)) {
+ top = h;
+ };
+ var at: usize = 0;
+ for (hits) |h| at += @intFromBool(before(n.cands.items, h, top));
+ return at;
+}
+
/// The row of hit `i` and, in `marks`, the bytes of it the query matched.
pub fn row(n: *const Names, i: usize, marks: []u16, nmarks: *usize) []const u8 {
const c = n.cands.items[n.hits.items[i].cand];
diff --git a/core/Pick.zig b/core/Pick.zig
index 1d332f25..2b5714cb 100644
--- a/core/Pick.zig
+++ b/core/Pick.zig
@@ -452,7 +452,10 @@ pub fn filter(p: *Pardes, pk: *Pick) void {
const q = std.mem.trim(u8, p.view().tag_state.field.text(), " ");
p.view().tag_state.rows.at = 0;
pk.shown = no_row;
- if (fuzzy(pk)) return pk.names.typed(p.gpa, q);
+ if (fuzzy(pk)) {
+ pk.names.typed(p.gpa, q);
+ return toBest(p, pk);
+ }
if (pk.source == .grep) {
pk.found.clearRetainingCapacity();
pk.found_bytes.clearRetainingCapacity();
@@ -514,15 +517,31 @@ pub fn declsArrived(p: *Pardes, serial: u32) void {
Query.gather(p, &pk.names, .symbols, pk.dir.slice(), null, p.paneBySerial(serial));
pk.names.typed(p.gpa, pk.names.queryText());
pk.names.rescore(p.gpa);
+ if (live(p) == pk) toBest(p, pk);
};
}
+/// The live picker's cursor on its best match, wherever its group puts it
+/// (UX DESIGN N3: a Symbols list stays grouped while typed), its rows
+/// sorted as far as the band shows past it.
+fn toBest(p: *Pardes, pk: *Pick) void {
+ const at = pk.names.bestRow();
+ pk.names.reachTo(at + Band.Cursor.shown);
+ p.view().tag_state.rows.at = @intCast(@min(at, std.math.maxInt(u16)));
+}
+
/// After every step: each live picker's names scored on (a frame's count),
/// and on a frame of its own after the cursor stood, the preview of the
/// current row.
pub fn produceAll(p: *Pardes, tick: bool) void {
for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) {
- if (pk.names.busy()) pk.names.rescore(p.gpa);
+ if (pk.names.busy()) {
+ // A cursor on the best match follows it while the rest are
+ // scored.
+ const on_best = live(p) == pk and p.view().tag_state.rows.at == pk.names.bestRow();
+ pk.names.rescore(p.gpa);
+ if (on_best) toBest(p, pk);
+ }
// A theme's preview in the step of the key that moved to it.
if (pk.source == .themes) pardes.colors.previewTheme(p, refAt(p, pk));
if (tick) preview(p, pk);
@@ -584,7 +603,7 @@ const Target = union(enum) { none, place: struct { path: []const u8, at: look.Sp
/// Row `i` as the band shows it and what it points at, its text in
/// `arena`.
-const Row = struct { text: []const u8, key: u8 = 0, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none, meta: []const u8 = "" };
+const Row = struct { text: []const u8, key: u8 = 0, kind: u8 = 0, pre: u16 = 0, faint: u16 = 0, quiet: [2]u16 = .{ 0, 0 }, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none, meta: []const u8 = "" };
fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) std.mem.Allocator.Error!Row {
const dir = pk.dir.slice();
@@ -646,8 +665,23 @@ fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) std.me
row.dim = p.paneBySerial(cand.ref) == null;
row.target = .{ .pane = cand.ref };
},
+ // ` 12 m Counts.lines : usize = 0` (Query.gather): the line its
+ // meta, the mark in the keyword's ink, the qualifier and what
+ // follows the name dim (UX DESIGN N4).
.symbols => {
- row.pre = 6;
+ const line = 8;
+ if (text.len <= line or cand.key < line) return row;
+ row.text = text[line..];
+ row.meta = std.mem.trimStart(u8, text[0..6], " ");
+ const marks_in = try arena.alloc(u16, row.marks.len);
+ for (marks_in, row.marks) |*m, at| m.* = at -| line;
+ row.marks = marks_in;
+ const name_at = cand.key - line;
+ const dot = std.mem.lastIndexOfScalar(u8, row.text[name_at .. name_at + cand.key_len], '.');
+ row.kind = @intCast(name_at - 1);
+ row.pre = @intCast(name_at);
+ row.faint = @intCast(if (dot) |at| at + 1 else 0);
+ if (name_at + cand.key_len < row.text.len) row.quiet = .{ @intCast(name_at + cand.key_len), @intCast(row.text.len) };
const owner = p.panes[p.paneBySerial(pk.owner) orelse return row] orelse return row;
const f = owner.file orelse return row;
row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } };
@@ -837,7 +871,7 @@ pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step {
const rows = try arena.alloc(Band.Row, w.hi - w.lo);
for (rows, w.lo..) |*row, i| {
const r = try rowAt(p, pk, arena, i);
- row.* = .{ .text = r.text, .key = r.key, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i), .meta = r.meta };
+ row.* = .{ .text = r.text, .key = r.key, .kind = r.kind, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .quiet = r.quiet, .marks = r.marks, .index = @intCast(i), .meta = r.meta };
}
// A place's text (a Grep's line, a list's): its `path:line` in the dim
// ink and the text after it in one column, the widest place shown
@@ -1415,6 +1449,7 @@ fn refine(p: *Pardes, pk: *Pick, drop: bool) void {
if (drop and (if (pk.marks.items.len > 0) marked(pk, h.cand) != null else h.cand == current)) continue;
const c = pk.names.cands.items[h.cand];
next.add(p.gpa, pk.names.bytes.items[c.start..][0..c.len], c.key, c.key_len, c.base, c.ref) catch break;
+ next.cands.items[next.cands.items.len - 1].group = c.group;
}
} else {
var arena = std.heap.ArenaAllocator.init(p.gpa);
@@ -1514,7 +1549,7 @@ fn keep(p: *Pardes, pk: *Pick) void {
const row = rowAt(p, pk, arena.allocator(), i) catch break;
switch (row.target) {
.place => |t| if (pk.source == .symbols)
- out.writer.print("{s}:{d} {s}\n", .{ std.Io.Dir.path.basename(t.path), t.at.line, std.mem.trimStart(u8, row.text, " 0123456789") }) catch break
+ out.writer.print("{s}:{d} {s}\n", .{ std.Io.Dir.path.basename(t.path), t.at.line, row.text }) catch break
else
out.writer.print("{s}\n", .{row.text}) catch break,
else => out.writer.print("{s}\n", .{row.text}) catch break,
@@ -3283,3 +3318,211 @@ test "Ctrl-r in a picker unrolls its source's earlier queries (UX L2's last line
p.update(.{ .key = .{ .cp = Key.escape } });
p.update(.{ .key = .{ .cp = Key.escape } });
}
+
+/// A Symbols picker opened from a file pane whose path is `name` and text
+/// `text`, its symbols parsed (small: here and now), and the pane.
+fn openSymbols(p: *Pardes, name: []const u8, text: []const u8) !*Pane {
+ const pane = try p.setTestFile(text);
+ p.gpa.free(pane.file.?.path);
+ pane.file.?.path = try p.gpa.dupe(u8, name);
+ open(p, p.view().active, .symbols, "", "", "");
+ settle(p);
+ return pane;
+}
+
+/// The live picker's rows, `meta text` a line each.
+fn rowLines(p: *Pardes, a: std.mem.Allocator) ![]const u8 {
+ const pk = live(p).?;
+ var out: std.ArrayList(u8) = .empty;
+ for (0..count(p, pk)) |i| {
+ const r = try rowAt(p, pk, a, i);
+ try out.print(a, "{s: >2} {s}\n", .{ r.meta, r.text });
+ }
+ return out.items;
+}
+
+const counts_zig =
+ \\const std = @import("std");
+ \\pub const Counts = struct {
+ \\ lines: usize = 0,
+ \\ words: usize = 0,
+ \\ pub const zero: Counts = .{};
+ \\ pub fn add(c: *Counts, text: []const u8) void {
+ \\ const local = text.len;
+ \\ c.lines += local;
+ \\ }
+ \\};
+ \\const Mode = enum { fast, slow };
+ \\var hits: u32 = 0;
+ \\pub fn count(text: []const u8) Counts {
+ \\ return .{ .lines = text.len };
+ \\}
+ \\test "count" {}
+ \\
+;
+
+test "Symbols (UX DESIGN N): a Zig file's rows types, functions, fields, then the rest, each in the text's order with the field empty; a row its kind's mark, its name qualified, what its first line says after it, its line the meta; the mark in the keyword's ink, the qualifier and the rest dim" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
+ defer p.deinit();
+ p.settings.jumps = .walk;
+ var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer frame.deinit();
+ const a = frame.allocator();
+ _ = try openSymbols(p, "/w6/counts.zig", counts_zig);
+ try std.testing.expectEqualStrings(
+ \\ 2 t Counts = struct
+ \\11 t Mode = enum { fast, slow }
+ \\ 6 f Counts.add (c: *Counts, text: []const u8) void
+ \\13 f count (text: []const u8) Counts
+ \\ 3 m Counts.lines : usize = 0
+ \\ 4 m Counts.words : usize = 0
+ \\11 m Mode.fast
+ \\11 m Mode.slow
+ \\ 1 n std = @import("std")
+ \\ 5 c Counts.zero : Counts = .{}
+ \\12 v hits : u32 = 0
+ \\16 · "count"
+ \\
+ , try rowLines(p, a));
+ // Drawn: `m Counts.lines : usize = 0` (not the cursor's row).
+ const pane = p.panes[p.paneBySerial(live(p).?.landing).?].?;
+ _ = try p.render(a);
+ const layer = &p.surface.tag_layers[pardes.BAND_LAYER];
+ const roles = &p.chromeTheme().roles;
+ const inks = roles.on(if (Trail.reading(p, pane)) .reading_focused else .focused);
+ var found = false;
+ for (0..layer.rows) |y| {
+ const cells = layer.cells[y * layer.cols ..][0..layer.cols];
+ var text: std.ArrayList(u8) = .empty;
+ var at: std.ArrayList(usize) = .empty;
+ for (cells, 0..) |c, x| {
+ try at.append(a, text.items.len);
+ try text.appendSlice(a, c.grapheme());
+ _ = x;
+ }
+ const from = std.mem.indexOf(u8, text.items, "m Counts.lines") orelse continue;
+ var x: usize = 0;
+ while (at.items[x] < from) x += 1;
+ try std.testing.expectEqual(pardes.Color{ .rgb = roles.kind }, cells[x].style.fg);
+ try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[x + 2].style.fg);
+ try std.testing.expectEqual(pardes.Color{ .rgb = inks.text }, cells[x + 9].style.fg);
+ try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[x + 16].style.fg);
+ // Its line at the row's right end, dim.
+ const three = std.mem.lastIndexOfScalar(u8, text.items, '3').?;
+ var m: usize = 0;
+ while (at.items[m] < three) m += 1;
+ try std.testing.expect(m > x + 30);
+ try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[m].style.fg);
+ found = true;
+ }
+ try std.testing.expect(found);
+}
+
+test "Symbols (UX DESIGN N3): typed, the rows stay grouped, scored within each group, and the cursor starts on the best match wherever its group puts it; the name alone is matched, never the signature" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
+ defer p.deinit();
+ p.settings.jumps = .walk;
+ var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer frame.deinit();
+ const a = frame.allocator();
+ const pane = try openSymbols(p, "/w6/counts.zig", counts_zig);
+ for ("count") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
+ settle(p);
+ const rows = try rowLines(p, a);
+ try std.testing.expect(std.mem.startsWith(u8, rows,
+ \\ 2 t Counts = struct
+ \\13 f count (text: []const u8) Counts
+ \\ 6 f Counts.add (c: *Counts, text: []const u8) void
+ \\ 3 m Counts.lines : usize = 0
+ \\ 4 m Counts.words : usize = 0
+ \\
+ ));
+ // `count` matched best: the cursor on it, not on the first row, and
+ // the count says where it is.
+ const s = &p.view().tag_state;
+ try std.testing.expectEqual(@as(u16, 1), s.rows.at);
+ const h = (try head(p, a, p.panes[p.paneBySerial(live(p).?.landing).?].?)).?;
+ try std.testing.expect(std.mem.indexOf(u8, h.text, "2/7") != null);
+ // Enter lands on its line.
+ _ = pane;
+ // `u8` is in signatures only: nothing matches.
+ for (0..5) |_| p.update(.{ .key = .{ .cp = pardes.Key.backspace } });
+ for ("u8") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
+ settle(p);
+ try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?));
+}
+
+test "Symbols (UX DESIGN N): a C++ file's rows by its kind table, members named in their class and namespace, a function's locals none" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
+ defer p.deinit();
+ p.settings.jumps = .walk;
+ var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer frame.deinit();
+ _ = try openSymbols(p, "/w6/parser.cc",
+ \\#define LIMIT 4
+ \\namespace torque {
+ \\class Parser : public Base {
+ \\ public:
+ \\ Parser();
+ \\ int Parse(int depth) const { return depth; }
+ \\ int depth_;
+ \\};
+ \\enum class Kind { kA, kB };
+ \\int Parser::Run(int n) { int local = n; return local; }
+ \\static int counter = 0;
+ \\const int limit = 4;
+ \\using Alias = int;
+ \\}
+ \\
+ );
+ try std.testing.expectEqualStrings(
+ \\ 3 t torque.Parser : public Base
+ \\ 9 t torque.Kind
+ \\13 t torque.Alias = int
+ \\ 5 f torque.Parser.Parser ()
+ \\ 6 f torque.Parser.Parse (int depth) const
+ \\10 f torque.Parser::Run (int n)
+ \\ 7 m torque.Parser.depth_
+ \\ 9 m torque.Kind.kA
+ \\ 9 m torque.Kind.kB
+ \\ 1 · LIMIT 4
+ \\ 2 n torque
+ \\11 v torque.counter = 0
+ \\12 c torque.limit = 4
+ \\
+ , try rowLines(p, frame.allocator()));
+}
+
+test "Symbols: every row is ordinary text: no header rows, the cursor steps onto each in turn, the band shows each row's text, and C-q keeps them in a +Search with the mark a word" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 });
+ defer p.deinit();
+ p.settings.jumps = .walk;
+ var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer frame.deinit();
+ const a = frame.allocator();
+ _ = try openSymbols(p, "/w6/counts.zig", counts_zig);
+ const pk = live(p).?;
+ const n = count(p, pk);
+ try std.testing.expectEqual(@as(usize, 12), n);
+ const s = &p.view().tag_state;
+ for (0..n) |i| {
+ try std.testing.expectEqual(@as(u16, @intCast(i)), s.rows.at);
+ const r = try rowAt(p, pk, a, i);
+ const host = p.paneBySerial(pk.landing).?;
+ const band = (try Band.of(p, a, p.panes[host].?, host)).?;
+ var shown = false;
+ for (0..band.height) |y| {
+ const ln = try band.line(a, p.settings.tab, @intCast(y));
+ shown = shown or std.mem.indexOf(u8, ln.text, r.text) != null;
+ }
+ try std.testing.expect(shown);
+ p.update(.{ .key = .{ .cp = pardes.Key.down } });
+ }
+ p.update(.{ .key = .{ .cp = 'q', .ctrl = true } });
+ var kept: ?[]const u8 = null;
+ for (p.panes) |slot| if (slot) |tp| if (tp.file) |f| if (std.mem.startsWith(u8, f.content, "Symbols ")) {
+ kept = f.content;
+ };
+ try std.testing.expect(std.mem.indexOf(u8, kept.?, "\ncounts.zig:3 m Counts.lines : usize = 0\n") != null);
+ try std.testing.expect(std.mem.indexOf(u8, kept.?, "\ncounts.zig:2 t Counts = struct\n") != null);
+}
diff --git a/core/Query.zig b/core/Query.zig
index 2b2abebb..743e9540 100644
--- a/core/Query.zig
+++ b/core/Query.zig
@@ -530,8 +530,9 @@ fn makeNameRows(p: *Pardes, id: usize) !void {
f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{};
q.total = q.names.hits.items.len;
q.more = q.names.busy() or p.stream.busyFor(rp.serial);
- // The best is current until a step or a click moves it.
- q.current = if (shown > 0) 0 else null;
+ // The best is current until a step or a click moves it: in a grouped
+ // list (Symbols) wherever its group puts it.
+ q.current = if (shown > 0) @min(q.names.bestRow(), shown - 1) else null;
countCurrent(q);
showCurrent(p.settings.tab, rp);
if (q.current == null) blankPreview(p, id) else showTarget(p, id);
@@ -771,23 +772,51 @@ pub fn gather(p: *Pardes, names: *Names, source: Source, dir: []const u8, self:
const oid = owner_id orelse return;
const owner = p.panes[oid].?;
const f = if (owner.file) |*file| file else return;
- const decls = ownerDecls(f) orelse {
+ if (f.context.revision != f.revision) {
// Parsed on the worker; listed when it is done (declsArrived).
Stream.parseFor(p, oid);
return;
- };
- for (decls) |d| {
- const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)];
- const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r");
- var buf: [256 + 16]u8 = undefined;
- const row = std.fmt.bufPrint(&buf, "{d: >6} {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue;
- names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break;
}
+ // The file's text, which was parsed (the `Changes` layer's lines
+ // are none of it).
+ const text = File.fileText(f, p.scratch.allocator()) catch return;
+ const symbols = f.context.symbols;
+ // A row a symbol, ` 12 m Counts.lines : usize = 0`: its
+ // line, its mark, its name qualified by the ones it is in, then
+ // what its first line says after the name; types, functions,
+ // fields, then the rest, each in the text's order (UX DESIGN N).
+ // The name alone is matched.
+ for (0..4) |group| for (symbols) |sym| {
+ if (sym.kind.group() != group or sym.kind == .scope or sym.end > text.len) continue;
+ var buf: [512]u8 = undefined;
+ var row: std.Io.Writer = .fixed(&buf);
+ row.print("{d: >6} {s} ", .{ sym.line + 1, sym.kind.mark() }) catch continue;
+ const key_at = row.end;
+ qualify(&row, symbols, text, sym.parent, 4) catch continue;
+ row.writeAll(text[sym.name_start..sym.name_end]) catch continue;
+ const key_len = row.end - key_at;
+ const rest = text[sym.name_end..@max(sym.name_end, sym.end)];
+ var detail = std.mem.trim(u8, rest[0 .. std.mem.indexOfScalar(u8, rest, '\n') orelse rest.len], " \t\r");
+ detail = std.mem.trimEnd(u8, std.mem.trimEnd(u8, detail, "{,;"), " \t");
+ if (detail.len > 0) row.print(" {s}", .{detail[0..@min(detail.len, buf.len - row.end -| 2)]}) catch {};
+ names.add(gpa, row.buffered(), key_at, key_len, 0, sym.line + 1) catch break;
+ names.cands.items[names.cands.items.len - 1].group = @intCast(group);
+ };
},
else => {},
}
}
+/// The names of the symbols `parent` (an index + 1) is in, outermost
+/// first, each with its `.`: `Outer.Inner.` (the `depth` innermost).
+fn qualify(w: *std.Io.Writer, symbols: []const syntax.Symbol, text: []const u8, parent: u32, depth: u8) std.Io.Writer.Error!void {
+ if (parent == 0 or parent > symbols.len or depth == 0) return;
+ const up = symbols[parent - 1];
+ if (up.name_end > text.len) return;
+ try qualify(w, symbols, text, up.parent, depth - 1);
+ try w.print("{s}.", .{text[up.name_start..up.name_end]});
+}
+
/// What a Panes row of a closed pane ends with.
const closed_word = " (closed)";
diff --git a/core/Stream.zig b/core/Stream.zig
index e9e7793b..50c43ae4 100644
--- a/core/Stream.zig
+++ b/core/Stream.zig
@@ -67,10 +67,11 @@ pub const Batch = struct {
end: ?End = null,
/// A parse's own time on the worker (`parse_ns`).
took_ns: u64 = 0,
- /// A parse's answer (`parseFor`): the declarations of pane `serial`'s
- /// text at `revision`.
+ /// A parse's answer (`parseFor`): the declarations and symbols of pane
+ /// `serial`'s text at `revision`.
parsed: ?struct { serial: u32, revision: u32 } = null,
decls: []syntax.ContextDeclaration = &.{},
+ symbols: []syntax.Symbol = &.{},
/// A paint's answer (`paintAhead`): the colours of pane `serial`'s text
/// at `revision` from byte `start`, one syntax.Syn a byte.
painted: ?struct { serial: u32, revision: u32, start: usize } = null,
@@ -83,6 +84,7 @@ pub const Batch = struct {
pub fn deinit(b: *const Batch, gpa: std.mem.Allocator) void {
gpa.free(b.rows);
gpa.free(b.decls);
+ gpa.free(b.symbols);
gpa.free(b.styles);
}
};
@@ -480,9 +482,9 @@ pub fn parseFor(p: *Pardes, id: usize) void {
fn parseWork(io: std.Io, job: *TextJob, ctx: ?*anyopaque, sink: Sink) void {
const began = std.Io.Clock.awake.now(io);
- const decls: []syntax.ContextDeclaration = syntax.declarationsApart(job.out, job.path, job.source, &job.stop) catch @constCast(&[_]syntax.ContextDeclaration{});
+ const made: syntax.Context = syntax.contextApart(job.out, job.path, job.source, &job.stop) catch .{};
const took: u64 = @intCast(@max(0, began.durationTo(std.Io.Clock.awake.now(io)).nanoseconds));
- _ = sink(ctx, .{ .gen = job.gen, .decls = decls, .parsed = .{ .serial = job.serial, .revision = job.revision }, .end = .done, .took_ns = took });
+ _ = sink(ctx, .{ .gen = job.gen, .decls = made.declarations, .symbols = made.symbols, .parsed = .{ .serial = job.serial, .revision = job.revision }, .end = .done, .took_ns = took });
}
fn now() u64 {
@@ -732,12 +734,15 @@ fn receiveParse(p: *Pardes, b: *const Batch, serial: u32, revision: u32) void {
t.job.deinit();
};
s.parse_ns = b.took_ns;
- if (p.paneBySerial(serial)) |id| if (p.panes[id].?.file) |*f| if (f.revision == revision and b.decls.len > 0) {
- if (p.tree_sitter_gpa.dupe(syntax.ContextDeclaration, b.decls)) |copy| {
- f.context.replace(p.tree_sitter_gpa, copy, revision);
- panes.Query.declsArrived(p, serial);
- panes.Pick.declsArrived(p, serial);
- } else |_| {}
+ if (p.paneBySerial(serial)) |id| if (p.panes[id].?.file) |*f| if (f.revision == revision and (b.decls.len > 0 or b.symbols.len > 0)) kept: {
+ const decls = p.tree_sitter_gpa.dupe(syntax.ContextDeclaration, b.decls) catch break :kept;
+ const symbols = p.tree_sitter_gpa.dupe(syntax.Symbol, b.symbols) catch {
+ p.tree_sitter_gpa.free(decls);
+ break :kept;
+ };
+ f.context.replace(p.tree_sitter_gpa, .{ .declarations = decls, .symbols = symbols }, revision);
+ panes.Query.declsArrived(p, serial);
+ panes.Pick.declsArrived(p, serial);
};
p.needs_frame = true;
// A `Churn` waiting on these declarations (jj.zig).
diff --git a/core/colors.zig b/core/colors.zig
index eefb2b67..f9de60c9 100644
--- a/core/colors.zig
+++ b/core/colors.zig
@@ -1381,6 +1381,10 @@ pub const Roles = struct {
/// The letters a query matched: an ink, never a ground, 4.5:1 on every
/// tag ground and on the selection.
match: [3]u8,
+ /// A symbol's kind mark in a list (`t`, `f`, UX DESIGN N4): the
+ /// keyword's ink, which spells a kind in the text (`struct`, `fn`),
+ /// 4.5:1 on every tag ground and on the selection.
+ kind: [3]u8,
/// The body's places and a preview's landing line, and the current
/// one (its matched span): grounds off the page, its ink on them 4.5:1.
hit: [3]u8,
@@ -1429,6 +1433,7 @@ pub const Roles = struct {
const tag_grounds = [_][3]u8{ plain, focused, reading, r.selected[0].ground, r.selected[1].ground, r.selected[2].ground, r.selected[3].ground };
r.key = pushAway(th.box, &tag_grounds, ink_floor);
r.match = pushAway(matchHue(th), &tag_grounds, ink_floor);
+ r.kind = pushAway(th.kw, &tag_grounds, ink_floor);
const page = th.bg orelse null_page;
const body_ink = th.fg orelse th.tag_fg;
const dark = relativeLuminance(page) < 0.18;
@@ -2379,6 +2384,7 @@ test "every theme's walk UI roles meet their floors on every ground they are dra
}
try checks.append(a, .{ .what = "key", .got = leastContrast(r.key, &tags), .floor = @min(Roles.ink_floor, Reach.of(&tags)) });
try checks.append(a, .{ .what = "match", .got = leastContrast(r.match, &tags), .floor = @min(Roles.ink_floor, Reach.of(&tags)) });
+ try checks.append(a, .{ .what = "kind", .got = leastContrast(r.kind, &tags), .floor = @min(Roles.ink_floor, Reach.of(&tags)) });
for (r.tag) |inks| {
try checks.append(a, .{ .what = "rule", .got = contrast(inks.rule, inks.ground), .floor = Roles.rule_floor });
try checks.append(a, .{ .what = "rule ceiling", .got = Roles.rule_ceiling - contrast(inks.rule, inks.ground), .floor = 0 });
diff --git a/core/draw.zig b/core/draw.zig
index b666fc15..447256a9 100644
--- a/core/draw.zig
+++ b/core/draw.zig
@@ -965,6 +965,7 @@ fn joinBand(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: R
if (b < part.row.chord) style.fg = .{ .rgb = chrome.roles.key };
if (b < part.row.pre) style.fg = .{ .rgb = if (active) chrome.tag_active_name_fg else chrome.tag_name_fg };
if (part.row.dim or (b >= part.row.pre and b < part.row.pre + part.row.faint) or (b >= part.row.quiet[0] and b < part.row.quiet[1])) style.fg = .{ .rgb = on.dim };
+ if (b < part.row.kind) style.fg = .{ .rgb = chrome.roles.kind };
for (part.row.keys) |k| if (k == b) {
style.fg = .{ .rgb = chrome.roles.key };
style.bold = true;
diff --git a/core/dump.zig b/core/dump.zig
index 2dde9c8c..663ee083 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -1379,7 +1379,7 @@ test "restored syntax context caches are rebuilt from the text rather than loade
const f = &pane.file.?;
const declarations = try p.tree_sitter_gpa.alloc(pardes.syntax.ContextDeclaration, 1);
@memset(std.mem.sliceAsBytes(declarations), 0);
- f.context.replace(p.tree_sitter_gpa, declarations, f.revision);
+ f.context.replace(p.tree_sitter_gpa, .{ .declarations = declarations }, f.revision);
// Older builds persisted these two fields; the schema reader must skip them too.
const OldFile = struct {
path: []const u8,
@@ -1405,13 +1405,14 @@ test "restored syntax context caches are rebuilt from the text rather than loade
defer gpa.free(bytes);
const q = try load(gpa, opts, bytes, null);
defer q.deinit();
- // This build's: the revision kept, the declarations parsed again from
- // the text, with the syntax allocator.
- const want = try pardes.syntax.contextDeclarations(syntax_gpa.allocator(), f.path, f.content);
- defer syntax_gpa.allocator().free(want);
+ // This build's: the revision kept, the declarations and the symbols
+ // parsed again from the text, with the syntax allocator.
+ var want = try pardes.syntax.context(syntax_gpa.allocator(), f.path, f.content);
+ defer want.deinit(syntax_gpa.allocator());
for (q.panes) |slot| if (slot) |restored| if (restored.file) |file| {
try std.testing.expectEqual(f.context.revision, file.context.revision);
- try std.testing.expectEqualSlices(pardes.syntax.ContextDeclaration, want, file.context.declarations);
+ try std.testing.expectEqualSlices(pardes.syntax.ContextDeclaration, want.declarations, file.context.declarations);
+ try std.testing.expectEqualSlices(pardes.syntax.Symbol, want.symbols, file.context.symbols);
};
}
diff --git a/core/root.zig b/core/root.zig
index 11cb5058..86ca62e0 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -461,6 +461,7 @@ test {
_ = @import("FrameStats.zig");
_ = @import("Query.zig");
_ = @import("Names.zig");
+ _ = @import("syntax.zig"); // its tests ran nowhere before
_ = @import("Stream.zig");
_ = @import("Tables.zig");
_ = @import("Handover.zig");
diff --git a/core/syntax.zig b/core/syntax.zig
index 5c05300e..5cdc2ff3 100644
--- a/core/syntax.zig
+++ b/core/syntax.zig
@@ -621,7 +621,7 @@ pub fn analyzeSource(gpa: std.mem.Allocator, path: []const u8, content: []const
defer tree.destroy();
var result: SourceAnalysis = .{};
errdefer result.deinit(gpa);
- if (want_declarations) result.declarations = try declarationsFromTree(gpa, content, tree, null);
+ if (want_declarations) result.declarations = (try contextFromTree(gpa, content, tree, null, &.{})).declarations;
if (want_colors) {
result.colors = try gpa.alloc(u8, content.len);
@memset(result.colors, 0);
@@ -635,23 +635,52 @@ pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: []
return analysis.declarations;
}
-/// The declarations of `content` (its path's language), on a worker
-/// (`parseApart`). `halt` ends the parse and the walk early
-/// (error.Canceled): a 1.2 MB file is seconds in a Debug build.
-pub fn declarationsApart(gpa: std.mem.Allocator, path: []const u8, content: []const u8, halt: *const std.atomic.Value(bool)) ![]ContextDeclaration {
- if (content.len == 0) return &.{};
+/// A text's context, from one parse: its declarations (the sticky
+/// headers', Locations') and its symbols (the Symbols picker's, UX DESIGN
+/// N), both of the same allocator.
+pub const Context = struct {
+ declarations: []ContextDeclaration = &.{},
+ symbols: []Symbol = &.{},
+
+ pub fn deinit(c: *Context, gpa: std.mem.Allocator) void {
+ gpa.free(c.declarations);
+ gpa.free(c.symbols);
+ c.* = .{};
+ }
+};
+
+/// `content`'s context (its path's language), parsed here: a sticky
+/// header's (File.refreshContext), a loaded text's.
+pub fn context(gpa: std.mem.Allocator, path: []const u8, content: []const u8) !Context {
+ if (content.len == 0) return .{};
+ const spec = byExt(std.Io.Dir.path.extension(path)) orelse return .{};
+ const selected = try ensure(spec);
+ const tree = selected.parser.parseString(content, null) orelse return .{};
+ defer tree.destroy();
+ return contextFromTree(gpa, content, tree, null, rulesOf(spec.name));
+}
+
+/// `content`'s context, on a worker (`parseApart`). `halt` ends the parse
+/// and the walk early (error.Canceled): a 1.2 MB file is seconds in a
+/// Debug build.
+pub fn contextApart(gpa: std.mem.Allocator, path: []const u8, content: []const u8, halt: *const std.atomic.Value(bool)) !Context {
+ if (content.len == 0) return .{};
const ext = std.Io.Dir.path.extension(path);
const spec = specs: for (&specs) |*spec| {
for (spec.exts) |choice| if (std.ascii.eqlIgnoreCase(ext, choice)) break :specs spec;
- } else return &.{};
+ } else return .{};
const tree = try parseApart(langOf(spec), content, halt);
defer tree.destroy();
- return declarationsFromTree(gpa, content, tree, halt);
+ return contextFromTree(gpa, content, tree, halt, rulesOf(spec.name));
}
-fn declarationsFromTree(gpa: std.mem.Allocator, content: []const u8, tree: *ts.Tree, halt: ?*const std.atomic.Value(bool)) ![]ContextDeclaration {
+/// The declarations and, by `rules` (none: no symbols), the symbols of a
+/// parse, in one walk of its nodes.
+fn contextFromTree(gpa: std.mem.Allocator, content: []const u8, tree: *ts.Tree, halt: ?*const std.atomic.Value(bool), rules: []const Rule) !Context {
var result: std.ArrayList(ContextDeclaration) = .empty;
errdefer result.deinit(gpa);
+ var symbols: SymbolWalk = .{ .gpa = gpa, .rules = rules, .source = content };
+ errdefer symbols.out.deinit(gpa);
// The cursor retains its ancestor stack: sibling visits do not repeatedly
// reconstruct parents in broad syntax trees. Preorder preserves source order.
var cursor = tree.rootNode().walk();
@@ -661,14 +690,21 @@ fn declarationsFromTree(gpa: std.mem.Allocator, content: []const u8, tree: *ts.T
visited += 1;
if (halt) |flag| if (visited % 4096 == 0 and flag.load(.monotonic)) return error.Canceled;
const node = cursor.node();
- if (node.isNamed()) if (contextSpan(node, content)) |span| {
- if (result.items.len == 0 or result.items[result.items.len - 1].start_line != span.start_line or
- result.items[result.items.len - 1].end_line != span.end_line)
- try result.append(gpa, span);
- };
+ if (node.isNamed()) {
+ if (contextSpan(node, content)) |span| {
+ if (result.items.len == 0 or result.items[result.items.len - 1].start_line != span.start_line or
+ result.items[result.items.len - 1].end_line != span.end_line)
+ try result.append(gpa, span);
+ }
+ if (rules.len > 0) try symbols.visit(node);
+ }
if (cursor.gotoFirstChild()) continue;
while (!cursor.gotoNextSibling()) {
- if (!cursor.gotoParent()) return result.toOwnedSlice(gpa);
+ if (!cursor.gotoParent()) {
+ const declarations = try result.toOwnedSlice(gpa);
+ errdefer gpa.free(declarations);
+ return .{ .declarations = declarations, .symbols = try symbols.out.toOwnedSlice(gpa) };
+ }
}
}
}
@@ -761,6 +797,527 @@ fn contextSpan(node: ts.Node, source: []const u8) ?ContextDeclaration {
};
}
+// ---- symbols: the Symbols picker's (UX DESIGN N) ----
+
+/// What a symbol is, in the Symbols picker's order (UX DESIGN N2): types,
+/// functions, fields, then the rest (consts, vars, modules, other) as one
+/// group. A `scope` is listed nowhere: it names its members (Rust's
+/// `impl S`: `S.new`).
+pub const SymbolKind = enum(u8) {
+ type,
+ function,
+ field,
+ constant,
+ variable,
+ module,
+ other,
+ scope,
+
+ /// Its mark in a row (UX DESIGN N4): one letter, `·` for the other.
+ pub fn mark(k: SymbolKind) []const u8 {
+ return switch (k) {
+ .type => "t",
+ .function => "f",
+ .field => "m",
+ .constant => "c",
+ .variable => "v",
+ .module => "n",
+ .other, .scope => "·",
+ };
+ }
+
+ /// Its group in the picker: 0 types, 1 functions, 2 fields, 3 the rest.
+ pub fn group(k: SymbolKind) u8 {
+ return @min(@intFromEnum(k), 3);
+ }
+};
+
+/// A declaration the Symbols picker lists: its kind, the line and bytes of
+/// its name, and the symbol it is declared in.
+pub const Symbol = struct {
+ kind: SymbolKind,
+ /// The line its name is on, from 0.
+ line: u32,
+ name_start: u32,
+ name_end: u32,
+ /// Where what its row says after its name ends (a function's
+ /// signature): its body's start, else its own end. Its row cuts it at
+ /// its name's line's end.
+ end: u32,
+ /// The symbol it is declared in, by its index + 1 (0: none): its name
+ /// qualifies this one's (`Counts.lines`).
+ parent: u32 = 0,
+};
+
+/// How a node of a grammar is a symbol (UX DESIGN N2: one table a language).
+const Rule = struct {
+ node: []const u8,
+ kind: SymbolKind,
+ how: How = .plain,
+ /// The field naming it; without it, its declarator's name (C's) or the
+ /// first name under it (`nameOf`). "": none (an anonymous scope).
+ name: []const u8 = "name",
+ /// A form's first words and the kinds they declare (`.head`).
+ heads: []const struct { []const u8, SymbolKind } = &.{},
+ /// Not one under a node of this kind (Pascal's declProc heading the
+ /// defProc that is the symbol).
+ unless_in: []const u8 = "",
+};
+
+const How = enum {
+ /// Its kind as given.
+ plain,
+ /// Only with a body (C's `struct s { ... }`; `struct s x;` names the
+ /// type, declares none); unnamed, a scope (an anonymous struct's fields
+ /// are its owner's).
+ body,
+ /// C's declaration: a function where a declarator on the way to its
+ /// name is one's; else a const where `const` says so (its kind a var).
+ declarator,
+ /// A binding whose value tells: a type, a function, a module (Zig's
+ /// `const S = struct`, `@import`, JavaScript's arrow function); else a
+ /// const or a var by its keyword.
+ value,
+ /// A binding that is a field in a type (a Python class's attribute,
+ /// Kotlin's property); else a const or a var by its keyword. Named
+ /// by a name, never a pattern (`self.x = ...`).
+ binding,
+ /// A form whose first word says what it declares (Elixir's `def f`,
+ /// Clojure's `(defn f ...)`), named by its second.
+ head,
+ /// No row: a scope its members are named in, by its own name (Rust's
+ /// `impl S`) or its owner's (an anonymous struct).
+ scope,
+};
+
+const c_rules = [_]Rule{
+ .{ .node = "function_definition", .kind = .function },
+ .{ .node = "declaration", .kind = .variable, .how = .declarator },
+ .{ .node = "field_declaration", .kind = .field, .how = .declarator },
+ .{ .node = "struct_specifier", .kind = .type, .how = .body },
+ .{ .node = "union_specifier", .kind = .type, .how = .body },
+ .{ .node = "enum_specifier", .kind = .type, .how = .body },
+ .{ .node = "enumerator", .kind = .field },
+ .{ .node = "type_definition", .kind = .type },
+ .{ .node = "preproc_def", .kind = .other },
+ .{ .node = "preproc_function_def", .kind = .other },
+};
+
+/// The kind tables, by grammar (grammar_manifest.zig): a grammar with none
+/// (JSON, CSS, HTML, Markdown, Typst) lists no symbols.
+const symbol_rules = [_]struct { []const u8, []const Rule }{
+ .{ "zig", &.{
+ // Named by its FnProto's `function` (symbolOf).
+ .{ .node = "Decl", .kind = .function, .name = "" },
+ .{ .node = "VarDecl", .kind = .variable, .how = .value, .name = "variable_type_function" },
+ .{ .node = "ContainerField", .kind = .field },
+ .{ .node = "TestDecl", .kind = .other, .name = "" },
+ .{ .node = "ContainerDecl", .kind = .type, .how = .scope, .name = "" },
+ } },
+ .{ "c", &c_rules },
+ .{ "cpp", &(c_rules ++ [_]Rule{
+ .{ .node = "class_specifier", .kind = .type, .how = .body },
+ .{ .node = "namespace_definition", .kind = .module },
+ .{ .node = "alias_declaration", .kind = .type },
+ }) },
+ .{ "rust", &.{
+ .{ .node = "function_item", .kind = .function },
+ .{ .node = "function_signature_item", .kind = .function },
+ .{ .node = "struct_item", .kind = .type },
+ .{ .node = "enum_item", .kind = .type },
+ .{ .node = "union_item", .kind = .type },
+ .{ .node = "trait_item", .kind = .type },
+ .{ .node = "type_item", .kind = .type },
+ .{ .node = "impl_item", .kind = .type, .how = .scope, .name = "type" },
+ .{ .node = "field_declaration", .kind = .field },
+ .{ .node = "enum_variant", .kind = .field },
+ .{ .node = "const_item", .kind = .constant },
+ .{ .node = "static_item", .kind = .variable },
+ .{ .node = "mod_item", .kind = .module },
+ .{ .node = "macro_definition", .kind = .other },
+ } },
+ .{ "go", &.{
+ .{ .node = "function_declaration", .kind = .function },
+ .{ .node = "method_declaration", .kind = .function },
+ .{ .node = "method_elem", .kind = .function },
+ .{ .node = "type_spec", .kind = .type },
+ .{ .node = "type_alias", .kind = .type },
+ .{ .node = "field_declaration", .kind = .field },
+ .{ .node = "const_spec", .kind = .constant },
+ .{ .node = "var_spec", .kind = .variable },
+ } },
+ .{ "python", &.{
+ .{ .node = "class_definition", .kind = .type },
+ .{ .node = "function_definition", .kind = .function },
+ .{ .node = "assignment", .kind = .variable, .how = .binding, .name = "left" },
+ } },
+ .{ "javascript", &.{
+ .{ .node = "function_declaration", .kind = .function },
+ .{ .node = "generator_function_declaration", .kind = .function },
+ .{ .node = "class_declaration", .kind = .type },
+ .{ .node = "method_definition", .kind = .function },
+ .{ .node = "field_definition", .kind = .field, .name = "property" },
+ .{ .node = "variable_declarator", .kind = .variable, .how = .value },
+ } },
+ .{ "java", &.{
+ .{ .node = "class_declaration", .kind = .type },
+ .{ .node = "interface_declaration", .kind = .type },
+ .{ .node = "enum_declaration", .kind = .type },
+ .{ .node = "record_declaration", .kind = .type },
+ .{ .node = "annotation_type_declaration", .kind = .type },
+ .{ .node = "method_declaration", .kind = .function },
+ .{ .node = "constructor_declaration", .kind = .function },
+ .{ .node = "field_declaration", .kind = .field },
+ .{ .node = "enum_constant", .kind = .field },
+ .{ .node = "constant_declaration", .kind = .constant },
+ } },
+ .{ "c_sharp", &.{
+ .{ .node = "class_declaration", .kind = .type },
+ .{ .node = "struct_declaration", .kind = .type },
+ .{ .node = "interface_declaration", .kind = .type },
+ .{ .node = "enum_declaration", .kind = .type },
+ .{ .node = "record_declaration", .kind = .type },
+ .{ .node = "delegate_declaration", .kind = .type },
+ .{ .node = "namespace_declaration", .kind = .module },
+ .{ .node = "file_scoped_namespace_declaration", .kind = .module },
+ .{ .node = "method_declaration", .kind = .function },
+ .{ .node = "constructor_declaration", .kind = .function },
+ .{ .node = "destructor_declaration", .kind = .function },
+ .{ .node = "field_declaration", .kind = .field },
+ .{ .node = "property_declaration", .kind = .field },
+ .{ .node = "event_field_declaration", .kind = .field },
+ .{ .node = "enum_member_declaration", .kind = .field },
+ } },
+ .{ "kotlin", &.{
+ .{ .node = "class_declaration", .kind = .type },
+ .{ .node = "object_declaration", .kind = .type },
+ .{ .node = "companion_object", .kind = .type, .how = .scope, .name = "" },
+ .{ .node = "function_declaration", .kind = .function },
+ .{ .node = "property_declaration", .kind = .variable, .how = .binding },
+ .{ .node = "type_alias", .kind = .type },
+ .{ .node = "enum_entry", .kind = .field },
+ } },
+ .{ "scala", &.{
+ .{ .node = "class_definition", .kind = .type },
+ .{ .node = "object_definition", .kind = .type },
+ .{ .node = "trait_definition", .kind = .type },
+ .{ .node = "enum_definition", .kind = .type },
+ .{ .node = "type_definition", .kind = .type },
+ .{ .node = "function_definition", .kind = .function },
+ .{ .node = "function_declaration", .kind = .function },
+ .{ .node = "val_definition", .kind = .constant, .how = .binding, .name = "pattern" },
+ .{ .node = "var_definition", .kind = .variable, .how = .binding, .name = "pattern" },
+ .{ .node = "simple_enum_case", .kind = .field },
+ .{ .node = "full_enum_case", .kind = .field },
+ } },
+ .{ "ruby", &.{
+ .{ .node = "class", .kind = .type },
+ .{ .node = "singleton_class", .kind = .type, .how = .scope, .name = "" },
+ .{ .node = "module", .kind = .module },
+ .{ .node = "method", .kind = .function },
+ .{ .node = "singleton_method", .kind = .function },
+ } },
+ .{ "php", &.{
+ .{ .node = "class_declaration", .kind = .type },
+ .{ .node = "interface_declaration", .kind = .type },
+ .{ .node = "trait_declaration", .kind = .type },
+ .{ .node = "enum_declaration", .kind = .type },
+ .{ .node = "function_definition", .kind = .function },
+ .{ .node = "method_declaration", .kind = .function },
+ .{ .node = "property_declaration", .kind = .field },
+ .{ .node = "enum_case", .kind = .field },
+ .{ .node = "const_declaration", .kind = .constant },
+ .{ .node = "namespace_definition", .kind = .module },
+ } },
+ .{ "bash", &.{
+ .{ .node = "function_definition", .kind = .function },
+ .{ .node = "variable_assignment", .kind = .variable, .how = .binding },
+ } },
+ .{ "haskell", &.{
+ .{ .node = "data_type", .kind = .type },
+ .{ .node = "newtype", .kind = .type },
+ .{ .node = "type_synomym", .kind = .type },
+ .{ .node = "class", .kind = .type },
+ .{ .node = "instance", .kind = .type, .how = .scope },
+ .{ .node = "function", .kind = .function },
+ .{ .node = "bind", .kind = .constant },
+ .{ .node = "data_constructor", .kind = .field },
+ } },
+ .{ "ocaml", &.{
+ .{ .node = "type_binding", .kind = .type },
+ .{ .node = "module_binding", .kind = .module },
+ .{ .node = "module_type_definition", .kind = .type },
+ .{ .node = "class_binding", .kind = .type },
+ .{ .node = "method_definition", .kind = .function },
+ .{ .node = "let_binding", .kind = .constant, .how = .value, .name = "pattern" },
+ .{ .node = "field_declaration", .kind = .field },
+ .{ .node = "constructor_declaration", .kind = .field },
+ } },
+ .{ "erlang", &.{
+ .{ .node = "fun_decl", .kind = .function },
+ .{ .node = "record_decl", .kind = .type },
+ .{ .node = "record_field", .kind = .field },
+ .{ .node = "type_alias", .kind = .type },
+ .{ .node = "pp_define", .kind = .other },
+ .{ .node = "module_attribute", .kind = .module },
+ } },
+ .{ "elixir", &.{
+ .{ .node = "call", .kind = .other, .how = .head, .heads = &.{
+ .{ "defmodule", .module }, .{ "defprotocol", .type }, .{ "def", .function },
+ .{ "defp", .function }, .{ "defdelegate", .function }, .{ "defguard", .function },
+ .{ "defguardp", .function }, .{ "defmacro", .other }, .{ "defmacrop", .other },
+ } },
+ } },
+ .{ "clojure", &.{
+ .{ .node = "list_lit", .kind = .other, .how = .head, .heads = &.{
+ .{ "ns", .module }, .{ "def", .constant }, .{ "defonce", .constant }, .{ "defn", .function },
+ .{ "defn-", .function }, .{ "defmulti", .function }, .{ "defmethod", .function }, .{ "defmacro", .other },
+ .{ "defrecord", .type }, .{ "deftype", .type }, .{ "defprotocol", .type }, .{ "definterface", .type },
+ .{ "defstruct", .type },
+ } },
+ } },
+ .{ "fortran", &.{
+ .{ .node = "module", .kind = .module },
+ .{ .node = "program", .kind = .module },
+ .{ .node = "subroutine", .kind = .function },
+ .{ .node = "function", .kind = .function },
+ .{ .node = "derived_type_definition", .kind = .type },
+ .{ .node = "variable_declaration", .kind = .variable, .how = .binding },
+ } },
+ .{ "ada", &.{
+ .{ .node = "package_declaration", .kind = .module },
+ .{ .node = "package_body", .kind = .module },
+ .{ .node = "full_type_declaration", .kind = .type },
+ .{ .node = "subprogram_declaration", .kind = .function },
+ .{ .node = "subprogram_body", .kind = .function },
+ .{ .node = "object_declaration", .kind = .variable, .how = .binding },
+ .{ .node = "component_declaration", .kind = .field },
+ } },
+ .{ "pascal", &.{
+ .{ .node = "declType", .kind = .type },
+ .{ .node = "declProc", .kind = .function, .unless_in = "defProc" },
+ .{ .node = "defProc", .kind = .function },
+ .{ .node = "declConst", .kind = .constant },
+ .{ .node = "declVar", .kind = .variable, .how = .binding },
+ .{ .node = "declField", .kind = .field },
+ } },
+ .{ "powershell", &.{
+ .{ .node = "function_statement", .kind = .function },
+ .{ .node = "class_statement", .kind = .type },
+ .{ .node = "class_method_definition", .kind = .function },
+ .{ .node = "class_property_definition", .kind = .field },
+ .{ .node = "enum_statement", .kind = .type },
+ .{ .node = "enum_member", .kind = .field },
+ } },
+};
+
+fn rulesOf(grammar: []const u8) []const Rule {
+ for (symbol_rules) |entry| if (std.mem.eql(u8, entry[0], grammar)) return entry[1];
+ return &.{};
+}
+
+/// A walk's symbols, node by node in preorder (`contextFromTree`).
+const SymbolWalk = struct {
+ gpa: std.mem.Allocator,
+ rules: []const Rule,
+ source: []const u8,
+ out: std.ArrayList(Symbol) = .empty,
+ /// The scopes the node is in, the innermost last.
+ scopes: [max_scopes]Scope = undefined,
+ depth: u8 = 0,
+
+ /// Where a scope ends, its kind, and the symbol its members are named
+ /// in (an index + 1, 0 none).
+ const Scope = struct { end: u32, kind: SymbolKind, symbol: u32 };
+ /// Deeper scopes are their parent's.
+ const max_scopes = 32;
+
+ fn visit(w: *SymbolWalk, node: ts.Node) !void {
+ while (w.depth > 0 and w.scopes[w.depth - 1].end <= node.startByte()) w.depth -= 1;
+ const in: Scope = if (w.depth > 0) w.scopes[w.depth - 1] else .{ .end = 0, .kind = .module, .symbol = 0 };
+ const kind_name = node.kind();
+ const rule = for (w.rules) |r| {
+ if (std.mem.eql(u8, r.node, kind_name)) break r;
+ } else return;
+ const found = symbolOf(rule, node, w.source, in.kind) orelse return;
+ // A body's consts and vars are its locals, none of them listed.
+ const local = in.kind != .type and in.kind != .module and in.kind != .scope;
+ if (local and (found.kind == .constant or found.kind == .variable)) return;
+ var named = in.symbol;
+ if (found.name) |name| {
+ try w.out.append(w.gpa, .{
+ .kind = found.kind,
+ .line = name.startPoint().row,
+ .name_start = name.startByte(),
+ .name_end = name.endByte(),
+ .end = found.end,
+ .parent = in.symbol,
+ });
+ // A const's or a field's members are not named in it.
+ if (found.kind == .type or found.kind == .function or found.kind == .module or found.kind == .scope) named = @intCast(w.out.items.len);
+ }
+ if (w.depth == max_scopes) return;
+ w.scopes[w.depth] = .{ .end = node.endByte(), .kind = if (found.kind == .scope) rule.kind else found.kind, .symbol = named };
+ w.depth += 1;
+ }
+};
+
+/// What node `node` declares by `rule`, in a scope of kind `in`: its kind,
+/// its name (null: an anonymous scope) and where its row's words end.
+fn symbolOf(rule: Rule, node: ts.Node, source: []const u8, in: SymbolKind) ?struct { kind: SymbolKind, name: ?ts.Node, end: u32 } {
+ if (rule.unless_in.len > 0) if (node.parent()) |up| if (std.mem.eql(u8, up.kind(), rule.unless_in)) return null;
+ var kind = rule.kind;
+ var name: ?ts.Node = null;
+ var end = if (node.childByFieldName("body")) |body| body.startByte() else node.endByte();
+ switch (rule.how) {
+ .plain => name = nameOf(node, rule.name),
+ .scope => {
+ name = nameOf(node, rule.name);
+ kind = .scope;
+ },
+ .body => {
+ if (node.childByFieldName("body") == null) return null;
+ name = nameOf(node, rule.name);
+ if (name == null) kind = .scope;
+ },
+ .declarator => {
+ var d = node;
+ while (d.childByFieldName("declarator")) |next| {
+ if (std.mem.eql(u8, next.kind(), "function_declarator")) kind = .function;
+ d = next;
+ }
+ name = nameOf(node, rule.name);
+ if (kind == .variable and constant(source, node.startByte(), name orelse return null)) kind = .constant;
+ },
+ .value => {
+ name = nameOf(node, rule.name);
+ kind = valueKind(node, source) orelse kind;
+ // JavaScript's keyword is its declaration's (`const a = 1, b`).
+ const from = if (std.mem.eql(u8, rule.node, "variable_declarator")) (node.parent() orelse node).startByte() else node.startByte();
+ if (kind == .variable and constant(source, from, name orelse return null)) kind = .constant;
+ },
+ .binding => {
+ const n = node.childByFieldName(rule.name) orelse nameOf(node, rule.name) orelse return null;
+ if (!nameLike(n.kind())) return null;
+ name = n;
+ if (in == .type) kind = .field else if (kind == .variable and constant(source, node.startByte(), n)) kind = .constant;
+ },
+ .head => {
+ const elixir = std.mem.eql(u8, rule.node, "call");
+ const first = (if (elixir) node.childByFieldName("target") else node.namedChild(0)) orelse return null;
+ const word = source[first.startByte()..first.endByte()];
+ kind = for (rule.heads) |h| {
+ if (std.mem.eql(u8, h[0], word)) break h[1];
+ } else return null;
+ var second = (if (elixir) childOfKind(node, "arguments") else node.namedChild(1)) orelse return null;
+ if (elixir) second = second.namedChild(0) orelse return null;
+ if (second.childByFieldName("target")) |target| second = target;
+ name = if (nameLike(second.kind())) second else nameOf(second, "name");
+ },
+ }
+ // Zig's: a function's name is its prototype's, its body a Block; a
+ // test's its string.
+ if (std.mem.eql(u8, rule.node, "Decl")) {
+ const proto = childOfKind(node, "FnProto") orelse return null;
+ name = proto.childByFieldName("function");
+ if (childOfKind(node, "Block")) |block| end = block.startByte();
+ } else if (std.mem.eql(u8, rule.node, "TestDecl")) {
+ const first = node.namedChild(0) orelse return null;
+ if (std.mem.eql(u8, first.kind(), "Block")) return null;
+ name = first;
+ if (childOfKind(node, "Block")) |block| end = block.startByte();
+ }
+ if (name == null and kind != .scope) return null;
+ if (name) |n| if (n.endByte() <= n.startByte() or n.endByte() - n.startByte() > max_name) return null;
+ return .{ .kind = kind, .name = name, .end = end };
+}
+
+/// The longest name a symbol has: a longer one is no name.
+const max_name = 200;
+
+/// The node naming `node`: its field `field`; without one, its declarator's
+/// (C's `int *f(void)`: `f`); else the first name under it, past its
+/// type, value, body and parameters (Kotlin's, Fortran's).
+fn nameOf(node: ts.Node, field: []const u8) ?ts.Node {
+ if (field.len == 0) return null;
+ var n = node;
+ if (node.childByFieldName(field)) |f| n = f else while (n.childByFieldName("declarator")) |d| n = d;
+ if (nameLike(n.kind())) return n;
+ if (n.childByFieldName("name")) |f| if (nameLike(f.kind())) return f;
+ return firstName(n, 3);
+}
+
+fn firstName(node: ts.Node, depth: u8) ?ts.Node {
+ if (depth == 0) return null;
+ const skipped = [_][]const u8{ "type", "value", "body", "parameters", "return_type", "returns", "result", "superclass", "arguments", "default", "trait" };
+ var i: u32 = 0;
+ while (i < node.childCount()) : (i += 1) {
+ const child = node.child(i) orelse continue;
+ if (!child.isNamed()) continue;
+ const field = node.fieldNameForChild(i) orelse "";
+ if (for (skipped) |s| {
+ if (std.mem.eql(u8, s, field)) break true;
+ } else false) continue;
+ const kind = child.kind();
+ if (std.mem.indexOf(u8, kind, "modifier") != null or std.mem.indexOf(u8, kind, "annotation") != null or
+ std.mem.indexOf(u8, kind, "parameter") != null or std.mem.indexOf(u8, kind, "attribute") != null or
+ std.mem.indexOf(u8, kind, "decorator") != null or std.mem.indexOf(u8, kind, "comment") != null or
+ std.mem.indexOf(u8, kind, "literal") != null) continue;
+ if (nameLike(kind)) return child;
+ if (firstName(child, depth - 1)) |found| return found;
+ }
+ return null;
+}
+
+/// A node kind that is a name: an identifier, a `*_name`, a word.
+fn nameLike(kind: []const u8) bool {
+ if (std.ascii.endsWithIgnoreCase(kind, "identifier") or std.mem.endsWith(u8, kind, "name")) return true;
+ for ([_][]const u8{ "word", "constant", "atom", "variable", "constructor", "type_constructor", "alias" }) |k| {
+ if (std.mem.eql(u8, kind, k)) return true;
+ }
+ return false;
+}
+
+/// What a binding's value makes it, where it says (else null): Zig's
+/// `struct {...}`, `error{...}`, `@This()`, `@Type(...)` a type and
+/// `@import(...)` a module; JavaScript's function a function and class a
+/// type; OCaml's `let f x = ...` (a parameter) a function.
+fn valueKind(node: ts.Node, source: []const u8) ?SymbolKind {
+ if (node.childByFieldName("value")) |value| {
+ const kind = value.kind();
+ for ([_][]const u8{ "arrow_function", "function_expression", "generator_function" }) |k| if (std.mem.eql(u8, kind, k)) return .function;
+ if (std.mem.eql(u8, kind, "class")) return .type;
+ return null;
+ }
+ if (childOfKind(node, "parameter") != null) return .function;
+ // Zig's value: the last of the VarDecl, under its ErrorUnionExpr.
+ var v = node.namedChild(node.namedChildCount() -| 1) orelse return null;
+ while (std.mem.eql(u8, v.kind(), "ErrorUnionExpr")) v = v.namedChild(0) orelse return null;
+ if (!std.mem.eql(u8, v.kind(), "SuffixExpr")) return null;
+ const first = v.namedChild(0) orelse return null;
+ const kind = first.kind();
+ if (std.mem.eql(u8, kind, "ContainerDecl") or std.mem.eql(u8, kind, "ErrorSetDecl")) return .type;
+ if (!std.mem.eql(u8, kind, "BUILTINIDENTIFIER")) return null;
+ const builtin = source[first.startByte()..first.endByte()];
+ if (std.mem.eql(u8, builtin, "@This") or std.mem.eql(u8, builtin, "@Type")) return .type;
+ if ((std.mem.eql(u8, builtin, "@import") or std.mem.eql(u8, builtin, "@cImport")) and v.namedChildCount() == 2) return .module;
+ return null;
+}
+
+/// Whether a binding is a const: a keyword says so between `from` and its
+/// name, or after the name before its value (Ada's `K : constant`).
+fn constant(source: []const u8, from: usize, name: ts.Node) bool {
+ const after = source[name.endByte()..];
+ const before_value = std.mem.indexOfAny(u8, after, "=\n") orelse after.len;
+ for ([_][]const u8{ source[@min(from, name.startByte())..name.startByte()], after[0..before_value] }) |text| {
+ var words = std.mem.tokenizeAny(u8, text, " \t\r\n,:()*&");
+ while (words.next()) |word| for ([_][]const u8{ "const", "constexpr", "val", "final", "readonly", "parameter", "constant" }) |k| {
+ if (std.mem.eql(u8, word, k)) return true;
+ };
+ }
+ return false;
+}
+
fn paint(styles: []u8, source: []const u8, selected: Selected) void {
const tree = selected.parser.parseString(source, null) orelse return;
defer tree.destroy();
@@ -2180,3 +2737,123 @@ test "syntax: a grammar handed in at run time colours and walks as the one compi
forgetLanguages();
try std.testing.expect(!supportsPath("x.mine"));
}
+
+/// Each of `source`'s symbols as `mark qualified name`, in the walk's order.
+fn symbolLines(gpa: std.mem.Allocator, path: []const u8, source: []const u8) ![]const u8 {
+ var made = try context(gpa, path, source);
+ defer made.deinit(gpa);
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ defer out.deinit();
+ for (made.symbols) |sym| {
+ if (sym.kind == .scope) continue;
+ try out.writer.print("{s} ", .{sym.kind.mark()});
+ var chain: [8]u32 = undefined;
+ var n: usize = 0;
+ var up = sym.parent;
+ while (up != 0 and n < chain.len) : (up = made.symbols[up - 1].parent) {
+ chain[n] = up;
+ n += 1;
+ }
+ while (n > 0) {
+ n -= 1;
+ const s = made.symbols[chain[n] - 1];
+ try out.writer.print("{s}.", .{source[s.name_start..s.name_end]});
+ }
+ try out.writer.print("{s}\n", .{source[sym.name_start..sym.name_end]});
+ }
+ return out.toOwnedSlice();
+}
+
+test "syntax symbols: a Zig file's types, functions, fields and the rest by their declarations and values, each named in the containers it is in; a function's locals and an unnamed test none of them (UX DESIGN N2)" {
+ if (comptime !minimal_grammars) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ start(gpa);
+ defer stop();
+ const source =
+ \\const std = @import("std");
+ \\pub const Counts = struct {
+ \\ lines: usize = 0,
+ \\ pub const zero: Counts = .{};
+ \\ pub fn add(c: *Counts) void {
+ \\ const local = 1;
+ \\ c.lines += local;
+ \\ }
+ \\};
+ \\const Mode = enum { fast, slow };
+ \\const Failure = error{ Late, Lost };
+ \\const Self = @This();
+ \\var hits: u32 = 0;
+ \\fn List(comptime T: type) type {
+ \\ return struct { items: []T };
+ \\}
+ \\test "count" {}
+ \\test {}
+ \\extern fn tick() void;
+ \\
+ ;
+ const lines = try symbolLines(gpa, "a.zig", source);
+ defer gpa.free(lines);
+ try std.testing.expectEqualStrings(
+ \\n std
+ \\t Counts
+ \\m Counts.lines
+ \\c Counts.zero
+ \\f Counts.add
+ \\t Mode
+ \\m Mode.fast
+ \\m Mode.slow
+ \\t Failure
+ \\t Self
+ \\v hits
+ \\f List
+ \\m List.items
+ \\· "count"
+ \\f tick
+ \\
+ , lines);
+}
+
+test "syntax symbols: C, C++, Rust, Go, Python and JavaScript by their kind tables, members named in their types, an impl's in its type, locals none" {
+ if (!full_grammars) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ start(gpa);
+ defer stop();
+ const cases = [_]struct { path: []const u8, source: []const u8, want: []const u8 }{
+ .{ .path = "a.c", .source = "#define LIMIT 4\nstruct point { int x; int *y; };\ntypedef struct { int a; } pair;\nenum color { RED };\nstatic int counter = 0;\nconst int limit = 4;\nint add(int a) { int local = a; return local; }\nint later(void);\nstruct point p;\n", .want = "· LIMIT\nt point\nm point.x\nm point.y\nt pair\nm pair.a\nt color\nm color.RED\nv counter\nc limit\nf add\nf later\nv p\n" },
+ .{ .path = "a.cc", .source = "namespace torque {\nclass Parser : public Base {\n public:\n Parser();\n int Parse(int depth) const { return depth; }\n int depth_;\n};\nint Parser::Run(int n) { int local = n; return local; }\nusing Alias = int;\n}\n", .want = "n torque\nt torque.Parser\nf torque.Parser.Parser\nf torque.Parser.Parse\nm torque.Parser.depth_\nf torque.Parser::Run\nt torque.Alias\n" },
+ .{ .path = "a.rs", .source = "mod m {\npub struct S { pub a: u32 }\nenum E { A, B(u32) }\ntrait T { fn f(&self); }\nimpl S { pub fn new() -> Self { let x = 1; S { a: x } } }\nconst C: u32 = 1;\nstatic G: u32 = 2;\nmacro_rules! mac { () => {} }\n}\n", .want = "n m\nt m.S\nm m.S.a\nt m.E\nm m.E.A\nm m.E.B\nt m.T\nf m.T.f\nf m.S.new\nc m.C\nv m.G\n· m.mac\n" },
+ .{ .path = "a.go", .source = "package main\ntype S struct { A int }\ntype I interface { M() }\nconst C = 1\nvar V = 2\nfunc F() { var x = 1; _ = x }\nfunc (s *S) M() {}\n", .want = "t S\nm S.A\nt I\nf I.M\nc C\nv V\nf F\nf M\n" },
+ .{ .path = "a.py", .source = "X = 1\nclass C:\n attr = 2\n def m(self):\n y = 3\n self.z = 4\ndef f():\n pass\n", .want = "v X\nt C\nm C.attr\nf C.m\nf f\n" },
+ .{ .path = "a.js", .source = "const A = 1;\nlet b = 2;\nfunction f() { const local = 1; }\nclass K { field = 1; m() {} }\nconst arrow = () => 1;\nconst Klass = class {};\n", .want = "c A\nv b\nf f\nt K\nm K.field\nf K.m\nf arrow\nt Klass\n" },
+ };
+ for (cases) |case| {
+ const lines = try symbolLines(gpa, case.path, case.source);
+ defer gpa.free(lines);
+ std.testing.expectEqualStrings(case.want, lines) catch |err| {
+ std.debug.print("in {s}\n", .{case.path});
+ return err;
+ };
+ }
+}
+
+test "syntax symbols: every kind table names nodes of its grammar, and a grammar with none (JSON) lists no symbol" {
+ if (!full_grammars) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ start(gpa);
+ defer stop();
+ var tables: usize = 0;
+ for (symbol_rules) |entry| {
+ const spec = for (&specs) |*spec| {
+ if (std.mem.eql(u8, spec.name, entry[0])) break spec;
+ } else return error.NoGrammar;
+ for (entry[1]) |rule| std.testing.expect(langOf(spec).idForNodeKind(rule.node, true) != 0) catch |err| {
+ std.debug.print("{s} has no node {s}\n", .{ entry[0], rule.node });
+ return err;
+ };
+ tables += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 23), tables);
+ var made = try context(gpa, "a.json", "{\"a\": 1}\n");
+ defer made.deinit(gpa);
+ try std.testing.expectEqual(@as(usize, 0), made.symbols.len);
+}