summaryrefslogtreecommitdiff
path: root/core/syntax.zig
diff options
context:
space:
mode:
Diffstat (limited to 'core/syntax.zig')
-rw-r--r--core/syntax.zig731
1 files changed, 716 insertions, 15 deletions
diff --git a/core/syntax.zig b/core/syntax.zig
index 5c05300e..9fbad3cf 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,543 @@ 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 };
+ // A test's body (a macro's) lists nothing: its types are its
+ // locals' (a test's `const Find = struct`).
+ if (in.kind == .other) return;
+ 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| {
+ // A longer name is cut (a test's sentence), on a character.
+ var end = name.endByte();
+ if (end - name.startByte() > max_name) {
+ end = name.startByte() + max_name;
+ while (end > name.startByte() and w.source[end] & 0xc0 == 0x80) end -= 1;
+ }
+ try w.out.append(w.gpa, .{
+ .kind = found.kind,
+ .line = name.startPoint().row,
+ .name_start = name.startByte(),
+ .name_end = end,
+ .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 => {
+ // Named by a name, never a pattern (`const { a, b } = ...`,
+ // OCaml's `let () = ...`).
+ name = nameOf(node, rule.name);
+ if (name) |n| if (!nameLike(n.kind())) return null;
+ 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()) return null;
+ return .{ .kind = kind, .name = name, .end = end };
+}
+
+/// The longest name a symbol has: a longer one is cut.
+const max_name = 200;
+
+/// The node naming `node`: its field `field`, whole on its line (C++'s
+/// `namespace v8::internal`, Rust's `impl Vec<T>`); 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| {
+ if (f.startPoint().row == f.endPoint().row) return 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 +2753,131 @@ 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" {
+ \\ const Local = struct {
+ \\ fn helper() void {}
+ \\ };
+ \\ _ = Local;
+ \\}
+ \\test {}
+ \\extern fn tick() void;
+ \\
+ ;
+ // A test's name longer than a row's room is cut, its body still none.
+ const xs: [250]u8 = @splat('x');
+ const long = "test \"" ++ xs ++ "\" {\n const Inner = struct {};\n _ = Inner;\n}\n";
+ const lines = try symbolLines(gpa, "a.zig", source ++ long);
+ 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
+ \\
+ ++ "· \"" ++ xs[0 .. max_name - 1].* ++ "\n", 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}\nnamespace v8::internal {\nint flags;\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\nn v8::internal\nv v8::internal.flags\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 {};\nconst { x, y } = A;\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);
+}