summaryrefslogtreecommitdiff
path: root/build/patches.zig
blob: f58fb9269b039738deaa7873048ccfdf6c50e296 (plain) (blame)
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
const std = @import("std");

/// The upstream patches: each a table of edits to one fetched file, applied
/// at make time by tools/patch.zig, with what it appends a file of its own
/// in build/patches/. Each is applied so that a fresh fetch keeps it, and a
/// bump that moves an anchor fails that file's step.
const Edit = struct { old: []const u8, new: []const u8, count: u8 = 1 };

/// tools/patch.zig, made once and handed to each patch below.
pub fn tool(b: *std.Build) *std.Build.Step.Compile {
    return b.addExecutable(.{ .name = "pardes-patch", .root_module = b.createModule(.{
        .root_source_file = b.path("tools/patch.zig"),
        .target = b.graph.host,
    }) });
}

/// `file` of `dep` with `edits` applied, and build/patches/`append` after them.
fn apply(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, file: []const u8, edits: []const Edit, append: ?[]const u8) std.Build.LazyPath {
    const run = b.addRunArtifact(patch);
    run.setName(b.fmt("patch {s}", .{file}));
    run.addFileArg(dep.path(file));
    const out = run.addOutputFileArg(std.fs.path.basename(file));
    if (append) |name| {
        run.addArg("--append");
        run.addFileArg(b.path(b.fmt("build/patches/{s}", .{name})));
    }
    for (edits) |e| run.addArgs(&.{ b.fmt("{d}", .{e.count}), e.old, e.new });
    return out;
}

/// vaxis's input parser: no reply, split read or malformed sequence may
/// reach the editor as typed text, and none may panic or end input.
/// - A cursor position report that no F3 could have sent is no key: the
///   startup width queries' `CSI 1;1R` arrived as two F3s, which a shell
///   pane took for text (build/patches/vaxis_parser.zig).
/// - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key,
///   not Alt+Escape followed by `[A` as text.
/// - An X10 mouse report and a kitty graphics reply cut short by a read
///   wait for their rest: the first became three bytes of text, the
///   second sliced past its input.
/// - A byte no UTF-8 starts with is dropped instead of failing the parse,
///   which stopped input. (vaxis itself now drops a malformed color or
///   clipboard reply and ends an OSC at its first terminator.)
/// - A device report's fields are sought in the sequence, not past it.
const vaxis_parser = [_]Edit{
    .{
        .old =
        \\            0x5F => return parseApc(input),
        \\            else => {
        ,
        .new =
        \\            0x5F => return parseApc(input),
        \\            // pardes's patch (its build.zig): ESC before a key's sequence is Alt on the key.
        \\            0x1B => if (input.len > 2 and (input[2] == '[' or input[2] == 'O')) {
        \\                var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf, self.cursor_position_requests) else parseSs3(input[1..]);
        \\                if (inner.n == 0) return inner;
        \\                if (inner.event) |*event| switch (event.*) {
        \\                    .key_press, .key_release => |*key| key.mods.alt = true,
        \\                    else => {},
        \\                };
        \\                inner.n += 1;
        \\                return inner;
        \\            } else return .{ .event = .{ .key_press = .{ .codepoint = Key.escape, .mods = .{ .alt = true } } }, .n = 2 },
        \\            else => {
        ,
    },
    .{
        .old = "            const first_cp = iter.next() orelse return error.InvalidUTF8;\n",
        .new = "            const first_cp = iter.next() orelse return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n",
    },
    .{
        .old = "            n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return error.InvalidUTF8;\n",
        .new = "            n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n",
    },
    .{
        .old =
        \\    const sequence = input[0 .. end + 1 + 1];
        \\
        \\    switch (input[2]) {
        ,
        .new =
        \\    // pardes's patch (its build.zig): an ESC that ends the input is half an ST.
        \\    if (input.len < end + 2) return .{ .event = null, .n = 0 };
        \\    const sequence = input[0 .. end + 1 + 1];
        \\
        \\    switch (input[2]) {
        ,
    },
    .{
        .old =
        \\        'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => {
        \\            // Legacy keys
        \\
        ,
        .new =
        \\        'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => {
        \\            // pardes's patch (its build.zig): a cursor position report is no key.
        \\            if (final == 'R' and cursorReport(sequence)) return null_event;
        \\            // Legacy keys
        \\
        ,
    },
    .{
        .old = "            std.debug.assert(sequence.len >= 4); // ESC [ ? c == 4 bytes\n",
        .new = "            if (sequence.len < 4) return null_event; // pardes's patch (its build.zig)\n",
    },
    .{
        .old = "const delim_idx = std.mem.indexOfScalarPos(u8, input, 3, ';')",
        .new = "const delim_idx = std.mem.indexOfScalarPos(u8, sequence, 3, ';')",
        .count = 2,
    },
    .{
        .old = "input[delim_idx + 1 .. sequence.len - 2]",
        .new = "sequence[@min(delim_idx + 1, sequence.len - 2) .. sequence.len - 2]",
    },
    .{
        .old = "    if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) {\n",
        .new =
        \\    // pardes's patch (its build.zig): an X10 report still arriving is incomplete, not text.
        \\    if (input.len == 3 and input[2] == 'M' and full_input.len < 6) return .{ .event = null, .n = 0 };
        \\    if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) {
        \\
        ,
    },
};

/// vaxis's render: a blank whose ink alone changed is not sent, since a
/// blank's ink shows nowhere (build/patches/vaxis_render.zig). A fade
/// (InactiveDim on a focus change) sent every blank of every pane it
/// touched again: 7 KB a click for three shell panes. The terminal keeps
/// the old ink there, and so does vaxis's last frame. And the secondary
/// cursors count as changed when they differ, not when they are the
/// same: read the other way round, every render started a frame, ~40
/// bytes to the terminal with nothing changed.
const vaxis_render = [_]Edit{
    .{
        .old =
        \\        if ((!self.refresh and
        \\            last.eql(cell) and
        ,
        .new =
        \\        if ((!self.refresh and
        \\            (last.eql(cell) or blankInkOnly(&last, &cell)) and // pardes's patch (its build.zig)
        \\
        ,
    },
    .{
        .old = "        std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary);\n",
        .new = "        !std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary); // pardes's patch (its build.zig)\n",
    },
};

/// vaxis's event queue: a pop that makes room woke one blocked writer, and
/// only on the pop from full. The tui has two writers (a pane's pty
/// reader, and the input reader posting the frame ack's wake), so when the
/// loop emptied a full queue in one batch the writer not woken waited on
/// for good: under `yes` the pane stopped being read, its program blocked
/// on the pty, while keys went on working. Every blocked writer is woken now.
const vaxis_queue = [_]Edit{
    .{ .old = "self.not_full.signal(self.io);", .new = "self.not_full.broadcast(self.io); // pardes's patch (its build.zig)", .count = 2 },
};

pub fn vaxis(b: *std.Build, patch: *std.Build.Step.Compile, vaxis_dep: *std.Build.Dependency, vaxis_mod: *std.Build.Module) void {
    const files = b.addWriteFiles();
    _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/Parser.zig", &vaxis_parser, "vaxis_parser.zig"), "Parser.zig");
    _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/Vaxis.zig", &vaxis_render, "vaxis_render.zig"), "Vaxis.zig");
    _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/queue.zig", &vaxis_queue, null), "queue.zig");
    _ = files.addCopyFile(vaxis_dep.path("src/widgets/terminal/Parser.zig"), "widgets/terminal/Parser.zig");
    // Suffixes: this leaves out both Parser.zig files, Vaxis.zig and
    // queue.zig, written above.
    _ = files.addCopyDirectory(vaxis_dep.path("src"), "", .{ .exclude_extensions = &.{ "Parser.zig", "Vaxis.zig", "queue.zig" } });
    vaxis_mod.root_source_file = files.getDirectory().path(b, "main.zig");
}

/// zstbi with stb_image and its writer cut out: of it only its resize is
/// left, for a terminal PNG's downscale (build/core.zig, "One PNG
/// decoder"). zstbi.deinit still resets the reader's and the writer's flip
/// flags, and Image.deinit frees the resize's output.
const zstbi_cut = [_]Edit{
    .{ .old = "#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n", .new = "void stbi_set_flip_vertically_on_load(int flag) { (void)flag; }\nvoid stbi_image_free(void *p) { zstbiFreePtr(p); }\n" },
    .{ .old = "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n", .new = "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n" },
};

pub fn zstbi(b: *std.Build, patch: *std.Build.Step.Compile, zstbi_dep: *std.Build.Dependency, zstbi_mod: *std.Build.Module) void {
    var sources: usize = 0;
    for (zstbi_mod.link_objects.items) |obj| switch (obj) {
        .c_source_file => |csf| {
            sources += 1;
            csf.file = apply(b, patch, zstbi_dep, "src/zstbi.c", &zstbi_cut, null);
        },
        else => {},
    };
    if (sources != 1) @panic("zstbi's build no longer compiles one C file: redo its patch in build/patches.zig");
}

/// ghostty's kitty graphics loader (src/terminal/kitty/graphics_image.zig),
/// for what a program in a pane may name with t=f, t=t and t=s
/// (test/kitty.zig):
/// - a path is opened for reading only once it is known to be a regular
///   file: ghostty opens first and checks after, and the open of a FIFO
///   waits for a writer (pardes hung) while a device's open may do
///   something. On Linux an O_PATH probe looks, which opens nothing, and
///   the same inode is reopened through /proc/self/fd; elsewhere a stat by
///   path looks first (build/patches/ghostty_kitty.zig).
/// - shared memory is opened non-blocking and must be a regular file, so
///   a FIFO in /dev/shm (or a symlink there to one) neither hangs nor maps.
/// - an image may be no larger than a screen's storage
///   (TerminalImages.storage_limit) rather than ghostty's 400 MB, which a
///   program could make pardes read and hold before refusing it.
const ghostty_kitty = [_]Edit{
    .{
        .old = "const max_size = 400 * 1024 * 1024; // 400MB",
        .new = "const max_size = 64 * 1024 * 1024; // pardes (build.zig): a screen's storage, TerminalImages.storage_limit",
    },
    .{
        .old =
        \\        var file = std.Io.Dir.cwd().openFile(
        \\            io,
        \\            path,
        \\            .{},
        \\        ) catch |err| {
        ,
        .new =
        \\        var file = pardesOpenRegular(io, path) catch |err| {
        ,
    },
    .{
        .old = "        const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), @as(u16, 0));",
        .new =
        \\        // pardes (build.zig): a FIFO there must not hang the open, and
        \\        // on Linux nothing but a regular file is opened at all. FreeBSD's
        \\        // names are no files, and its shm_open refuses O_NONBLOCK.
        \\        if (comptime builtin.target.os.tag == .linux) if (path.len > 0 and path[0] == '/') {
        \\            var dev: [std.Io.Dir.max_path_bytes]u8 = undefined;
        \\            const full = std.fmt.bufPrint(&dev, "/dev/shm{s}", .{path}) catch return error.InvalidData;
        \\            const shm_stat = std.Io.Dir.cwd().statFile(io, full, .{}) catch return error.InvalidData;
        \\            if (shm_stat.kind != .file) return error.InvalidData;
        \\        };
        \\        const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY, .NONBLOCK = builtin.target.os.tag != .freebsd })), @as(u16, 0));
        ,
    },
    .{
        .old = "            if (stat.size <= 0) return error.InvalidData;",
        .new = "            if (stat.kind != .file) return error.InvalidData; // pardes (build.zig)\n            if (stat.size <= 0) return error.InvalidData;",
    },
};

/// ghostty's terminal page (src/terminal/page.zig): a page's size is
/// rounded to 4 KiB on every target, not to the OS page (4 KiB on Linux
/// and FreeBSD, 16 KiB on an Apple aarch64 Mac). The same bytes must give
/// the same emulator on every machine a client runs on, and the rounding
/// decides how many rows a page holds and how much room its style and link
/// tables grow to, so how many history rows the 16 MiB scrollback keeps:
/// a Mac had fewer than Linux once it was full, which the digest saw
/// (docs/ghostty-page-size.md). On Linux and FreeBSD this changes nothing;
/// a Mac maps whole 16 KiB pages under a length that is not one, up to
/// 12 KiB a page left unused, and ghostty's assertions that a page's
/// length is a whole number of OS pages (page.zig, mem.zig) ask for 4 KiB.
const ghostty_page = [_]Edit{
    .{
        .old = "        const total_size = alignForward(usize, meta_end, std.heap.page_size_min);\n",
        .new = "        const total_size = alignForward(usize, meta_end, 4 << 10); // pardes (build/patches.zig)\n",
    },
    .{
        .old = "        assert(l.total_size % std.heap.page_size_min == 0);\n",
        .new = "        assert(l.total_size % (4 << 10) == 0); // pardes (build/patches.zig)\n",
    },
};
const ghostty_mem = [_]Edit{.{
    .old = "    assert(memory.len % std.heap.page_size_min == 0);\n",
    .new = "    assert(memory.len % (4 << 10) == 0); // pardes (build/patches.zig): a page's size\n",
    .count = 2,
}};

pub fn ghosttyKitty(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, vt: *std.Build.Module) void {
    const files = b.addWriteFiles();
    // The rest of src as it is; fonts are the app's, not the library's.
    // ("terminal/page.zig" leaves terminal/snapshot/page.zig in.)
    _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", "terminal/page.zig", "terminal/mem.zig", ".ttf", ".otf" } });
    _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/kitty/graphics_image.zig", &ghostty_kitty, "ghostty_kitty.zig"), "terminal/kitty/graphics_image.zig");
    _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/page.zig", &ghostty_page, null), "terminal/page.zig");
    _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/mem.zig", &ghostty_mem, null), "terminal/mem.zig");
    vt.root_source_file = files.getDirectory().path(b, "lib_vt.zig");
}

/// mvzr, whose matcher pardes searches with while holding the editor:
/// - A step budget (build/patches/mvzr_budget.zig): mvzr backtracks with
///   no bound on its work (its own test "do not make this test any
///   longer": `a?` n times is 2^n steps), so each entry to matchPattern,
///   which its backtracking recurses through, spends a step, and with none
///   left the match fails and says so (core/regexp.zig).
/// - A group's greedy match never gave back to what follows the group: on
///   `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the group's
///   own `)` as an alternative, so every group with pattern after it takes
///   matchGroup's alternatives branch, which tries each alternative's one
///   (greedy) match and gives up. When the rest fails after it, try that
///   alternative's shorter matches, longest first
///   (docs/mvzr-group-backtrack.md is the report for upstream).
/// - `$` is refused anywhere but last, so `h$|zz` was a bad pattern while
///   `zz|h$` was fine. An alternative or a group ends at `|` and `)`, and
///   the matcher's `.end` ends the alternative it is in, so `$` may stand
///   before either (docs/mvzr-group-backtrack.md).
/// - Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it
///   upstream). A class's range ending at `\xff` counted to 256 in a u8, an
///   overflow (a panic in a safe build, a runaway loop in a fast one):
///   `[\x80-\xff]` in any search took the editor down.
/// - compile() read past the end of a pattern that stops inside a count
///   (`a{`, `a{,1`, `a{1`, `a{1,`, `a{1,2`), a byte escape (`\x`, `{\\x`)
///   or a class (`[\`, `[\x`, `[\x41`, `[\\x]`): a panic in a safe build
///   on the second key of a search for `a{2}`; in a fast one the bytes
///   after the pattern decided what it meant, so a session and its client
///   could compile one typed pattern differently. Unreported upstream as
///   of 3efcfe33 (its trunk on 2026-11-19); docs/mvzr-bounds.md is the
///   report for it.
const mvzr_edits = [_]Edit{
    .{
        .old = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n",
        .new =
        \\fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {
        \\    if (steps_left == 0) {
        \\        exhausted = true;
        \\        return null;
        \\    }
        \\    steps_left -= 1;
        \\
        ,
    },
    .{
        .old =
        \\            const next_match = matchPattern(next_patt, sets, haystack, m1.i);
        \\            if (next_match) |m2| {
        \\                // Whole group matches, and we can use m2.j
        \\                return m2;
        \\            } else { // Try our next pattern, if any.
        \\
        ,
        .new =
        \\            const next_match = matchPattern(next_patt, sets, haystack, m1.i);
        \\            if (next_match) |m2| {
        \\                // Whole group matches, and we can use m2.j
        \\                return m2;
        \\            } else { // Try our next pattern, if any.
        \\                // pardes's patch (its build.zig): back the group off.
        \\                var e = m1.i;
        \\                while (e > i) {
        \\                    e -= 1;
        \\                    const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue;
        \\                    if (shorter.i != e) continue;
        \\                    if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole;
        \\                }
        \\
        ,
    },
    .{
        .old =
        \\            '$' => {
        \\                if (i + 1 < in.len) {
        \\
        ,
        .new =
        \\            '$' => {
        \\                // pardes's patch (its build.zig): `$` may end an alternative.
        \\                if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') {
        \\
        ,
    },
    // A pattern cut short inside a count, a byte escape or a class: each
    // read checks the pattern's end first (a bad string, as its other
    // malformed patterns are).
    .{ .old = "fn parseHex(in: []const u8) !u8 {\n", .new = "fn parseHex(in: []const u8) !u8 {\n    if (in.len < 2) return error.BadString;\n" },
    .{ .old = "                i += 1;\n                if (in[i] == ',') { // {,?\n", .new = "                i += 1;\n                if (i == in.len) {\n                    bad_string = true;\n                    break :dispatch;\n                }\n                if (in[i] == ',') { // {,?\n" },
    .{ .old = "                    if (in[i] == '}') { // {,N}\n", .new = "                    if (i < in.len and in[i] == '}') { // {,N}\n" },
    .{ .old = "                i += d1;\n                if (in[i] == ',') { // {M,?\n                    i += 1;\n                    if (in[i] == '}') { // {M,}\n", .new = "                i += d1;\n                if (i == in.len) {\n                    bad_string = true;\n                    break :dispatch;\n                }\n                if (in[i] == ',') { // {M,?\n                    i += 1;\n                    if (i < in.len and in[i] == '}') { // {M,}\n" },
    .{ .old = "                    i += d2;\n                    if (in[i] != '}') {\n", .new = "                    i += d2;\n                    if (i == in.len or in[i] != '}') {\n" },
    .{ .old = "fn valueFor(in: []const u8) ?u8 {\n", .new = "fn valueFor(in: []const u8) ?u8 {\n    if (in.len == 0) return null;\n" },
    .{ .old = "                return parseHex(in[1..4]) catch return null;\n", .new = "                return parseHex(in[1..3]) catch return null;\n" },
    .{ .old = "    if (i == in.len or in[i] != ']') {\n        return BadString;\n", .new = "    if (i >= in.len or in[i] != ']') {\n        return BadString;\n" },
    .{ .old = "for (c1..c2 + 1) |c_range|", .new = "for (c1..@as(usize, c2) + 1) |c_range|" },
    .{ .old = "[1]RegOp{.{ .unused = {} }} ** ops", .new = "@splat(.{ .unused = {} })" },
    .{ .old = "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", .new = "@splat(.{ .low = 0, .hi = 0 })" },
    .{ .old = "\"a\" ** 2048", .new = "&@as([2048]u8, @splat('a'))", .count = 2 },
    .{ .old = "\"12345,\" ** 255", .new = "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))" },
};

pub fn mvzr(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module {
    return b.createModule(.{ .root_source_file = apply(b, patch, dep, "src/mvzr.zig", &mvzr_edits, "mvzr_budget.zig"), .target = target, .optimize = optimize });
}