-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.zig
More file actions
3083 lines (2693 loc) · 127 KB
/
Copy pathmanager.zig
File metadata and controls
3083 lines (2693 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const log = std.log.scoped(.SyntaxManager);
const ts = @import("tree_sitter.zig");
const c = ts.c;
const protocol = @import("../kernel/protocol.zig");
const thread_name = @import("../services/thread_name.zig");
const test_utils = @import("../test_utils.zig");
const MemoryTestUtils = test_utils.MemoryTestUtils;
const PerformanceTestUtils = test_utils.PerformanceTestUtils;
pub const SyntaxManager = struct {
allocator: std.mem.Allocator,
/// io is used for the locking primitives that guard tree/parse state.
/// `null` means no worker thread will be spawned and all locking is a
/// no-op (single-threaded test mode).
io: ?std.Io = null,
/// Main-thread parser. Used by the synchronous `parse()` path (which
/// tests rely on). The async path has its own parser so the two never
/// contend.
parser: *c.TSParser,
/// Parser owned by the background worker. Created lazily in
/// `startParseWorker`; null until then.
worker_parser: ?*c.TSParser = null,
/// Current syntax tree. Reads and writes must hold `tree_mutex` once
/// the parse worker is running; before that, single-threaded access is
/// fine.
tree: ?*c.TSTree,
language: ?*const c.TSLanguage,
query: ?*c.TSQuery,
query_truncated: bool = false,
cursor: *c.TSQueryCursor,
/// Guards `tree`, `current_lang`, `current_resource_id`. Brief locks
/// only — readers hold it during one ts_* call, the worker holds it
/// during the pointer swap, not the parse itself.
tree_mutex: std.Io.Mutex = .init,
current_lang: Language = .unknown,
current_resource_id: u64 = 0,
/// Latest-wins parse job. `submitParse` overwrites the previous one if
/// the worker hasn't picked it up yet — only the most-recent edit needs
/// to be parsed.
pending_job: ?ParseJob = null,
parse_mutex: std.Io.Mutex = .init,
parse_cond: std.Io.Condition = .init,
parse_thread: ?std.Thread = null,
parse_shutdown: std.atomic.Value(bool) = .{ .raw = false },
/// Liveness flag for the parse worker: set by the owner before spawn,
/// cleared by the worker on exit. `parse_thread != null` with this false
/// means the worker died without a shutdown request.
parse_worker_alive: std.atomic.Value(bool) = .{ .raw = false },
/// Single-slot memoization for `highlight`. When the caller asks for
/// the same buffer-version + visible range we just computed, return a
/// fresh copy instead of re-running the query cursor. Invalidated on
/// every tree swap (parse / setLanguage / clear). Massively cuts CPU on
/// idle frames where the buffer hasn't changed and the user just
/// breathed near the editor.
highlight_cache: HighlightCache = .{},
/// Same idea as `highlight_cache`, but for `findBrackets`. The cache
/// stores brackets for the *entire* buffer, keyed on
/// `(resource_id, content_len)`. Visible-range windowing happens
/// at lookup time. Without whole-buffer caching, scrolling would
/// miss the cache every frame (visible range changes) and trigger
/// a full byte-walk per render — visibly laggy on large files.
bracket_cache: BracketCache = .{},
/// Pending edits queued by `recordEdit`. Drained on the next
/// `submitParse` or cleared on `setLanguageEnum`.
pending_edits: std.ArrayListUnmanaged(EditInfo) = .empty,
edits_mutex: std.Io.Mutex = .init,
/// Set to true by the parse worker each time it installs a new tree.
/// Core's tick handler polls this; on hit, clears it and requests a
/// render. Without this, a freshly-parsed tree sits invisible until
/// some other event (mouse move, keystroke) happens to fire a render.
tree_updated: std.atomic.Value(bool) = .{ .raw = false },
/// Per-buffer tree cache. When the user switches away from a
/// buffer, `setActiveBuffer` parks that buffer's tree here so a
/// switch *back* can restore it instantly — no flash of
/// unhighlighted text waiting on the async parse. Keyed on the
/// buffer's stable `resource_id`. Each entry remembers the
/// language and content length at parse time so a stale tree
/// (the user edited the buffer just before leaving) can be
/// identified and discarded on restore rather than rendered
/// against mismatched positions.
///
/// Memory: one TSTree per cached buffer (~tens of KB typical).
/// Capped indirectly by the buffer count — closed buffers call
/// `dropBuffer` which evicts.
state_cache: std.AutoHashMapUnmanaged(u64, ParkedTree) = .empty,
/// Most-recent parsed content length per buffer, written by the
/// parse worker on install and read by `setActiveBuffer` when
/// parking the live tree. Mirrors the resource_ids in
/// state_cache + the current live buffer.
last_parse_content_len: std.AutoHashMapUnmanaged(u64, usize) = .empty,
/// Guards `state_cache` and `last_parse_content_len`. Brief;
/// never held across a tree-sitter call.
state_mutex: std.Io.Mutex = .init,
pub const ParkedTree = struct {
tree: *c.TSTree,
lang: Language,
content_len_at_parse: usize,
};
pub const HighlightCache = struct {
resource_id: u64 = 0,
lang: Language = .unknown,
start_line: usize = 0,
end_line: usize = 0,
tokens: std.ArrayListUnmanaged(protocol.SyntaxToken) = .empty,
valid: bool = false,
fn invalidate(self: *HighlightCache, allocator: std.mem.Allocator) void {
self.tokens.clearAndFree(allocator);
self.valid = false;
}
};
pub const BracketCache = struct {
resource_id: u64 = 0,
content_len: usize = 0,
/// Whole-buffer bracket tokens, sorted by `(line, start_col)` via
/// the natural left-to-right walk that produces them. Lookups
/// binary-search by line to extract the visible window.
tokens: std.ArrayListUnmanaged(protocol.SyntaxToken) = .empty,
valid: bool = false,
fn invalidate(self: *BracketCache, allocator: std.mem.Allocator) void {
self.tokens.clearAndFree(allocator);
self.valid = false;
}
};
pub const ParseJob = struct {
source: []u8,
lang: Language,
resource_id: ?u64,
/// Edits recorded since the last parse. Replayed onto a tree_copy
/// before reparse so tree-sitter can do real incremental parsing.
/// Empty slice means no incremental hints — the parser still uses
/// the copy for subtree-reuse content matching, just slower.
edits: []EditInfo = &.{},
};
/// Single buffer edit, in the shape tree-sitter's `TSInputEdit`
/// expects. Stored in `pending_edits` on the manager and drained by
/// `submitParse` into the ParseJob.
pub const EditInfo = struct {
start_byte: usize,
old_end_byte: usize,
new_end_byte: usize,
start_row: usize,
start_col: usize,
old_end_row: usize,
old_end_col: usize,
new_end_row: usize,
new_end_col: usize,
};
/// Lock helpers: no-op when no io (single-threaded test mode).
inline fn treeLock(self: *SyntaxManager) void {
if (self.io) |io| self.tree_mutex.lockUncancelable(io);
}
inline fn treeUnlock(self: *SyntaxManager) void {
if (self.io) |io| self.tree_mutex.unlock(io);
}
inline fn parseLock(self: *SyntaxManager) void {
if (self.io) |io| self.parse_mutex.lockUncancelable(io);
}
inline fn parseUnlock(self: *SyntaxManager) void {
if (self.io) |io| self.parse_mutex.unlock(io);
}
inline fn stateLock(self: *SyntaxManager) void {
if (self.io) |io| self.state_mutex.lockUncancelable(io);
}
inline fn stateUnlock(self: *SyntaxManager) void {
if (self.io) |io| self.state_mutex.unlock(io);
}
pub const Language = enum {
zig,
python,
go,
javascript,
typescript,
tsx,
json,
bash,
html,
css,
rust,
c,
cpp,
java,
ruby,
csharp,
php,
swift,
kotlin,
lua,
dart,
elixir,
haskell,
ocaml,
scala,
r,
perl,
erlang,
markdown,
unknown,
pub fn fromExtension(ext: []const u8) Language {
if (std.mem.eql(u8, ext, ".zig")) return .zig;
if (std.mem.eql(u8, ext, ".go")) return .go;
if (std.mem.eql(u8, ext, ".rs")) return .rust;
if (std.mem.eql(u8, ext, ".py") or std.mem.eql(u8, ext, ".pyw") or std.mem.eql(u8, ext, ".pyi")) return .python;
if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return .html;
if (std.mem.eql(u8, ext, ".css")) return .css;
if (std.mem.eql(u8, ext, ".js") or std.mem.eql(u8, ext, ".mjs") or std.mem.eql(u8, ext, ".cjs")) return .javascript;
if (std.mem.eql(u8, ext, ".jsx")) return .tsx;
if (std.mem.eql(u8, ext, ".ts") or std.mem.eql(u8, ext, ".mts") or std.mem.eql(u8, ext, ".cts")) return .typescript;
if (std.mem.eql(u8, ext, ".tsx")) return .tsx;
if (std.mem.eql(u8, ext, ".json")) return .json;
if (std.mem.eql(u8, ext, ".sh") or std.mem.eql(u8, ext, ".bash") or std.mem.eql(u8, ext, ".zsh")) return .bash;
if (std.mem.eql(u8, ext, ".md") or std.mem.eql(u8, ext, ".markdown")) return .markdown;
// C: `.c` and `.h`. `.h` is ambiguous (could be C++) but most C
// codebases use `.h`; C++ files conventionally use `.hpp`/`.hxx`.
if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return .c;
if (std.mem.eql(u8, ext, ".cpp") or std.mem.eql(u8, ext, ".cc") or std.mem.eql(u8, ext, ".cxx") or
std.mem.eql(u8, ext, ".hpp") or std.mem.eql(u8, ext, ".hxx") or std.mem.eql(u8, ext, ".hh")) return .cpp;
if (std.mem.eql(u8, ext, ".java")) return .java;
if (std.mem.eql(u8, ext, ".rb") or std.mem.eql(u8, ext, ".rake")) return .ruby;
if (std.mem.eql(u8, ext, ".cs")) return .csharp;
if (std.mem.eql(u8, ext, ".php") or std.mem.eql(u8, ext, ".phtml") or std.mem.eql(u8, ext, ".php3") or std.mem.eql(u8, ext, ".php4") or std.mem.eql(u8, ext, ".php5") or std.mem.eql(u8, ext, ".php7")) return .php;
if (std.mem.eql(u8, ext, ".swift")) return .swift;
if (std.mem.eql(u8, ext, ".kt") or std.mem.eql(u8, ext, ".kts")) return .kotlin;
if (std.mem.eql(u8, ext, ".lua")) return .lua;
if (std.mem.eql(u8, ext, ".dart")) return .dart;
if (std.mem.eql(u8, ext, ".ex") or std.mem.eql(u8, ext, ".exs")) return .elixir;
if (std.mem.eql(u8, ext, ".hs") or std.mem.eql(u8, ext, ".lhs")) return .haskell;
if (std.mem.eql(u8, ext, ".ml") or std.mem.eql(u8, ext, ".mli")) return .ocaml;
if (std.mem.eql(u8, ext, ".scala") or std.mem.eql(u8, ext, ".sc")) return .scala;
if (std.mem.eql(u8, ext, ".r") or std.mem.eql(u8, ext, ".R")) return .r;
if (std.mem.eql(u8, ext, ".pl") or std.mem.eql(u8, ext, ".pm") or std.mem.eql(u8, ext, ".t")) return .perl;
if (std.mem.eql(u8, ext, ".erl") or std.mem.eql(u8, ext, ".hrl")) return .erlang;
return .unknown;
}
pub fn fromFilename(filename: []const u8) Language {
const ext = std.fs.path.extension(filename);
return fromExtension(ext);
}
};
const zig_query = @embedFile("queries/zig.scm");
const python_query = @embedFile("queries/python.scm");
const javascript_query = @embedFile("queries/javascript.scm");
const typescript_query = @embedFile("queries/typescript.scm");
const json_query = @embedFile("queries/json.scm");
const bash_query = @embedFile("queries/bash.scm");
const go_query = @embedFile("queries/go.scm");
const html_query = @embedFile("queries/html.scm");
const css_query = @embedFile("queries/css.scm");
const rust_query = @embedFile("queries/rust.scm");
const c_query = @embedFile("queries/c.scm");
const cpp_query = @embedFile("queries/cpp.scm");
const java_query = @embedFile("queries/java.scm");
const ruby_query = @embedFile("queries/ruby.scm");
const csharp_query = @embedFile("queries/csharp.scm");
const php_query = @embedFile("queries/php.scm");
const swift_query = @embedFile("queries/swift.scm");
const kotlin_query = @embedFile("queries/kotlin.scm");
const lua_query = @embedFile("queries/lua.scm");
const dart_query = @embedFile("queries/dart.scm");
const elixir_query = @embedFile("queries/elixir.scm");
const haskell_query = @embedFile("queries/haskell.scm");
const ocaml_query = @embedFile("queries/ocaml.scm");
const scala_query = @embedFile("queries/scala.scm");
const r_query = @embedFile("queries/r.scm");
const perl_query = @embedFile("queries/perl.scm");
const erlang_query = @embedFile("queries/erlang.scm");
pub fn init(allocator: std.mem.Allocator) !SyntaxManager {
const parser = c.ts_parser_new() orelse return error.OutOfMemory;
const cursor = c.ts_query_cursor_new() orelse {
c.ts_parser_delete(parser);
return error.OutOfMemory;
};
return .{
.allocator = allocator,
.parser = parser,
.tree = null,
.language = null,
.query = null,
.cursor = cursor,
.current_lang = .unknown,
};
}
pub fn deinit(self: *SyntaxManager) void {
// Stop the parse worker first so it can't be mid-write to `tree`
// when we free it.
self.stopParseWorker();
if (self.tree) |t| c.ts_tree_delete(t);
if (self.query) |q| c.ts_query_delete(q);
c.ts_query_cursor_delete(self.cursor);
c.ts_parser_delete(self.parser);
if (self.worker_parser) |p| c.ts_parser_delete(p);
self.highlight_cache.invalidate(self.allocator);
self.bracket_cache.invalidate(self.allocator);
// Drop every parked tree.
var it = self.state_cache.valueIterator();
while (it.next()) |parked| c.ts_tree_delete(parked.tree);
self.state_cache.deinit(self.allocator);
self.last_parse_content_len.deinit(self.allocator);
}
/// Spawn the background parse worker. Idempotent — safe to call if one
/// is already running. Failures are non-fatal: subsequent `submitParse`
/// calls fall back to a synchronous parse on the caller's thread.
pub fn startParseWorker(self: *SyntaxManager, io: std.Io) !void {
if (self.parse_thread != null) return;
if (self.worker_parser == null) {
self.worker_parser = c.ts_parser_new() orelse return error.OutOfMemory;
}
// io is captured for the lifetime of the worker; needed by the
// mutex/condvar primitives the worker uses.
self.io = io;
self.parse_shutdown.store(false, .release);
// Set before spawn so a watchdog probe between spawn and the
// worker's first instruction can't misread a starting worker as dead.
self.parse_worker_alive.store(true, .release);
self.parse_thread = std.Thread.spawn(.{}, parseWorkerMain, .{self}) catch |err| {
self.parse_worker_alive.store(false, .release);
return err;
};
}
/// Watchdog hook: if the parse worker exited without a shutdown request
/// (swallowed panic path, unexpected return), reap the dead thread and
/// respawn it. Returns true when a restart actually happened. Must be
/// called from the thread that owns worker lifecycle (core).
pub fn restartParseWorkerIfDead(self: *SyntaxManager, io: std.Io) bool {
if (self.parse_thread == null) return false; // never started
if (self.parse_worker_alive.load(.acquire)) return false; // healthy
if (self.parse_shutdown.load(.acquire)) return false; // shutting down
if (self.parse_thread) |t| {
t.join(); // already exited; returns immediately
self.parse_thread = null;
}
self.startParseWorker(io) catch return false;
return true;
}
fn stopParseWorker(self: *SyntaxManager) void {
if (self.parse_thread == null) return;
self.parse_shutdown.store(true, .release);
self.parseLock();
if (self.io) |io| self.parse_cond.broadcast(io);
self.parseUnlock();
if (self.parse_thread) |t| {
t.join();
self.parse_thread = null;
}
// Drop any pending job.
self.parseLock();
if (self.pending_job) |old| {
self.allocator.free(old.source);
if (old.edits.len > 0) self.allocator.free(old.edits);
self.pending_job = null;
}
self.parseUnlock();
// Drop any pending edits — no worker left to apply them.
if (self.io) |io| self.edits_mutex.lockUncancelable(io);
self.pending_edits.deinit(self.allocator);
self.pending_edits = .empty;
if (self.io) |io| self.edits_mutex.unlock(io);
}
fn parseWorkerMain(self: *SyntaxManager) void {
thread_name.set("stem-parse");
log.debug("parse worker started", .{});
defer log.debug("parse worker exited", .{});
defer self.parse_worker_alive.store(false, .release);
while (true) {
// Wait for a job.
self.parseLock();
while (self.pending_job == null and !self.parse_shutdown.load(.acquire)) {
if (self.io) |io| self.parse_cond.waitUncancelable(io, &self.parse_mutex);
}
if (self.parse_shutdown.load(.acquire)) {
self.parseUnlock();
return;
}
var job = self.pending_job.?;
self.pending_job = null;
self.parseUnlock();
defer self.allocator.free(job.source);
const lang_ptr: ?*const c.TSLanguage = switch (job.lang) {
.zig => ts.zig_language(),
.python => ts.python_language(),
.javascript => ts.javascript_language(),
.typescript => ts.typescript_language(),
.tsx => ts.tsx_language(),
.json => ts.json_language(),
.bash => ts.bash_language(),
.go => ts.go_language(),
.html => ts.html_language(),
.css => ts.css_language(),
.rust => ts.rust_language(),
.c => ts.c_language(),
.cpp => ts.cpp_language(),
.java => ts.java_language(),
.ruby => ts.ruby_language(),
.csharp => ts.csharp_language(),
.php => ts.php_language(),
.swift => ts.swift_language(),
.kotlin => ts.kotlin_language(),
.lua => ts.lua_language(),
.dart => ts.dart_language(),
.elixir => ts.elixir_language(),
.haskell => ts.haskell_language(),
.ocaml => ts.ocaml_language(),
.scala => ts.scala_language(),
.r => ts.r_language(),
.perl => ts.perl_language(),
.erlang => ts.erlang_language(),
.markdown, .unknown => null,
};
if (lang_ptr == null) continue;
const wp = self.worker_parser orelse continue;
thread_name.markStep("parse:set_language");
if (!c.ts_parser_set_language(wp, lang_ptr.?)) continue;
// Take a refcounted copy of the previous tree (cheap — tree-
// sitter's ts_tree_copy is shallow) so we can pass it to the
// parser without holding the tree lock during the parse. The
// copy must be language-compatible with the new parse: if the
// user switched languages, skip the copy.
thread_name.markStep("parse:lock_for_copy");
self.treeLock();
thread_name.markStep("parse:tree_copy");
const prev_tree_copy: ?*c.TSTree = if (self.current_lang == job.lang and self.tree != null)
c.ts_tree_copy(self.tree.?)
else
null;
const apply_edits = job.edits;
job.edits = &.{};
self.treeUnlock();
// Replay any edits recorded on the main thread since the last
// parse, so the parser knows which byte ranges changed and can
// reuse subtrees outside those ranges. Without these calls the
// copy is just a content hint; with them, edited regions get
// proper reparse and the rest is reused.
if (prev_tree_copy) |t| {
thread_name.markStep("parse:apply_edits");
for (apply_edits) |ed| {
var ts_edit = c.TSInputEdit{
.start_byte = @intCast(ed.start_byte),
.old_end_byte = @intCast(ed.old_end_byte),
.new_end_byte = @intCast(ed.new_end_byte),
.start_point = .{ .row = @intCast(ed.start_row), .column = @intCast(ed.start_col) },
.old_end_point = .{ .row = @intCast(ed.old_end_row), .column = @intCast(ed.old_end_col) },
.new_end_point = .{ .row = @intCast(ed.new_end_row), .column = @intCast(ed.new_end_col) },
};
c.ts_tree_edit(t, &ts_edit);
}
}
if (apply_edits.len > 0) self.allocator.free(apply_edits);
// Parse. With prev_tree_copy non-null and ts_tree_edit applied,
// tree-sitter does an incremental reparse — only changed nodes
// are rebuilt; everything else is reused. Order-of-magnitude
// faster on 1-char edits in large files.
thread_name.markStep("parse:parse_string");
const new_tree = c.ts_parser_parse_string(wp, prev_tree_copy, job.source.ptr, @intCast(job.source.len));
thread_name.markStep("parse:delete_prev_copy");
if (prev_tree_copy) |t| c.ts_tree_delete(t);
if (new_tree == null) continue;
// Swap in. Discard if the user changed language during the parse.
// Steal the old tree pointer under the lock; do the actual
// `ts_tree_delete` (which can be tens of µs on a large tree
// and walks the entire node arena) outside the lock so a
// concurrent `highlight()` / `findBrackets()` / `nodeAt()`
// never blocks on it. Same reasoning for `new_tree` when
// we discard.
thread_name.markStep("parse:lock_for_install");
self.treeLock();
thread_name.markStep("parse:check_installed");
const installed = self.current_lang == job.lang;
var deferred_delete: ?*c.TSTree = null;
if (installed) {
deferred_delete = self.tree;
thread_name.markStep("parse:assign_new_tree");
self.tree = new_tree;
if (job.resource_id) |id| self.current_resource_id = id;
// Tree changed → memoized highlight + bracket pass stale.
thread_name.markStep("parse:invalidate_hl_cache");
self.highlight_cache.invalidate(self.allocator);
thread_name.markStep("parse:invalidate_bracket_cache");
self.bracket_cache.invalidate(self.allocator);
} else {
deferred_delete = new_tree;
}
self.treeUnlock();
if (deferred_delete) |t| {
thread_name.markStep("parse:delete_old_tree_unlocked");
c.ts_tree_delete(t);
}
// Record the parse-time content length on the parked
// entry for this buffer. Used by `setActiveBuffer` to
// distinguish "tree matches current content" (instant
// restore) from "tree is stale, need a fresh parse".
// We don't install into state_cache here — the LIVE
// tree stays in `self.tree`; state_cache is populated
// when the buffer is switched *away from*. But we DO
// need to track the most-recent parse's content_len
// so the park step can record it without re-walking
// the content.
if (installed) {
if (job.resource_id) |id| {
// OOM here means the parked-tree cache loses
// its content_len marker for this buffer. The
// next setActiveBuffer will discard the parked
// tree as "unknown freshness" and force a
// reparse — correct but slower. Log so we'd
// notice if this starts firing.
self.last_parse_content_len.put(self.allocator, id, job.source.len) catch |err| {
log.debug("last_parse_content_len put failed for buffer {d}: {s}", .{ id, @errorName(err) });
};
}
}
thread_name.markStep("parse:idle");
// Signal core's tick handler that highlighting can be redrawn.
if (installed) self.tree_updated.store(true, .release);
}
}
/// Submit a parse job to the background worker, replacing any prior job
/// the worker hasn't picked up yet. The caller's content is duped so
/// it's safe to free immediately after this returns. If no worker is
/// running, falls back to a synchronous `parse`.
pub fn submitParse(self: *SyntaxManager, source: []const u8, resource_id: ?u64) !void {
self.treeLock();
const lang = self.current_lang;
self.treeUnlock();
if (lang == .markdown or lang == .unknown) return;
if (self.parse_thread == null) {
// No worker; do it inline. This is the test path.
return self.parse(source, resource_id);
}
const dup = try self.allocator.dupe(u8, source);
errdefer self.allocator.free(dup);
// Drain pending edits into an owned slice that travels with the
// job. Worker frees it after applying.
const empty_edits: []EditInfo = &.{};
const edits_owned: []EditInfo = blk: {
if (self.io) |io| self.edits_mutex.lockUncancelable(io);
defer if (self.io) |io| self.edits_mutex.unlock(io);
if (self.pending_edits.items.len == 0) break :blk empty_edits;
const owned = self.pending_edits.toOwnedSlice(self.allocator) catch break :blk empty_edits;
break :blk owned;
};
errdefer if (edits_owned.len > 0) self.allocator.free(edits_owned);
self.parseLock();
defer self.parseUnlock();
if (self.pending_job) |old| {
self.allocator.free(old.source);
if (old.edits.len > 0) self.allocator.free(old.edits);
}
self.pending_job = .{
.source = dup,
.lang = lang,
.resource_id = resource_id,
.edits = edits_owned,
};
if (self.io) |io| self.parse_cond.signal(io);
}
/// Record a buffer edit so the next parse can replay it as a tree-
/// sitter `TSInputEdit`. Cheap (just appends to a list). The list is
/// drained on the next `submitParse` and applied to the previous tree
/// before the worker reparses.
///
/// NOTE: callers (the edit sites in `EditorState`) need a reference to
/// `SyntaxManager` to invoke this. Today the manager is owned by
/// `Core` and not exposed to `EditorState`, so this method is unused.
/// Even without callers, `submitParse` passes a tree_copy to the
/// parser; tree-sitter does content-based subtree reuse against that
/// copy, which captures most of the incremental win for typical
/// edits. Wiring `recordEdit` from `insertChar`/`deleteChar`/etc.
/// would push the remaining win (large files + small edits) but
/// requires a callback or back-reference plumbed through
/// `EditorState`.
pub fn recordEdit(self: *SyntaxManager, info: EditInfo) void {
if (self.io) |io| self.edits_mutex.lockUncancelable(io);
defer if (self.io) |io| self.edits_mutex.unlock(io);
self.pending_edits.append(self.allocator, info) catch {
// OOM: drop the record. Worst case the next parse is a full
// (non-incremental) reparse — slower but still correct.
};
// Brackets are computed by a byte-walk over the buffer, not
// from the tree. The tree-update path also invalidates this
// cache, but that only fires once the async parse lands; an
// edit that preserves byte length (e.g. find/replace `foo`
// → `bar`) would otherwise serve stale positions in the
// intervening window.
//
// Lock under treeLock — the parse worker and findBrackets
// both touch bracket_cache under treeLock; mixing edits_mutex
// alone here would let an invalidate race with a findBrackets
// dupe.
self.treeLock();
defer self.treeUnlock();
self.bracket_cache.invalidate(self.allocator);
}
pub fn setLanguageEnum(self: *SyntaxManager, lang_enum: Language) !void {
if (lang_enum == .unknown) return error.UnsupportedLanguage;
log.debug("SyntaxManager.setLanguageEnum called with: {s}", .{@tagName(lang_enum)});
const lang_ptr: ?*const c.TSLanguage = switch (lang_enum) {
.zig => ts.zig_language(),
.python => ts.python_language(),
.javascript => ts.javascript_language(),
.typescript => ts.typescript_language(),
.tsx => ts.tsx_language(),
.json => ts.json_language(),
.bash => ts.bash_language(),
.go => ts.go_language(),
.html => ts.html_language(),
.css => ts.css_language(),
.rust => ts.rust_language(),
.c => ts.c_language(),
.cpp => ts.cpp_language(),
.java => ts.java_language(),
.ruby => ts.ruby_language(),
.csharp => ts.csharp_language(),
.php => ts.php_language(),
.swift => ts.swift_language(),
.kotlin => ts.kotlin_language(),
.lua => ts.lua_language(),
.dart => ts.dart_language(),
.elixir => ts.elixir_language(),
.haskell => ts.haskell_language(),
.ocaml => ts.ocaml_language(),
.scala => ts.scala_language(),
.r => ts.r_language(),
.perl => ts.perl_language(),
.erlang => ts.erlang_language(),
.markdown => null,
.unknown => null,
};
const query_source: []const u8 = switch (lang_enum) {
.zig => zig_query,
.python => python_query,
.javascript => javascript_query,
.typescript, .tsx => typescript_query,
.json => json_query,
.bash => bash_query,
.go => go_query,
.html => html_query,
.css => css_query,
.rust => rust_query,
.c => c_query,
.cpp => cpp_query,
.java => java_query,
.ruby => ruby_query,
.csharp => csharp_query,
.php => php_query,
.swift => swift_query,
.kotlin => kotlin_query,
.lua => lua_query,
.dart => dart_query,
.elixir => elixir_query,
.haskell => haskell_query,
.ocaml => ocaml_query,
.scala => scala_query,
.r => r_query,
.perl => perl_query,
.erlang => erlang_query,
.markdown => &.{},
.unknown => &.{},
};
// Drop any pending edits — they reference the OLD content/tree.
if (self.io) |io| self.edits_mutex.lockUncancelable(io);
self.pending_edits.clearRetainingCapacity();
if (self.io) |io| self.edits_mutex.unlock(io);
// Drop any pending parse job — it was for the OLD language.
self.parseLock();
if (self.pending_job) |old| {
self.allocator.free(old.source);
if (old.edits.len > 0) self.allocator.free(old.edits);
self.pending_job = null;
}
self.parseUnlock();
if (lang_enum == .markdown) {
self.treeLock();
self.current_lang = lang_enum;
if (self.tree) |t| c.ts_tree_delete(t);
self.tree = null;
self.highlight_cache.invalidate(self.allocator);
self.bracket_cache.invalidate(self.allocator);
self.treeUnlock();
if (self.query) |q| c.ts_query_delete(q);
self.query = null;
self.query_truncated = false;
self.language = null;
log.debug("SyntaxManager: {s} uses custom/LSP highlighting", .{@tagName(lang_enum)});
return;
}
if (lang_ptr == null) return error.InvalidLanguage;
const lang = lang_ptr.?;
if (!c.ts_parser_set_language(self.parser, lang)) {
log.err("SyntaxManager: Failed to set parser language", .{});
return error.InvalidLanguage;
}
self.language = lang;
self.treeLock();
self.current_lang = lang_enum;
self.current_resource_id = 0;
if (self.tree) |t| c.ts_tree_delete(t);
self.tree = null;
self.highlight_cache.invalidate(self.allocator);
self.treeUnlock();
log.debug("SyntaxManager: Language set successfully, loading query ({d} bytes)", .{query_source.len});
if (self.query) |q| c.ts_query_delete(q);
self.query = null;
self.query_truncated = false;
// Tree-sitter rejects the whole query if any single pattern
// references a node type or anonymous token unknown to the
// linked grammar version. Rather than losing all highlighting
// when one pattern is stale, truncate at the start of the
// failing pattern and retry — we keep the valid prefix.
var src_len: usize = query_source.len;
var first_err_logged = false;
while (src_len > 0) {
var error_offset: u32 = 0;
var error_type: c.TSQueryError = undefined;
self.query = c.ts_query_new(
lang,
query_source.ptr,
@intCast(src_len),
&error_offset,
&error_type,
);
if (self.query != null) break;
if (!first_err_logged) {
const eo: usize = @intCast(error_offset);
const ctx_start: usize = if (eo > 30) eo - 30 else 0;
const ctx_end: usize = @min(eo + 30, src_len);
log.warn(
"SyntaxManager: ts_query_new failed for {s}: offset={d} type={d}\n near: \"{s}\" (truncating and retrying)",
.{ @tagName(lang_enum), error_offset, @as(u32, error_type), query_source[ctx_start..ctx_end] },
);
first_err_logged = true;
}
// Truncate to the start of the line containing the error,
// then keep walking back past blank lines so we land on a
// pattern boundary rather than inside an open paren/bracket.
var cut: usize = @intCast(error_offset);
if (cut > src_len) cut = src_len;
while (cut > 0 and query_source[cut - 1] != '\n') : (cut -= 1) {}
// Skip blank lines so we don't stop in the middle of a
// bracketed alternative.
while (cut > 0 and (query_source[cut - 1] == '\n' or query_source[cut - 1] == ' ' or query_source[cut - 1] == '\t')) : (cut -= 1) {}
// Back up to the start of the previous pattern: scan back
// until we hit a newline, then the line that follows is
// assumed to be a complete top-level pattern boundary.
while (cut > 0 and query_source[cut - 1] != '\n') : (cut -= 1) {}
if (cut >= src_len) {
// Couldn't make progress; bail.
break;
}
src_len = cut;
}
if (self.query == null) {
log.err("SyntaxManager: no usable query patterns for {s}", .{@tagName(lang_enum)});
return error.InvalidQuery;
} else if (src_len < query_source.len) {
self.query_truncated = true;
log.warn(
"SyntaxManager: loaded {d}/{d} bytes of query for {s} (rest skipped due to unknown nodes in linked grammar)",
.{ src_len, query_source.len, @tagName(lang_enum) },
);
}
}
pub fn queryWasTruncated(self: *const SyntaxManager) bool {
return self.query_truncated;
}
pub fn setLanguage(self: *SyntaxManager, lang_name: []const u8) !void {
const lang_enum: Language = blk: {
if (std.mem.eql(u8, lang_name, "zig")) break :blk .zig;
if (std.mem.eql(u8, lang_name, "python")) break :blk .python;
if (std.mem.eql(u8, lang_name, "javascript") or std.mem.eql(u8, lang_name, "js")) break :blk .javascript;
if (std.mem.eql(u8, lang_name, "typescript") or std.mem.eql(u8, lang_name, "ts")) break :blk .typescript;
if (std.mem.eql(u8, lang_name, "tsx") or std.mem.eql(u8, lang_name, "jsx")) break :blk .tsx;
if (std.mem.eql(u8, lang_name, "json")) break :blk .json;
if (std.mem.eql(u8, lang_name, "bash") or std.mem.eql(u8, lang_name, "sh")) break :blk .bash;
if (std.mem.eql(u8, lang_name, "html")) break :blk .html;
if (std.mem.eql(u8, lang_name, "css")) break :blk .css;
if (std.mem.eql(u8, lang_name, "rust") or std.mem.eql(u8, lang_name, "rs")) break :blk .rust;
if (std.mem.eql(u8, lang_name, "go")) break :blk .go;
if (std.mem.eql(u8, lang_name, "c")) break :blk .c;
if (std.mem.eql(u8, lang_name, "cpp") or std.mem.eql(u8, lang_name, "c++") or std.mem.eql(u8, lang_name, "cxx")) break :blk .cpp;
if (std.mem.eql(u8, lang_name, "java")) break :blk .java;
if (std.mem.eql(u8, lang_name, "ruby") or std.mem.eql(u8, lang_name, "rb")) break :blk .ruby;
if (std.mem.eql(u8, lang_name, "csharp") or std.mem.eql(u8, lang_name, "c#") or std.mem.eql(u8, lang_name, "cs")) break :blk .csharp;
if (std.mem.eql(u8, lang_name, "php")) break :blk .php;
if (std.mem.eql(u8, lang_name, "swift")) break :blk .swift;
if (std.mem.eql(u8, lang_name, "kotlin") or std.mem.eql(u8, lang_name, "kt")) break :blk .kotlin;
if (std.mem.eql(u8, lang_name, "lua")) break :blk .lua;
if (std.mem.eql(u8, lang_name, "dart")) break :blk .dart;
if (std.mem.eql(u8, lang_name, "elixir") or std.mem.eql(u8, lang_name, "ex")) break :blk .elixir;
if (std.mem.eql(u8, lang_name, "haskell") or std.mem.eql(u8, lang_name, "hs")) break :blk .haskell;
if (std.mem.eql(u8, lang_name, "ocaml") or std.mem.eql(u8, lang_name, "ml")) break :blk .ocaml;
if (std.mem.eql(u8, lang_name, "scala")) break :blk .scala;
if (std.mem.eql(u8, lang_name, "r")) break :blk .r;
if (std.mem.eql(u8, lang_name, "perl") or std.mem.eql(u8, lang_name, "pl")) break :blk .perl;
if (std.mem.eql(u8, lang_name, "erlang") or std.mem.eql(u8, lang_name, "erl")) break :blk .erlang;
if (std.mem.eql(u8, lang_name, "markdown") or std.mem.eql(u8, lang_name, "md")) break :blk .markdown;
break :blk Language.fromExtension(lang_name);
};
return self.setLanguageEnum(lang_enum);
}
pub fn parse(self: *SyntaxManager, source: []const u8, resource_id: ?u64) !void {
// Copy the previous tree under the lock so the parse itself can
// run without blocking readers (highlight calls). A raw pointer
// snapshot would race with the background worker, which can
// `ts_tree_delete` the prior tree mid-parse — UAF inside the
// C parser. `ts_tree_copy` is a cheap refcount bump.
self.treeLock();
const lang = self.current_lang;
const prev_tree_copy: ?*c.TSTree = if (self.tree) |t| c.ts_tree_copy(t) else null;
self.treeUnlock();
if (lang == .markdown or lang == .unknown) {
if (prev_tree_copy) |t| c.ts_tree_delete(t);
return;
}
const new_tree = c.ts_parser_parse_string(self.parser, prev_tree_copy, source.ptr, @intCast(source.len));
if (prev_tree_copy) |t| c.ts_tree_delete(t);
// Same steal-and-delete-outside pattern as `parseWorkerMain`:
// hand `ts_tree_delete` the freed tree only after we've
// dropped `tree_mutex`, so concurrent readers aren't blocked
// by a multi-µs C-side teardown.
var deferred_delete: ?*c.TSTree = null;
{
self.treeLock();
defer self.treeUnlock();
if (self.current_lang == lang) {
deferred_delete = self.tree;
self.tree = new_tree;
if (resource_id) |id| self.current_resource_id = id;
self.highlight_cache.invalidate(self.allocator);
self.bracket_cache.invalidate(self.allocator);
} else {
deferred_delete = new_tree;
}
}
if (deferred_delete) |t| c.ts_tree_delete(t);
}
/// Snapshot of the relevant node fields, extracted under the
/// tree lock so the caller never has to hold a live `TSNode`
/// reference across operations that could trigger a reparse —
/// such reparses delete the old tree on the worker thread and
/// would leave any held node pointing at freed memory.
pub const NodeSnapshot = struct {
start_row: u32,
start_col: u32,
end_row: u32,
end_col: u32,
start_byte: u32,
end_byte: u32,
type_name: []const u8,
is_named: bool,
};
/// Extract a node descriptor at the given point. Safer
/// replacement for `getNodeAt`: returns a fully owned-by-value
/// snapshot rather than a `TSNode` whose validity depends on
/// the tree staying alive.
pub fn nodeAt(self: *SyntaxManager, line: usize, col: usize) ?NodeSnapshot {
self.treeLock();
defer self.treeUnlock();
const tree = self.tree orelse return null;
const root = c.ts_tree_root_node(tree);
const point = c.TSPoint{
.row = @intCast(line),
.column = @intCast(col),
};
const node = c.ts_node_descendant_for_point_range(root, point, point);
if (c.ts_node_is_null(node)) return null;
const sp = c.ts_node_start_point(node);
const ep = c.ts_node_end_point(node);
const type_str = c.ts_node_type(node);
return .{
.start_row = sp.row,
.start_col = sp.column,
.end_row = ep.row,
.end_col = ep.column,
.start_byte = c.ts_node_start_byte(node),
.end_byte = c.ts_node_end_byte(node),
.type_name = std.mem.span(type_str),
.is_named = c.ts_node_is_named(node),
};
}
/// State snapshot used by the render thread to decide whether
/// the syntax tree is current. Reads `current_lang`,
/// `current_resource_id`, and the truthiness of `tree` under
/// `tree_mutex`, returning a by-value tuple so callers don't
/// have to hold the lock to use the values. Without this, the
/// render thread races with the parse worker installing a new
/// tree (see `parseWorkerMain`) — the worker can free the old
/// tree and overwrite the pointer at the moment the render
/// thread is reading it, producing a torn read.
pub const StateSnapshot = struct {
lang: Language,
resource_id: u64,
has_tree: bool,
};
pub fn stateSnapshot(self: *SyntaxManager) StateSnapshot {
self.treeLock();
defer self.treeUnlock();
return .{
.lang = self.current_lang,
.resource_id = self.current_resource_id,
.has_tree = self.tree != null,
};
}
/// Switch the live syntax state to a different buffer.
///
/// On switch-AWAY, parks the current `self.tree` into
/// `state_cache` under the *old* resource_id, tagged with the
/// content length at last parse (so a future restore knows
/// whether the tree is still valid against current content).
///
/// On switch-TO, if `state_cache` has a tree for `new_id`,
/// restores it as `self.tree` immediately — no flash of
/// unhighlighted text waiting on the async parse. If the
/// caller passes a `current_content_len` that doesn't match
/// the parked entry's `content_len_at_parse`, the parked tree
/// is discarded (stale: the user edited in between) and the
/// usual reparse path takes over.
///
/// Caller is still responsible for calling `submitParse` after
/// switching, to guarantee freshness — this method is purely
/// the cache-hit fast-path on top of that flow.
pub fn setActiveBuffer(
self: *SyntaxManager,
new_id: u64,