robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 9a29622b3b00ddb601

master
39.5 KiB994 linesraw
1const std = @import("std");
2const LazyPath = std.Build.LazyPath;
3const Compile = std.Build.Step.Compile;
4const build_lua = @import("src/build_lua.zig");
5const gen = @import("src/gen/gen_steps.zig");
6const runtime = @import("runtime/gen_runtime.zig");
7const tests = @import("test/run_tests.zig");
8const zcc = @import("compile_commands");
9const lint = @import("src/lint.zig");
10
11const version = struct {
12    const major = 0;
13    const minor = 13;
14    const patch = 0;
15    const prerelease = "-dev";
16
17    const api_level = 15;
18    const api_level_compat = 0;
19    const api_prerelease = true;
20};
21
22pub const SystemIntegrationOptions = packed struct {
23    lua: bool,
24    tree_sitter: bool,
25    unibilium: bool,
26    utf8proc: bool,
27    uv: bool,
28};
29
30// TODO(bfredl): this is for an upstream issue
31pub fn lazyArtifact(d: *std.Build.Dependency, name: []const u8) ?*std.Build.Step.Compile {
32    var found: ?*std.Build.Step.Compile = null;
33    for (d.builder.install_tls.step.dependencies.items) |dep_step| {
34        const inst = dep_step.cast(std.Build.Step.InstallArtifact) orelse continue;
35        if (std.mem.eql(u8, inst.artifact.name, name)) {
36            if (found != null) std.debug.panic("artifact name '{s}' is ambiguous", .{name});
37            found = inst.artifact;
38        }
39    }
40    return found;
41}
42
43fn addEmscriptenIncludes(emscripten_include: ?std.Build.LazyPath, artifact: *std.Build.Step.Compile) void {
44    if (emscripten_include) |inc| {
45        artifact.root_module.addSystemIncludePath(inc);
46    }
47}
48
49pub fn build(b: *std.Build) !void {
50    const target = b.standardTargetOptions(.{});
51    const optimize = b.standardOptimizeOption(.{});
52    const io = b.graph.io;
53
54    const t = target.result;
55    const os_tag = t.os.tag;
56    const is_windows = (os_tag == .windows);
57    const is_linux = (os_tag == .linux);
58    const is_darwin = os_tag.isDarwin();
59    const modern_unix = is_darwin or os_tag.isBSD() or is_linux;
60    const is_wasm = t.cpu.arch == .wasm32;
61
62    const h = b.graph.host.result;
63    const host = b.option([]const u8, "host", "target for host ") orelse
64        if (target.query.isNative() or h.cpu.arch == t.cpu.arch and h.os.tag == t.os.tag) "" else "native";
65    const cross_compiling = host.len > 0;
66    const target_host = if (cross_compiling) b.resolveTargetQuery(try std.Build.parseTargetQuery(.{ .arch_os_abi = host })) else target;
67
68    const emscripten_sysroot = b.option([]const u8, "emscripten-sysroot", "path to emscripten sysroot");
69    const emscripten_include = if (emscripten_sysroot) |s|
70        std.Build.LazyPath{ .cwd_relative = b.pathJoin(&.{ s, "include" }) }
71    else
72        null;
73
74    const emscripten_libc_path: ?std.Build.LazyPath = if (is_wasm) blk: {
75        if (emscripten_sysroot) |s| {
76            const libc_txt = b.fmt(
77                "include_dir={s}/include\nsys_include_dir={s}/include\ncrt_dir={s}/lib/wasm32-emscripten\nmsvc_lib_dir=\nkernel32_lib_dir=\ngcc_dir=\n",
78                .{ s, s, s },
79            );
80            const wf = b.addWriteFiles();
81            break :blk wf.add("emscripten-libc.txt", libc_txt);
82        }
83        break :blk null;
84    } else null;
85
86    // without cross_compiling we like to reuse libluv etc at the same optimize level
87    const optimize_host = if (cross_compiling) .ReleaseSafe else optimize;
88
89    const use_unibilium = b.option(bool, "unibilium", "use unibilium") orelse true;
90
91    // puc lua 5.1 is not ReleaseSafe "safe"
92    const optimize_lua = if (optimize == .Debug or optimize == .ReleaseSafe) .ReleaseSmall else optimize;
93
94    const use_luajit = b.option(bool, "luajit", "use luajit") orelse !is_wasm;
95    const lualib_name = if (use_luajit) "luajit" else "lua5.1";
96    const host_use_luajit = if (cross_compiling) false else use_luajit;
97    const E = enum { luajit, lua51 };
98
99    const sys_opts = SystemIntegrationOptions{
100        .lua = b.systemIntegrationOption("lua", .{}),
101        .tree_sitter = b.systemIntegrationOption("tree-sitter", .{}),
102        .unibilium = b.systemIntegrationOption("unibilium", .{}),
103        .utf8proc = b.systemIntegrationOption("utf8proc", .{}),
104        .uv = b.systemIntegrationOption("uv", .{}),
105    };
106    const ci_build = b.option(bool, "ci-build", "CI build") orelse false;
107
108    const libc = libc: {
109        break :libc std.zig.LibCDirs.detect(
110            b.graph.arena,
111            b.graph.io,
112            b.graph.zig_lib_directory.path orelse break :libc error.NoZigLib,
113            &t,
114            target.query.isNativeAbi(),
115            true,
116            null,
117            &b.graph.environ_map,
118        );
119    } catch |err| std.debug.panic("failed to locate libc: {s}", .{@errorName(err)});
120
121    const additional_system_headers = b.option([]std.Build.LazyPath, "additional_system_headers", "Slice of Lazy paths to additional system headers to include") orelse null;
122
123    var libc_include_paths: std.ArrayList(std.Build.LazyPath) = try .initCapacity(b.allocator, libc.libc_include_dir_list.len);
124    for (libc.libc_include_dir_list) |include_dir|
125        try libc_include_paths.append(b.allocator, .{ .cwd_relative = include_dir });
126
127    const include_paths = try std.mem.concat(b.allocator, LazyPath, &.{ libc_include_paths.items, additional_system_headers orelse &.{} });
128
129    const ziglua = b.dependency("zlua", .{
130        .target = target,
131        .optimize = optimize_lua,
132        .lang = if (use_luajit) E.luajit else E.lua51,
133        .shared = false,
134        .system_lua = sys_opts.lua,
135        .additional_system_headers = include_paths,
136    });
137    const ziglua_host = if (cross_compiling) b.dependency("zlua", .{
138        .target = target_host,
139        .optimize = .ReleaseSmall,
140        .lang = if (host_use_luajit) E.luajit else E.lua51,
141        .system_lua = sys_opts.lua,
142        .shared = false,
143        .additional_system_headers = include_paths,
144    }) else ziglua;
145    var lua: ?*Compile = null;
146    var libuv: ?*Compile = null;
147    var libluv: ?*Compile = null;
148    var libluv_host: ?*Compile = null;
149    if (!sys_opts.lua) {
150        // this is currently not necessary, as ziglua currently doesn't use lazy dependencies
151        // to circumvent ziglua.artifact() failing in a bad way.
152        lua = lazyArtifact(ziglua, "lua") orelse return;
153        addEmscriptenIncludes(emscripten_include, lua.?);
154
155        if (cross_compiling) {
156            _ = lazyArtifact(ziglua_host, "lua") orelse return;
157        }
158    }
159    if (!sys_opts.uv) {
160        // NOTE: libuv on Windows depends on Windows SDK when compiled with .Debug mode
161        // https://github.com/neovim/neovim/issues/36889
162        const optimize_uv = if (optimize == .Debug and target.result.os.tag == .windows) .ReleaseSafe else optimize;
163        if (b.lazyDependency("libuv", .{ .target = target, .optimize = optimize_uv })) |dep| {
164            libuv = dep.artifact("uv");
165
166            if (emscripten_libc_path) |lp| libuv.?.setLibCFile(lp);
167            addEmscriptenIncludes(emscripten_include, libuv.?);
168
169            libluv = try build_lua.build_libluv(b, target, optimize, lua, libuv.?, use_luajit);
170
171            if (libluv) |luv| addEmscriptenIncludes(emscripten_include, luv);
172
173            libluv_host = if (cross_compiling) libluv_host: {
174                const libuv_dep_host = b.lazyDependency("libuv", .{
175                    .target = target_host,
176                    .optimize = optimize_host,
177                });
178                const libuv_host = libuv_dep_host.?.artifact("uv");
179                break :libluv_host try build_lua.build_libluv(
180                    b,
181                    target_host,
182                    optimize_host,
183                    ziglua_host.artifact("lua"),
184                    libuv_host,
185                    host_use_luajit,
186                );
187            } else libluv;
188        }
189    }
190
191    const iconv = if (is_windows) b.lazyDependency("libiconv", .{
192        .target = target,
193        .optimize = optimize,
194    }) else null;
195
196    const utf8proc = if (sys_opts.utf8proc) null else b.lazyDependency("utf8proc", .{
197        .target = target,
198        .optimize = optimize,
199    });
200
201    const unibilium = if (use_unibilium and !sys_opts.unibilium) b.lazyDependency("unibilium", .{
202        .target = target,
203        .optimize = optimize,
204    }) else null;
205
206    // TODO(bfredl): fix upstream bugs with UBSAN
207    const optimize_ts = .ReleaseFast;
208    const treesitter = if (sys_opts.tree_sitter) null else b.lazyDependency("treesitter", .{
209        .target = target,
210        .optimize = optimize_ts,
211    });
212
213    if (utf8proc) |dep|
214        addEmscriptenIncludes(emscripten_include, dep.artifact("utf8proc"));
215
216    if (unibilium) |dep|
217        addEmscriptenIncludes(emscripten_include, dep.artifact("unibilium"));
218
219    if (treesitter) |dep|
220        addEmscriptenIncludes(emscripten_include, dep.artifact("tree-sitter"));
221
222    const nlua0 = try build_lua.build_nlua0(
223        b,
224        target_host,
225        optimize_host,
226        host_use_luajit,
227        ziglua_host,
228        libluv_host,
229        sys_opts,
230    );
231
232    // usual caveat emptor: might need to force a rebuild if the only change is
233    // addition of new .c files, as those are not seen by any hash
234    const subdirs = [_][]const u8{
235        "", // src/nvim itself
236        "os/",
237        "api/",
238        "api/private/",
239        "msgpack_rpc/",
240        "tui/",
241        "tui/termkey/",
242        "event/",
243        "eval/",
244        "lib/",
245        "lua/",
246        "viml/",
247        "viml/parser/",
248        "vterm/",
249    };
250
251    // source names _relative_ src/nvim/, not including other src/ subdircs
252    var nvim_sources = try std.ArrayList(gen.SourceItem).initCapacity(b.allocator, 100);
253    var nvim_headers = try std.ArrayList([]u8).initCapacity(b.allocator, 100);
254
255    // both source headers and the {module}.h.generated.h files
256    var api_headers = try std.ArrayList(std.Build.LazyPath).initCapacity(b.allocator, 10);
257
258    // TODO(bfredl): these should just become subdirs..
259    const windows_only = [_][]const u8{
260        "pty_proc_win.c",
261        "pty_proc_win.h",
262        "pty_conpty_win.c",
263        "pty_conpty_win.h",
264        "os_win_console.c",
265        "win_defs.h",
266    };
267    const unix_only = [_][]const u8{ "unix_defs.h", "pty_proc_unix.c", "pty_proc_unix.h" };
268    const exclude_list = if (is_windows) &unix_only else &windows_only;
269
270    const src_dir = b.build_root.handle;
271    for (subdirs) |s| {
272        var dir = try src_dir.openDir(io, b.fmt("src/nvim/{s}", .{s}), .{ .iterate = true });
273        defer dir.close(io);
274        var it = dir.iterateAssumeFirstIteration();
275        const api_export = std.mem.eql(u8, s, "api/");
276        const os_check = std.mem.eql(u8, s, "os/");
277        entries: while (try it.next(io)) |entry| {
278            if (entry.name.len < 3) continue;
279            if (entry.name[0] < 'a' or entry.name[0] > 'z') continue;
280            if (os_check) {
281                for (exclude_list) |name| {
282                    if (std.mem.eql(u8, name, entry.name)) {
283                        continue :entries;
284                    }
285                }
286            }
287            if (std.mem.eql(u8, ".c", entry.name[entry.name.len - 2 ..])) {
288                try nvim_sources.append(b.allocator, .{
289                    .name = b.fmt("{s}{s}", .{ s, entry.name }),
290                    .api_export = api_export,
291                });
292            }
293            if (std.mem.eql(u8, ".h", entry.name[entry.name.len - 2 ..])) {
294                try nvim_headers.append(b.allocator, b.fmt("{s}{s}", .{ s, entry.name }));
295                if (api_export and !std.mem.eql(u8, "ui_events.in.h", entry.name)) {
296                    try api_headers.append(b.allocator, b.path(b.fmt("src/nvim/{s}{s}", .{ s, entry.name })));
297                }
298            }
299        }
300    }
301
302    const support_unittests = use_luajit;
303
304    const gen_config = b.addWriteFiles();
305
306    const version_lua = gen_config.add("nvim_version.lua", lua_version_info(b));
307
308    // Note: these represent the actually resolved target and host platforms, which are often
309    // more verbose than what needs to be passed in (often -Dhost=native is auto-decteted)
310    // TODO(bfredl): we could include stuff like specific cpu features and os version but eh
311    var config_str = b.fmt("zig build -Doptimize={s} -Dtarget={s}", .{ @tagName(optimize), try t.linuxTriple(b.graph.arena) });
312    if (cross_compiling) {
313        config_str = b.fmt("{s} -Dhost={s}", .{ config_str, try target_host.result.linuxTriple(b.graph.arena) });
314    }
315
316    const versiondef_step = b.addConfigHeader(.{
317        .style = .{ .cmake = b.path("cmake.config/versiondef.h.in") },
318    }, .{
319        .NVIM_VERSION_MAJOR = version.major,
320        .NVIM_VERSION_MINOR = version.minor,
321        .NVIM_VERSION_PATCH = version.patch,
322        .NVIM_VERSION_PRERELEASE = version.prerelease,
323        .NVIM_VERSION_MEDIUM = "",
324        .VERSION_STRING = "TODO", // TODO(bfredl): not sure what to put here. summary already in "config_str"
325        .CONFIG = config_str,
326    });
327    _ = gen_config.addCopyFile(versiondef_step.getOutputFile(), "auto/versiondef.h"); // run_preprocessor() workaronnd
328
329    const ptrwidth = t.ptrBitWidth() / 8;
330    const sysconfig_step = b.addConfigHeader(.{
331        .style = .{ .cmake = b.path("cmake.config/config.h.in") },
332    }, .{
333        .SIZEOF_INT = t.cTypeByteSize(.int),
334        .SIZEOF_INTMAX_T = t.cTypeByteSize(.longlong), // TODO
335        .SIZEOF_LONG = t.cTypeByteSize(.long),
336        .SIZEOF_SIZE_T = ptrwidth,
337        .SIZEOF_VOID_PTR = ptrwidth,
338
339        .PROJECT_NAME = "nvim",
340
341        .HAVE__NSGETENVIRON = is_darwin,
342        .HAVE_FD_CLOEXEC = modern_unix,
343        .HAVE_FSEEKO = modern_unix,
344        .HAVE_LANGINFO_H = modern_unix,
345        .HAVE_NL_LANGINFO_CODESET = modern_unix,
346        .HAVE_NL_MSG_CAT_CNTR = t.isGnuLibC(),
347        .HAVE_PWD_FUNCS = modern_unix,
348        .HAVE_READLINK = modern_unix,
349        .HAVE_STRNLEN = modern_unix,
350        .HAVE_STRCASECMP = modern_unix,
351        .HAVE_STRINGS_H = modern_unix,
352        .HAVE_STRNCASECMP = modern_unix,
353        .HAVE_STRPTIME = modern_unix,
354        .HAVE_XATTR = is_linux,
355        .HAVE_SYS_SDT_H = false,
356        .HAVE_SYS_UTSNAME_H = modern_unix or is_wasm,
357        .HAVE_SYS_WAIT_H = false, // unused
358        .HAVE_TERMIOS_H = modern_unix,
359        .HAVE_WORKING_LIBINTL = t.isGnuLibC(),
360        .UNIX = modern_unix,
361        .CASE_INSENSITIVE_FILENAME = is_darwin or is_windows,
362        .HAVE_SYS_UIO_H = modern_unix,
363        .HAVE_READV = modern_unix,
364        .HAVE_DIRFD_AND_FLOCK = modern_unix,
365        .HAVE_FORKPTY = modern_unix and !is_darwin, // also on Darwin but we lack the headers :(
366        .HAVE_BE64TOH = modern_unix and !is_darwin,
367        .ORDER_BIG_ENDIAN = t.cpu.arch.endian() == .big,
368        .ENDIAN_INCLUDE_FILE = "endian.h",
369        .HAVE_EXECINFO_BACKTRACE = modern_unix and !t.isMuslLibC(),
370        .HAVE_BUILTIN_ADD_OVERFLOW = true,
371        .HAVE_WIMPLICIT_FALLTHROUGH_FLAG = true,
372        .HAVE_BITSCANFORWARD64 = null,
373
374        .VTERM_TEST_FILE = "test/vterm_test_output", // TODO(bfredl): revisit when porting libvterm tests
375    });
376
377    _ = gen_config.addCopyFile(sysconfig_step.getOutputFile(), "auto/config.h"); // run_preprocessor() workaronnd
378    //
379    const system_install_path = b.option([]const u8, "install-path", "Install path (for packagers)");
380    const vim_dir, const lib_dir = if (system_install_path) |path| confinstall: {
381        const good_path = try replace_backslashes(b, path);
382        break :confinstall .{ b.fmt("{s}/share/nvim", .{good_path}), b.fmt("{s}/lib/nvim", .{good_path}) };
383    } else .{ "", "" };
384
385    _ = gen_config.add("auto/pathdef.h", b.fmt(
386        \\char *default_vim_dir = "{s}";
387        \\char *default_vimruntime_dir = "";
388        \\char *default_lib_dir = "{s}";
389    , .{ vim_dir, lib_dir }));
390
391    const opt_version_string = b.option(
392        []const u8,
393        "version-string",
394        "Override Neovim version string. Default is to find out with git.",
395    );
396    const version_medium = if (opt_version_string) |version_string| version_string else v: {
397        var code: u8 = undefined;
398        const version_string = b.fmt("v{d}.{d}.{d}-laufey", .{
399            version.major,
400            version.minor,
401            version.patch,
402        });
403        const git_describe_untrimmed = b.runAllowFail(&[_][]const u8{
404            "git",
405            "-C", b.build_root.path orelse ".", // affects the --git-dir argument
406            "--git-dir", ".git", // affected by the -C argument
407            "describe", "--dirty", "--match", "v*.*.*", //
408        }, &code, .ignore) catch {
409            break :v version_string;
410        };
411        const git_describe = std.mem.trim(u8, git_describe_untrimmed, " \n\r");
412
413        const num_parts = std.mem.count(u8, git_describe, "-") + 1;
414        if (num_parts < 3) {
415            break :v version_string; // achtung: unrecognized format
416        }
417
418        var it = std.mem.splitScalar(u8, git_describe, '-');
419        const tagged_ancestor = it.first();
420        _ = tagged_ancestor;
421        const commit_height = it.next().?;
422        const commit_id = it.next().?;
423        const maybe_dirty = it.next();
424
425        // Check that the commit hash is prefixed with a 'g' (a Git convention).
426        if (commit_id.len < 1 or commit_id[0] != 'g') {
427            std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe});
428            break :v version_string;
429        }
430
431        const dirty_tag = if (maybe_dirty) |dirty| b.fmt("-{s}", .{dirty}) else "";
432
433        break :v b.fmt("{s}-dev-{s}+{s}{s}", .{ version_string, commit_height, commit_id, dirty_tag });
434    };
435
436    const versiondef_git = gen_config.add("auto/versiondef_git.h", b.fmt(
437        \\#define NVIM_VERSION_MEDIUM "{s}"
438        \\#define NVIM_VERSION_BUILD "zig"
439        \\
440    , .{version_medium}));
441
442    // TODO(zig): using getEmittedIncludeTree() is ugly af. we want unittests
443    // to reuse the std.build.Module include_path thing
444    var unittest_include_path: std.ArrayList(LazyPath) = try .initCapacity(b.allocator, 2);
445    try unittest_include_path.append(b.allocator, b.path("src/"));
446    try unittest_include_path.append(b.allocator, gen_config.getDirectory());
447    if (sys_opts.lua) {
448        try appendSystemIncludePath(b, &unittest_include_path, lualib_name);
449    } else if (lua) |compile| {
450        try unittest_include_path.append(b.allocator, compile.getEmittedIncludeTree());
451    }
452    if (sys_opts.uv) {
453        try appendSystemIncludePath(b, &unittest_include_path, "libuv");
454        try appendSystemIncludePath(b, &unittest_include_path, "libluv");
455    } else {
456        if (libuv) |compile| try unittest_include_path.append(b.allocator, compile.getEmittedIncludeTree());
457        if (libluv) |compile| try unittest_include_path.append(b.allocator, compile.getEmittedIncludeTree());
458    }
459    if (sys_opts.utf8proc) {
460        try appendSystemIncludePath(b, &unittest_include_path, "libutf8proc");
461    } else if (utf8proc) |dep| {
462        try unittest_include_path.append(b.allocator, dep.artifact("utf8proc").getEmittedIncludeTree());
463    }
464    if (use_unibilium) {
465        if (sys_opts.unibilium) {
466            try appendSystemIncludePath(b, &unittest_include_path, "unibilium");
467        } else if (unibilium) |dep| {
468            try unittest_include_path.append(b.allocator, dep.artifact("unibilium").getEmittedIncludeTree());
469        }
470    }
471    if (sys_opts.tree_sitter) {
472        try appendSystemIncludePath(b, &unittest_include_path, "tree-sitter");
473    } else if (treesitter) |dep| {
474        try unittest_include_path.append(b.allocator, dep.artifact("tree-sitter").getEmittedIncludeTree());
475    }
476    if (iconv) |dep| {
477        try unittest_include_path.append(b.allocator, dep.artifact("iconv").getEmittedIncludeTree());
478    }
479
480    const gen_headers, const funcs_data = try gen.nvim_gen_sources(
481        b,
482        nlua0,
483        &nvim_sources,
484        &nvim_headers,
485        &api_headers,
486        versiondef_git,
487        version_lua,
488        !cross_compiling,
489    );
490
491    const test_config_step = b.addWriteFiles();
492    _ = test_config_step.add("test/cmakeconfig/paths.lua", try test_config(b));
493
494    const test_gen_step = b.step("gen_headers", "debug: output generated headers");
495    const config_install = b.addInstallDirectory(.{
496        .source_dir = gen_config.getDirectory(),
497        .install_dir = .prefix,
498        .install_subdir = "config/",
499    });
500    test_gen_step.dependOn(&config_install.step);
501    test_gen_step.dependOn(&b.addInstallDirectory(.{
502        .source_dir = gen_headers.getDirectory(),
503        .install_dir = .prefix,
504        .install_subdir = "headers/",
505    }).step);
506
507    var nvim_mod = b.createModule(.{
508        .target = target,
509        .optimize = optimize,
510        .link_libc = true,
511    });
512
513    const nvim_exe = if (is_wasm) b.addLibrary(.{
514        .linkage = .static,
515        .name = "lf",
516        .root_module = nvim_mod,
517    }) else b.addExecutable(.{ .name = "lf", .root_module = nvim_mod });
518    nvim_exe.rdynamic = true; // -E
519    nvim_exe.link_gc_sections = false; // prevent linker from gc:ing exported symbols #40622
520    if (emscripten_libc_path) |lp| nvim_exe.setLibCFile(lp);
521    if (is_wasm) nvim_exe.entry = .disabled;
522    if (is_wasm) nvim_exe.linker_allow_shlib_undefined = true;
523
524    for (include_paths) |include_dir| {
525        nvim_exe.root_module.addSystemIncludePath(include_dir);
526        nlua0.root_module.addSystemIncludePath(include_dir);
527    }
528
529    if (sys_opts.lua) {
530        nvim_exe.root_module.linkSystemLibrary(lualib_name, .{});
531    } else if (lua) |compile| {
532        nvim_mod.linkLibrary(compile);
533    }
534    if (sys_opts.uv) {
535        nvim_mod.linkSystemLibrary("libuv", .{});
536        nvim_mod.linkSystemLibrary("libluv", .{});
537    } else {
538        if (libuv) |compile| nvim_mod.linkLibrary(compile);
539        if (libluv) |compile| nvim_mod.linkLibrary(compile);
540    }
541    if (iconv) |dep| {
542        nvim_mod.linkLibrary(dep.artifact("iconv"));
543    } else if (is_darwin) {
544        nvim_mod.linkSystemLibrary("iconv", .{});
545    }
546    if (sys_opts.utf8proc) {
547        nvim_mod.linkSystemLibrary("utf8proc", .{});
548    } else if (utf8proc) |dep| {
549        nvim_mod.linkLibrary(dep.artifact("utf8proc"));
550    }
551    if (use_unibilium) {
552        if (sys_opts.unibilium) {
553            nvim_mod.linkSystemLibrary("unibilium", .{});
554        } else if (unibilium) |dep| {
555            nvim_mod.linkLibrary(dep.artifact("unibilium"));
556        }
557    }
558    if (sys_opts.tree_sitter) {
559        nvim_mod.linkSystemLibrary("tree-sitter", .{});
560    } else if (treesitter) |dep| {
561        nvim_mod.linkLibrary(dep.artifact("tree-sitter"));
562    }
563    if (is_windows) {
564        nvim_mod.linkSystemLibrary("netapi32", .{});
565    }
566    nvim_mod.addIncludePath(b.path("src"));
567    nvim_mod.addIncludePath(gen_config.getDirectory());
568    nvim_mod.addIncludePath(gen_headers.getDirectory());
569    try build_lua.add_lua_modules(nvim_mod, use_luajit, false);
570
571    var unit_test_sources = try std.ArrayList([]u8).initCapacity(b.allocator, 10);
572    if (support_unittests) {
573        var unit_test_fixtures = try src_dir.openDir(io, "test/unit/fixtures/", .{ .iterate = true });
574        defer unit_test_fixtures.close(io);
575        var it = unit_test_fixtures.iterateAssumeFirstIteration();
576        while (try it.next(io)) |entry| {
577            if (entry.name.len < 3) continue;
578            if (std.mem.eql(u8, ".c", entry.name[entry.name.len - 2 ..])) {
579                try unit_test_sources.append(b.allocator, b.fmt("test/unit/fixtures/{s}", .{entry.name}));
580            }
581        }
582    }
583
584    var filtered_sources = try std.ArrayList([]u8).initCapacity(b.allocator, nvim_sources.items.len);
585    for (nvim_sources.items) |s| {
586        try filtered_sources.append(b.allocator, b.fmt("src/nvim/{s}", .{s.name}));
587    }
588    const src_paths = try b.allocator.alloc([]u8, filtered_sources.items.len + unit_test_sources.items.len);
589    @memcpy(src_paths[0..filtered_sources.items.len], filtered_sources.items);
590    @memcpy(src_paths[filtered_sources.items.len..], unit_test_sources.items);
591
592    const flags = [_][]const u8{
593        "-std=gnu99",
594        "-DZIG_BUILD",
595        "-D_GNU_SOURCE",
596        if (support_unittests) "-DUNIT_TESTING" else "",
597        if (use_luajit) "" else "-DNVIM_VENDOR_BIT",
598        if (is_windows) "-DMSWIN" else "",
599        if (is_windows) "-DWIN32_LEAN_AND_MEAN" else "",
600        if (is_windows) "-DUTF8PROC_STATIC" else "",
601        if (use_unibilium) "-DHAVE_UNIBILIUM" else "",
602        if (is_wasm) "-flto" else "",
603        if (is_wasm) "-DMAKE_LIB" else "",
604    };
605    nvim_mod.addCSourceFiles(.{ .files = src_paths, .flags = &flags });
606
607    nvim_mod.addCSourceFiles(.{ .files = &.{
608        "src/xdiff/xdiffi.c",
609        "src/xdiff/xemit.c",
610        "src/xdiff/xhistogram.c",
611        "src/xdiff/xpatience.c",
612        "src/xdiff/xprepare.c",
613        "src/xdiff/xutils.c",
614        "src/cjson/lua_cjson.c",
615        "src/cjson/fpconv.c",
616        "src/cjson/strbuf.c",
617    }, .flags = &flags });
618
619    if (is_wasm) {
620        nvim_mod.addCSourceFiles(.{ .files = &.{
621            "src/wasm/wasm_stubs.c",
622            "src/static_ts_registry.c",
623        }, .flags = &flags });
624    }
625
626    if (is_windows) {
627        nvim_mod.addWin32ResourceFile(.{ .file = b.path("src/nvim/os/nvim.rc") });
628    }
629
630    const nvim_exe_step = b.step("nvim_bin", "only the binary (not a fully working install!)");
631    const nvim_exe_install = b.addInstallArtifact(nvim_exe, .{ .dest_dir = if (is_wasm) .{ .override = .{ .custom = "wasm" } } else .default });
632    const gen_runtime = try runtime.nvim_gen_runtime(b, nlua0, funcs_data);
633
634    if (is_wasm) {
635        const s = emscripten_sysroot orelse @panic("-Demscripten-sysroot required for wasm target");
636        const emcc = b.addSystemCommand(&.{"emcc"});
637        emcc.step.dependOn(&nvim_exe.step);
638
639        emcc.addArg("-Wl,--whole-archive");
640        emcc.addFileArg(nvim_exe.getEmittedBin());
641        if (lua) |l| emcc.addFileArg(l.getEmittedBin());
642        if (libuv) |uv| emcc.addFileArg(uv.getEmittedBin());
643        if (libluv) |luv| emcc.addFileArg(luv.getEmittedBin());
644        if (utf8proc) |dep| emcc.addFileArg(dep.artifact("utf8proc").getEmittedBin());
645        if (unibilium) |dep| emcc.addFileArg(dep.artifact("unibilium").getEmittedBin());
646        if (treesitter) |dep| emcc.addFileArg(dep.artifact("tree-sitter").getEmittedBin());
647        emcc.addArg("-Wl,--no-whole-archive");
648
649        const merged_subdir = "wasm-runtime-merged";
650        const merged_path = b.getInstallPath(.prefix, merged_subdir);
651        const install_static_runtime = b.addInstallDirectory(.{
652            .source_dir = b.path("runtime"),
653            .install_dir = .prefix,
654            .install_subdir = merged_subdir,
655        });
656        const install_gen_runtime = b.addInstallDirectory(.{
657            .source_dir = gen_runtime.getDirectory(),
658            .install_dir = .prefix,
659            .install_subdir = merged_subdir,
660        });
661
662        emcc.step.dependOn(&install_static_runtime.step);
663        emcc.step.dependOn(&install_gen_runtime.step);
664
665        emcc.addArgs(&.{
666            b.fmt("--sysroot={s}", .{s}),
667            "-lidbfs.js",
668            "--profiling-funcs",
669            "-sEXPORTED_FUNCTIONS=_nvim_main,_malloc,_free",
670            "-Wno-undefined",
671            "-sEXPORTED_RUNTIME_METHODS=stringToUTF8,lengthBytesUTF8,setValue,getValue,UTF8ToString,ENV,FS,HEAPU8,IDBFS,ccall,cwrap",
672            "-sSTACK_SIZE=8388608",
673            "-sINITIAL_MEMORY=268435456",
674            "-sFORCE_FILESYSTEM=1",
675            "-sNODERAWFS=0",
676            "-sERROR_ON_UNDEFINED_SYMBOLS=1",
677            "-sEXIT_RUNTIME=0",
678            "-sINVOKE_RUN=0",
679            "-sMODULARIZE=1",
680            "-sEXPORT_NAME=createNvim",
681            "--no-entry",
682            "-fexceptions",
683            "-flto",
684            "-sSTACK_OVERFLOW_CHECK=2",
685            "-sASSERTIONS=1",
686            "-pthread",
687            "-sSHARED_MEMORY=1",
688            b.fmt("--preload-file={s}@/runtime", .{merged_path}),
689        });
690
691        emcc.addArg("-o");
692        const nvim_js = emcc.addOutputFileArg("nvim.js");
693        nvim_exe_step.dependOn(&b.addInstallFileWithDir(nvim_js, .bin, "nvim.js").step);
694        nvim_exe_step.dependOn(&b.addInstallFileWithDir(nvim_js.dirname().path(b, "nvim.wasm"), .bin, "nvim.wasm").step);
695        nvim_exe_step.dependOn(&b.addInstallFileWithDir(nvim_js.dirname().path(b, "nvim.data"), .bin, "nvim.data").step);
696    } else {
697        nvim_exe_step.dependOn(&nvim_exe_install.step);
698    }
699
700    const test_deps = b.step("test_deps", "test prerequisites");
701    if (!is_wasm) test_deps.dependOn(&nvim_exe_install.step); // running tests doesn't require copying the static runtime, only the generated stuff
702    const test_runtime_install = b.addInstallDirectory(.{
703        .source_dir = gen_runtime.getDirectory(),
704        .install_dir = .prefix,
705        .install_subdir = "runtime/",
706    });
707    test_deps.dependOn(&test_runtime_install.step);
708
709    const nvim_dev = b.step("nvim_dev", "build the editor for development");
710    b.default_step = nvim_dev;
711
712    if (!is_wasm) nvim_dev.dependOn(&nvim_exe_install.step);
713    nvim_dev.dependOn(&test_runtime_install.step);
714
715    // run from dev environment
716    const run_cmd = b.addRunArtifact(nvim_exe);
717    run_cmd.setEnvironmentVariable("VIMRUNTIME", try b.build_root.join(b.graph.arena, &.{"runtime"}));
718    run_cmd.setEnvironmentVariable("NVIM_ZIG_INSTALL_DIR", b.getInstallPath(.prefix, "runtime"));
719    run_cmd.step.dependOn(nvim_dev);
720    run_cmd.addArgs(&.{ "--cmd", "let &rtp = &rtp.','.$NVIM_ZIG_INSTALL_DIR" });
721    if (b.args) |args| {
722        run_cmd.addArgs(args);
723    }
724    const run_step = b.step("run_dev", "run the editor (for development)");
725    run_step.dependOn(&run_cmd.step);
726
727    // installation
728    const install = b.getInstallStep();
729    if (!is_wasm) install.dependOn(&nvim_exe_install.step);
730    b.installDirectory(.{
731        .source_dir = b.path("runtime/"),
732        .install_dir = .prefix,
733        .install_subdir = "share/nvim/runtime/",
734    });
735    b.installDirectory(.{
736        .source_dir = gen_runtime.getDirectory(),
737        .install_dir = .prefix,
738        .install_subdir = "share/nvim/runtime/",
739    });
740
741    test_deps.dependOn(test_fixture(b, "shell-test", false, false, null, target, optimize, &flags));
742    test_deps.dependOn(test_fixture(b, "tty-test", true, sys_opts.uv, libuv, target, optimize, &flags));
743    test_deps.dependOn(test_fixture(b, "pwsh-test", false, false, null, target, optimize, &flags));
744    test_deps.dependOn(test_fixture(b, "printargs-test", false, false, null, target, optimize, &flags));
745    test_deps.dependOn(test_fixture(b, "printenv-test", false, false, null, target, optimize, &flags));
746    test_deps.dependOn(test_fixture(b, "streams-test", true, sys_opts.uv, libuv, target, optimize, &flags));
747
748    // tee: vendored in src/tee/
749    const tee_exe = b.addExecutable(.{
750        .name = "tee",
751        .root_module = b.createModule(.{
752            .target = target,
753            .optimize = optimize,
754            .link_libc = true,
755        }),
756    });
757    tee_exe.root_module.addCSourceFile(.{ .file = b.path("src/tee/tee.c") });
758    test_deps.dependOn(&b.addInstallArtifact(tee_exe, .{}).step);
759
760    // xxd - hex dump utility (vendored from Vim)
761    const xxd_exe = b.addExecutable(.{
762        .name = "xxd",
763        .root_module = b.createModule(.{
764            .target = target,
765            .optimize = optimize,
766            .link_libc = true,
767        }),
768    });
769    xxd_exe.root_module.addCSourceFile(.{ .file = b.path("src/xxd/xxd.c") });
770    test_deps.dependOn(&b.addInstallArtifact(xxd_exe, .{}).step);
771
772    const parser_deps = b.step("parsers", "build tree-sitter parsers");
773    test_runtime_install.step.dependOn(parser_deps);
774    install.dependOn(parser_deps);
775
776    const parser_c = b.dependency("treesitter_c", .{ .target = target, .optimize = optimize_ts });
777    parser_deps.dependOn(add_ts_parser(b, "c", parser_c.path("."), false, target, optimize_ts));
778
779    const parser_diff = b.dependency("treesitter_diff", .{ .target = target, .optimize = optimize_ts });
780    parser_deps.dependOn(add_ts_parser(b, "diff", parser_diff.path("."), false, target, optimize_ts));
781
782    const parser_markdown = b.dependency("treesitter_markdown", .{ .target = target, .optimize = optimize_ts });
783    parser_deps.dependOn(add_ts_parser(b, "markdown", parser_markdown.path("tree-sitter-markdown/"), true, target, optimize_ts));
784    parser_deps.dependOn(add_ts_parser(b, "markdown_inline", parser_markdown.path("tree-sitter-markdown-inline/"), true, target, optimize_ts));
785
786    const parser_vim = b.dependency("treesitter_vim", .{ .target = target, .optimize = optimize_ts });
787    parser_deps.dependOn(add_ts_parser(b, "vim", parser_vim.path("."), true, target, optimize_ts));
788
789    const parser_vimdoc = b.dependency("treesitter_vimdoc", .{ .target = target, .optimize = optimize_ts });
790    parser_deps.dependOn(add_ts_parser(b, "vimdoc", parser_vimdoc.path("."), false, target, optimize_ts));
791
792    const parser_lua = b.dependency("treesitter_lua", .{ .target = target, .optimize = optimize_ts });
793    parser_deps.dependOn(add_ts_parser(b, "lua", parser_lua.path("."), true, target, optimize_ts));
794
795    const parser_query = b.dependency("treesitter_query", .{ .target = target, .optimize = optimize_ts });
796    parser_deps.dependOn(add_ts_parser(b, "query", parser_query.path("."), false, target, optimize_ts));
797
798    if (is_wasm) {
799        const WasmTsParser = struct {
800            name: []const u8,
801            dir: LazyPath,
802            has_scanner: bool,
803        };
804        const wasm_ts_parsers = [_]WasmTsParser{
805            .{ .name = "lua", .dir = parser_lua.path("."), .has_scanner = true },
806            .{ .name = "c", .dir = parser_c.path("."), .has_scanner = false },
807            .{ .name = "diff", .dir = parser_diff.path("."), .has_scanner = false },
808            .{ .name = "markdown", .dir = parser_markdown.path("tree-sitter-markdown/"), .has_scanner = true },
809            .{ .name = "markdown_inline", .dir = parser_markdown.path("tree-sitter-markdown-inline/"), .has_scanner = true },
810            .{ .name = "vim", .dir = parser_vim.path("."), .has_scanner = true },
811            .{ .name = "vimdoc", .dir = parser_vimdoc.path("."), .has_scanner = false },
812            .{ .name = "query", .dir = parser_query.path("."), .has_scanner = false },
813        };
814
815        for (wasm_ts_parsers) |p| {
816            nvim_mod.addCSourceFile(.{
817                .file = p.dir.path(b, "src/parser.c"),
818                .flags = &flags,
819            });
820            if (p.has_scanner) {
821                nvim_mod.addCSourceFile(.{
822                    .file = p.dir.path(b, "src/scanner.c"),
823                    .flags = &flags,
824                });
825            }
826            nvim_mod.addIncludePath(p.dir.path(b, "src"));
827        }
828    }
829    var unit_headers: ?[]const LazyPath = null;
830    if (support_unittests) {
831        try unittest_include_path.append(b.allocator, gen_headers.getDirectory());
832        unit_headers = unittest_include_path.items;
833    }
834    try tests.test_steps(
835        b,
836        nvim_exe,
837        test_deps,
838        test_config_step.getDirectory(),
839        unit_headers,
840    );
841
842    // compile_commands.json
843    var cdb_targets: std.ArrayListUnmanaged(*std.Build.Step.Compile) = try .initCapacity(b.allocator, 0);
844    try cdb_targets.append(b.allocator, nvim_exe);
845    try cdb_targets.append(b.allocator, tee_exe);
846    try cdb_targets.append(b.allocator, xxd_exe);
847    const cdb_step = zcc.createStep(b, "cdb", cdb_targets.items);
848    for (cdb_targets.items) |ct| cdb_step.dependOn(&ct.step);
849
850    try lint.addSteps(b, target, cdb_step, nvim_exe_install, nvim_sources, nvim_headers, ci_build);
851}
852
853pub fn test_fixture(
854    b: *std.Build,
855    name: []const u8,
856    use_libuv: bool,
857    use_system_libuv: bool,
858    libuv: ?*std.Build.Step.Compile,
859    target: std.Build.ResolvedTarget,
860    optimize: std.builtin.OptimizeMode,
861    flags: []const []const u8,
862) *std.Build.Step {
863    var root_module = b.createModule(.{
864        .target = target,
865        .optimize = optimize,
866        .link_libc = true,
867    });
868    const fixture = b.addExecutable(.{ .name = name, .root_module = root_module });
869    const source = if (std.mem.eql(u8, name, "pwsh-test")) "shell-test" else name;
870    if (std.mem.eql(u8, name, "printenv-test")) {
871        fixture.mingw_unicode_entry_point = true; // uses UNICODE on WINDOWS :scream:
872    }
873
874    root_module.addCSourceFile(.{
875        .file = b.path(b.fmt("./test/functional/fixtures/{s}.c", .{source})),
876        .flags = flags,
877    });
878    if (use_libuv) {
879        if (use_system_libuv) {
880            root_module.linkSystemLibrary("libuv", .{});
881        } else if (libuv) |uv| {
882            root_module.linkLibrary(uv);
883        }
884    }
885    return &b.addInstallArtifact(fixture, .{}).step;
886}
887
888pub fn add_ts_parser(
889    b: *std.Build,
890    name: []const u8,
891    parser_dir: LazyPath,
892    scanner: bool,
893    target: std.Build.ResolvedTarget,
894    optimize: std.builtin.OptimizeMode,
895) *std.Build.Step {
896    var root_module = b.createModule(.{
897        .target = target,
898        .optimize = optimize,
899        .link_libc = true,
900    });
901    const parser = b.addLibrary(.{
902        .name = name,
903        .linkage = .dynamic,
904        .root_module = root_module,
905    });
906    root_module.addCSourceFile(.{ .file = parser_dir.path(b, "src/parser.c") });
907    if (scanner) root_module.addCSourceFile(.{ .file = parser_dir.path(b, "src/scanner.c") });
908    root_module.addIncludePath(parser_dir.path(b, "src"));
909
910    return &b.addInstallArtifact(parser, .{ .dest_sub_path = b.fmt("nvim/parser/{s}.so", .{name}) }).step;
911}
912
913pub fn lua_version_info(b: *std.Build) []u8 {
914    const v = version;
915    return b.fmt(
916        \\return {{
917        \\  {{"major", {}}},
918        \\  {{"minor", {}}},
919        \\  {{"patch", {}}},
920        \\  {{"prerelease", {}}},
921        \\  {{"api_level", {}}},
922        \\  {{"api_compatible", {}}},
923        \\  {{"api_prerelease", {}}},
924        \\}}
925    , .{
926        v.major,
927        v.minor,
928        v.patch,
929        v.prerelease.len > 0,
930        v.api_level,
931        v.api_level_compat,
932        v.api_prerelease,
933    });
934}
935
936/// Replace all backslashes in `input` with with forward slashes when the target is Windows.
937/// Returned memory is stored in `b.graph.arena`.
938fn replace_backslashes(b: *std.Build, input: []const u8) ![]const u8 {
939    return if (b.graph.host.result.os.tag == .windows)
940        std.mem.replaceOwned(u8, b.graph.arena, input, "\\", "/")
941    else
942        input;
943}
944
945pub fn test_config(b: *std.Build) ![]u8 {
946    var buf: [std.fs.max_path_bytes]u8 = std.mem.zeroes([std.fs.max_path_bytes]u8);
947    _ = try b.build_root.handle.realPath(b.graph.io, &buf);
948    const src_path = std.mem.span(@as([*:0]u8, @ptrCast(&buf)));
949
950    // we don't use test/cmakeconfig/paths.lua.in because it contains cmake specific logic
951    return b.fmt(
952        \\local M = {{}}
953        \\
954        \\M.apple_sysroot = ""
955        \\M.translations_enabled = "$ENABLE_TRANSLATIONS" == "ON"
956        \\M.is_asan = "$ENABLE_ASAN_UBSAN" == "ON"
957        \\M.is_zig_build = true
958        \\M.vterm_test_file = "test/vterm_test_output"
959        \\M.test_build_dir = _G.nvim_build_dir -- command line arg
960        \\M.test_source_path = "{[src_path]s}"
961        \\M.test_lua_prg = ""
962        \\M.test_luajit_prg = ""
963        \\ -- include path passed on the cmdline, see test/runner.lua
964        \\M.include_paths = _G.c_include_path or {{}}
965        \\
966        \\return M
967    , .{ .src_path = try replace_backslashes(b, src_path) });
968}
969
970fn appendSystemIncludePath(
971    b: *std.Build,
972    path: *std.ArrayList(LazyPath),
973    system_name: []const u8,
974) !void {
975    var code: u8 = 0;
976    const stdout = try b.runAllowFail(
977        &[_][]const u8{ "pkg-config", system_name, "--cflags-only-I", "--keep-system-cflags" },
978        &code,
979        .ignore,
980    );
981    if (code != 0) return std.Build.PkgConfigError.PkgConfigFailed;
982    var arg_it = std.mem.tokenizeAny(u8, stdout, " \r\n\t");
983    while (arg_it.next()) |arg| {
984        if (std.mem.eql(u8, arg, "-I")) {
985            // -I /foo/bar
986            const dir = arg_it.next() orelse return std.Build.PkgConfigError.PkgConfigInvalidOutput;
987            try path.append(b.allocator, .{ .cwd_relative = dir });
988        } else if (std.mem.startsWith(u8, arg, "-I")) {
989            // -I/foo/bar
990            const dir = arg[("-I".len)..];
991            try path.append(b.allocator, .{ .cwd_relative = dir });
992        }
993    }
994}