summaryrefslogtreecommitdiff
path: root/src/syntax.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/syntax.zig')
-rw-r--r--src/syntax.zig206
1 files changed, 148 insertions, 58 deletions
diff --git a/src/syntax.zig b/src/syntax.zig
index 8533aaa9..3f75c4be 100644
--- a/src/syntax.zig
+++ b/src/syntax.zig
@@ -30,7 +30,9 @@ const Lazy = struct { src: []const u8 = "", query: ?*ts.Query = null, failed: bo
const Spec = struct {
name: []const u8,
exts: []const []const u8,
- language: *const fn () callconv(.c) *const ts.Language,
+ /// A compiled-in grammar's, else `lang`, one handed in at run time.
+ language: ?LanguageFn = null,
+ lang: ?*const ts.Language = null,
query_src: []const u8,
/// helix's textobjects.scm and indents.scm for the grammar
/// (vendor/queries), compiled the first time they are asked for
@@ -102,18 +104,8 @@ pub fn start(gpa: std.mem.Allocator) void {
pub fn stop() void {
if (comptime enabled) {
- for (&specs) |*spec| {
- if (spec.selected) |selected| {
- selected.cursor.destroy();
- selected.parser.destroy();
- selected.query.destroy();
- }
- spec.selected = null;
- for ([_]*Lazy{ &spec.objects, &spec.indents }) |lazy| {
- if (lazy.query) |q| q.destroy();
- lazy.* = .{ .src = lazy.src };
- }
- }
+ for (&specs) |*spec| dropSpec(spec);
+ forgetLanguages();
for (&diff_pieces) |*slot| {
if (slot.*) |piece| syntax_allocator.free(piece.styles);
slot.* = null;
@@ -134,9 +126,89 @@ const Selected = struct {
capture_styles: []u8,
};
+fn langOf(spec: *const Spec) *const ts.Language {
+ return spec.lang orelse spec.language.?();
+}
+
+/// A grammar handed in at run time, beside the compiled-in ones: a
+/// program's own (a sketch's language), its tree-sitter language and its
+/// queries' sources, told by its extension (`.dsl`) as theirs are by
+/// theirs. What it points at is the caller's: `forgetLanguages` before
+/// the code it is in goes (a reload).
+pub const Language = struct {
+ name: []const u8,
+ ext: []const u8,
+ ts: *const ts.Language,
+ highlights: []const u8 = "",
+ textobjects: []const u8 = "",
+ indents: []const u8 = "",
+
+ /// A path its extension tells, in `buf`.
+ pub fn path(l: Language, buf: []u8) []const u8 {
+ return std.fmt.bufPrint(buf, "a{s}", .{l.ext}) catch "";
+ }
+};
+
+var handed: [8]Spec = undefined;
+var handed_exts: [8][1][]const u8 = undefined;
+var handed_n: usize = 0;
+
+/// `l` told by its extension from now on; one already told by it is
+/// replaced (its parser and queries made again) unless it is the same.
+/// False when eight are told already.
+pub fn addLanguage(l: Language) bool {
+ const at = for (handed[0..handed_n], 0..) |*spec, i| {
+ if (std.mem.eql(u8, spec.exts[0], l.ext)) {
+ if (spec.lang == l.ts and spec.query_src.ptr == l.highlights.ptr and spec.objects.src.ptr == l.textobjects.ptr) return true;
+ dropSpec(spec);
+ break i;
+ }
+ } else if (handed_n == handed.len) return false else handed_n;
+ handed_exts[at] = .{l.ext};
+ handed[at] = .{
+ .name = l.name,
+ .exts = &handed_exts[at],
+ .lang = l.ts,
+ .query_src = l.highlights,
+ .objects = .{ .src = l.textobjects },
+ .indents = .{ .src = l.indents },
+ };
+ handed_n = @max(handed_n, at + 1);
+ return true;
+}
+
+/// Every grammar handed in at run time gone, with the parsers and queries
+/// made for it.
+pub fn forgetLanguages() void {
+ for (handed[0..handed_n]) |*spec| dropSpec(spec);
+ handed_n = 0;
+}
+
+fn dropSpec(spec: *Spec) void {
+ if (spec.selected) |selected| {
+ selected.cursor.destroy();
+ selected.parser.destroy();
+ selected.query.destroy();
+ }
+ spec.selected = null;
+ for ([_]*Lazy{ &spec.objects, &spec.indents }) |lazy| {
+ if (lazy.query) |q| q.destroy();
+ lazy.* = .{ .src = lazy.src };
+ }
+}
+
+/// The grammar a file's extension names: compiled in, else handed in.
+fn byExt(ext: []const u8) ?*Spec {
+ for (&specs) |*spec| for (spec.exts) |choice| {
+ if (std.ascii.eqlIgnoreCase(ext, choice)) return spec;
+ };
+ for (handed[0..handed_n]) |*spec| if (std.ascii.eqlIgnoreCase(ext, spec.exts[0])) return spec;
+ return null;
+}
+
fn ensure(spec: *Spec) !Selected {
if (spec.selected) |selected| return selected;
- const lang = spec.language();
+ const lang = langOf(spec);
var error_offset: u32 = 0;
const query = try ts.Query.create(lang, spec.query_src, &error_offset);
errdefer query.destroy();
@@ -163,12 +235,7 @@ fn ensure(spec: *Spec) !Selected {
}
fn forExt(ext: []const u8) !?Selected {
- for (&specs) |*spec| {
- for (spec.exts) |choice| {
- if (std.ascii.eqlIgnoreCase(ext, choice)) return try ensure(spec);
- }
- }
- return null;
+ return try ensure(byExt(ext) orelse return null);
}
fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void {
@@ -270,11 +337,7 @@ pub const ContextDeclaration = struct {
pub fn supportsPath(path: []const u8) bool {
if (!enabled) return false;
- const ext = std.Io.Dir.path.extension(path);
- for (specs) |spec| for (spec.exts) |choice| {
- if (std.ascii.eqlIgnoreCase(ext, choice)) return true;
- };
- return false;
+ return byExt(std.Io.Dir.path.extension(path)) != null;
}
/// A whole file's parse, kept by the file for the keys that walk its nodes
@@ -441,18 +504,14 @@ pub fn indentQuery(path: []const u8) ?struct { *ts.Query, []const u8 } {
}
fn specFor(path: []const u8) ?*Spec {
- const ext = std.Io.Dir.path.extension(path);
- for (&specs) |*spec| for (spec.exts) |choice| {
- if (std.ascii.eqlIgnoreCase(ext, choice)) return spec;
- };
- return null;
+ return byExt(std.Io.Dir.path.extension(path));
}
fn lazyQuery(spec: *Spec, lazy: *Lazy) ?*ts.Query {
if (lazy.query) |q| return q;
if (lazy.src.len == 0 or lazy.failed) return null;
var error_offset: u32 = 0;
- lazy.query = ts.Query.create(spec.language(), lazy.src, &error_offset) catch {
+ lazy.query = ts.Query.create(langOf(spec), lazy.src, &error_offset) catch {
lazy.failed = true;
return null;
};
@@ -600,7 +659,7 @@ pub fn declarationsApart(gpa: std.mem.Allocator, path: []const u8, content: []co
const spec = specs: for (&specs) |*spec| {
for (spec.exts) |choice| if (std.ascii.eqlIgnoreCase(ext, choice)) break :specs spec;
} else return &.{};
- const tree = try parseApart(spec.language(), content, halt);
+ const tree = try parseApart(langOf(spec), content, halt);
defer tree.destroy();
return declarationsFromTree(gpa, content, tree, halt);
}
@@ -933,16 +992,17 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node {
return null;
}
-/// A diff line's style byte carries whether the line was added or removed
-/// over its syntax style (the low bits), so the painter can tint its row
-/// and mark its prefix; Diff marks the words a changed line changed
-/// (hunks.zig), drawn on a stronger tint.
-pub const diff_added: u8 = 0x80;
-pub const diff_removed: u8 = 0x40;
-pub const diff_emph: u8 = 0x20;
-/// A +Diff line added or removed whole, paired with no line it changed:
-/// its row takes a faint tint, on its marker's byte.
-pub const diff_whole: u8 = 0x10;
+/// A style byte: a Syn in its low bits (syn_bits), and over them the
+/// grounds a theme resolves (colors.Grounds): `ground_add` or `ground_del`,
+/// a row added or removed (its hue); `ground_emph`, the stronger ground;
+/// `ground_line`, the faint one. A row's first byte says its row's ground:
+/// emph the stronger to the pane's edge, line the faint one, neither none
+/// (only its marker in the hue). Any later byte's emph is its own cell's
+/// ground: the words a changed line changed (hunks.zig).
+pub const ground_add: u8 = 0x80;
+pub const ground_del: u8 = 0x40;
+pub const ground_emph: u8 = 0x20;
+pub const ground_line: u8 = 0x10;
pub const syn_bits: u8 = 0x0f;
/// A file section's hunks are parsed together, each side as one text, in
@@ -967,7 +1027,8 @@ var diff_clock: u64 = 0;
/// the file its section names. A hunk's old side (context and removed
/// lines) and new side (context and added lines) are each parsed whole, so
/// a string or comment that spans lines colours as it does in the file.
-/// Added and removed lines carry `diff_added`/`diff_removed`. A file in no
+/// Added and removed lines carry `ground_add`/`ground_del`, the first byte
+/// the strong row ground too (`ground_emph`). A file in no
/// language pardes knows keeps the plain colours: added lines as strings,
/// removed ones as numbers.
pub fn highlightDiff(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 {
@@ -1082,13 +1143,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8,
for (kinds) |kind| {
const line = lines.next() orelse break;
const style: u8 = switch (kind) {
- .added => @backingInt(Syn.string) | diff_added,
- .removed => @backingInt(Syn.number) | diff_removed,
+ .added => @backingInt(Syn.string) | ground_add,
+ .removed => @backingInt(Syn.number) | ground_del,
.no_newline => @backingInt(Syn.comment),
.hunk => @backingInt(Syn.keyword),
else => 0,
};
if (style != 0) window.fill(at + offset, line.len, style);
+ if (style & (ground_add | ground_del) != 0 and line.len > 0) window.fill(at + offset, 1, style | ground_emph);
offset += line.len + 1;
}
}
@@ -1170,13 +1232,14 @@ fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []cons
if (kind == .context or kind == .removed) old_at += code_len + 1;
if (kind == .context or kind == .added) new_at += code_len + 1;
const flag: u8 = switch (kind) {
- .added => diff_added,
- .removed => diff_removed,
+ .added => ground_add,
+ .removed => ground_del,
else => 0,
};
if (flag != 0) for (out[offset..][0..line.len]) |*b| {
b.* |= flag;
};
+ if (flag != 0 and line.len > 0) out[offset] |= ground_emph;
}
}
@@ -1212,7 +1275,7 @@ test "every vendored textobject and indent query compiles against its grammar" {
for (&specs) |*spec| for ([_]Lazy{ spec.objects, spec.indents }, [_][]const u8{ "textobjects", "indents" }) |lazy, what| {
if (lazy.src.len == 0) continue;
var error_offset: u32 = 0;
- const q = ts.Query.create(spec.language(), lazy.src, &error_offset) catch {
+ const q = ts.Query.create(langOf(spec), lazy.src, &error_offset) catch {
std.debug.print("{s} for {s} do not compile (offset {d})\n", .{ what, spec.name, error_offset });
failed += 1;
continue;
@@ -1577,9 +1640,12 @@ test "syntax highlightDiff colors unified diff lines by prefix" {
// A file in no known language: each line in one colour, and tinted.
try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "-old line", 0));
try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+new line", 0));
- try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & diff_removed != 0);
- try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & diff_added != 0);
- try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (diff_added | diff_removed) == 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_del != 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & ground_add != 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (ground_add | ground_del) == 0);
+ // The row's ground on its first byte: the strong one, its other bytes none.
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_emph != 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & (ground_emph | ground_line) == 0);
}
test "syntax a Zig hunk is coloured as Zig, each side parsed whole" {
@@ -1611,9 +1677,9 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" {
try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "new words defer", 10));
// The prefix is no code: it carries the tint alone.
const added = std.mem.indexOf(u8, diff_text, "+ side").?;
- try std.testing.expectEqual(diff_added, styles[added]);
- try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & diff_added != 0);
- try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & diff_removed != 0);
+ try std.testing.expectEqual(ground_add | ground_emph, styles[added]);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & ground_add != 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & ground_del != 0);
try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "index 111", 0));
// A window in the middle is coloured as the whole is.
@@ -1660,7 +1726,7 @@ test "syntax a deleted file's lines are coloured in its language" {
defer std.testing.allocator.free(styles);
try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "enum", 0));
try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "// the end", 3));
- try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & diff_removed != 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & ground_del != 0);
try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "deleted file", 0));
}
@@ -1709,9 +1775,9 @@ test "syntax git diff output in a command pane is told and coloured by its rows"
try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, text, "fn main", 0));
try std.testing.expectEqual(Syn.number, diffSynAt(styles, text, "42", 0));
// The wrapped row stays an added line, and inside the comment.
- try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & diff_added != 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & ground_add != 0);
try std.testing.expectEqual(Syn.comment, diffSynAt(styles, text, "wrapped rest", 0));
- try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & diff_removed != 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & ground_del != 0);
}
test "syntax a section's small hunks share one parse" {
@@ -1733,7 +1799,7 @@ test "syntax a section's small hunks share one parse" {
try std.testing.expectEqual(@as(usize, 2), cached); // x.zig's three hunks, and y.zig's
try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -10", 0));
try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2;\n@@ -20", 0));
- try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (diff_added | diff_removed) == 0);
+ try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (ground_add | ground_del) == 0);
}
test "syntax a hunk painted once is kept, and a long one is parsed in pieces" {
@@ -2101,3 +2167,27 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al
try std.testing.expectEqual(fn_.endPoint(), rn.endPoint());
try std.testing.expectEqual(fn_.startByte(), rn.startByte());
}
+
+test "syntax: a grammar handed in at run time colours and walks as the one compiled in" {
+ if (!zig_grammar) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ start(gpa);
+ defer stop();
+ const zig_lang = @extern(LanguageFn, .{ .name = "tree_sitter_zig" })();
+ try std.testing.expect(addLanguage(.{ .name = "mine", .ext = ".mine", .ts = zig_lang, .highlights = ts_queries.zig_highlights }));
+ // the same again is kept; told again with other queries, replaced
+ try std.testing.expect(addLanguage(.{ .name = "mine", .ext = ".mine", .ts = zig_lang, .highlights = ts_queries.zig_highlights }));
+ try std.testing.expect(supportsPath("x.mine"));
+ const src = "const x = 1; // one\nfn f() void {}\n";
+ const want = try highlightFileRange(gpa, "a.zig", src, 0, src.len);
+ defer gpa.free(want);
+ const got = try highlightFileRange(gpa, "a.mine", src, 0, src.len);
+ defer gpa.free(got);
+ try std.testing.expectEqualSlices(u8, want, got);
+ const tree = parseTree("a.mine", src, null) orelse return error.NoTree;
+ defer freeTree(tree);
+ var spans: [4]Span = undefined;
+ try std.testing.expect(walkNodes(tree, .expand_node, 6, 7, 6, &spans) > 0);
+ forgetLanguages();
+ try std.testing.expect(!supportsPath("x.mine"));
+}