zshrs 0.13.21

The first JIT-compiled Unix shell — bytecode VM, Cranelift JIT, worker pool, AOP intercept, Rkyv caching
Documentation
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
//! Build-time PORT.md drift enforcement.
//!
//! Runs the name-presence drift check (the spine of
//! `tests/ported_fn_names_match_c.rs`) on every cargo invocation
//! that touches the ported tree. Catches `pub fn name_not_in_zsh_c`
//! violations BEFORE any test binary compiles, so a bot doing
//! `cargo test --test foo` (which would otherwise skip the drift
//! tests) still gets stopped.
//!
//! This duplicates the core logic of `collect_free_fns` +
//! `load_c_fn_index` from the test. If you change either, mirror
//! the change here. Kept self-contained (std only) so the build
//! script has no extra dependencies.
//!
//! Re-run is gated by `cargo:rerun-if-changed` directives below —
//! unchanged builds skip the scan in the cargo cache.

use std::collections::{HashMap, HashSet};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

fn main() {
    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());

    // Only re-run when the inputs change. src/ported/** (the code
    // being checked), the C-name snapshot, and the allowlist files.
    println!("cargo:rerun-if-changed=src/ported");
    println!("cargo:rerun-if-changed=tests/data/zsh_c_fn_names.txt");
    println!("cargo:rerun-if-changed=tests/data/fake_fn_allowlist.txt");
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=vendor/zsh");
    println!("cargo:rerun-if-changed=man/man1");
    println!("cargo:rerun-if-changed=functions");
    println!("cargo:rerun-if-changed=completions");
    println!("cargo:rerun-if-changed=../arb/completions");
    println!("cargo:rerun-if-changed=../strykelang/completions");
    bundle_zsh_functions();
    bundle_zsh_docs();
    println!("cargo:rerun-if-changed=src/zsh/Config/version.mk");

    // Parse `src/zsh/Config/version.mk` for VERSION + VERSION_DATE
    // and emit them as compile-time constants. Replaces hardcoded
    // `"5.9"` / `"zsh-5.9-0-g73d3173"` literals in `src/vm_helper`
    // with values derived from the vendored zsh source so future
    // version bumps land automatically.
    let version_mk = manifest_dir.join("src/zsh/Config/version.mk");
    let (zsh_version, zsh_version_date) = parse_version_mk(&version_mk);
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let dest = out_dir.join("zsh_version.rs");
    let generated = format!(
        "/// Vendored zsh source `Config/version.mk` `VERSION=...` value.\n\
         /// `ZSH_VERSION` constant.
         pub const ZSH_VERSION: &str = {:?};\n\
         /// Vendored zsh source `Config/version.mk` `VERSION_DATE=...` value.\n\
         pub const ZSH_VERSION_DATE: &str = {:?};\n\
         /// `$ZSH_PATCHLEVEL` default — C `Src/params.c:43` sets `\"unknown\"`\n\
         /// when no custom value is configured. The vendored zsh tarball\n\
         /// doesn't ship a patchlevel hash; emit `\"unknown\"` to match\n\
         /// upstream's no-CUSTOM_PATCHLEVEL build.\n\
         pub const ZSH_PATCHLEVEL: &str = \"unknown\";\n",
        zsh_version, zsh_version_date
    );
    fs::write(&dest, generated).expect("write zsh_version.rs");

    // No terminal-handling library is linked. `link_term_lib` used to probe
    // for `ncursesw`/`ncurses`/`tinfow`/`tinfo`/`termcap`/`curses` and emit a
    // `cargo:rustc-link-lib` for whichever answered, reproducing
    // `configure.ac:725-771`. The eighteen symbols it supplied
    // (`tgetent`/`tgetstr`/`tigetstr`/`setupterm`/`tparm`/`tputs`/`tgoto`/…
    // and the `boolnames`/`strcodes` tables) are now pure Rust in
    // `src/extensions/terminfo_db.rs`, `terminfo_caps.rs` and `tparm.rs`,
    // which read the compiled terminfo database directly.
    //
    // That removes `libtinfo.so.6` as an install dependency on Ubuntu and
    // `libtinfo-dev`/`libncurses-dev` as build dependencies everywhere, and
    // it removes the divergence the probe itself could cause: which library
    // answered decided which terminfo database `${(kv)terminfo}` reflected.

    // Enlarge the MAIN-thread stack (binaries only). zshrs runs the
    // whole shell on the main thread to keep signal/job-control
    // semantics intact — but its per-call frames are heavy (fusevm
    // executor state, closures, parse buffers) and real configs
    // (p10k/zinit precmd hooks) nest deeply, so on the default 8 MB
    // main-thread stack a deep or runaway recursion overflowed and
    // SEGFAULTed before the FUNCNEST guard (exec.rs::doshfunc, default
    // 500) could fire its graceful error. macOS honors the Mach-O
    // `-stack_size` load command for the main thread; 256 MB comfortably
    // fits FUNCNEST-deep recursion (pages are committed on demand, so
    // idle RSS is unaffected). `rustc-link-arg-bins` scopes this to the
    // shipped binaries — the Rust test harness runs each test on its own
    // (RUST_MIN_STACK-sized) thread and drives zshrs as a subprocess, so
    // it is unaffected. Bug #643. (Linux governs the main-thread stack
    // via RLIMIT_STACK/ulimit, not a link flag, so this is macOS-only.)
    #[cfg(target_os = "macos")]
    println!("cargo:rustc-link-arg-bins=-Wl,-stack_size,0x10000000");

    // Emit the `config.h` values that C's ./configure derives on the
    // build host rather than hard-codes. See `emit_config_h_env`.
    emit_config_h_env();

    let ported_root = manifest_dir.join("src/ported");
    let c_index_path = manifest_dir.join("tests/data/zsh_c_fn_names.txt");
    let allowlist_path = manifest_dir.join("tests/data/fake_fn_allowlist.txt");

    // If the ported root or the C-name snapshot is missing, this
    // isn't a configured port checkout — skip silently rather than
    // failing builds for unrelated workspaces.
    if !ported_root.exists() || !c_index_path.exists() {
        return;
    }

    let c_names = match load_c_fn_index(&c_index_path) {
        Ok(n) => n,
        Err(e) => {
            // Snapshot missing or unreadable — warn but don't break
            // the build. The full test will fail loudly if invoked.
            println!(
                "cargo:warning=PORT.md drift: cannot read {} ({})",
                c_index_path.display(),
                e
            );
            return;
        }
    };

    let allowlist: HashSet<String> = fs::read_to_string(&allowlist_path)
        .unwrap_or_default()
        .lines()
        .map(|l| {
            // Strip inline `#` comment so entries like
            // `name   # justification` parse to just `name`.
            let l = match l.find('#') {
                Some(i) => &l[..i],
                None => l,
            };
            l.trim()
        })
        .filter(|l| !l.is_empty())
        .map(|l| l.to_string())
        .collect();

    let mut rust_files: Vec<PathBuf> = Vec::new();
    collect_rust_files(&ported_root, &mut rust_files);

    let mut violations: Vec<String> = Vec::new();
    for path in &rust_files {
        let src = match fs::read_to_string(path) {
            Ok(s) => s,
            Err(_) => continue,
        };
        let rel = path
            .strip_prefix(&manifest_dir)
            .unwrap_or(path)
            .display()
            .to_string();
        for (name, lineno) in collect_free_fns(&src) {
            if !allowlist.contains(&name) && !c_names.contains_key(&name) {
                violations.push(format!(
                    "  {}:{}  fn {} — no C counterpart in zsh source",
                    rel, lineno, name,
                ));
            }
        }
    }

    if !violations.is_empty() {
        violations.sort();
        // Emit cargo:warning for visibility in IDE / lint output,
        // then panic to fail the build. Cargo prints panic messages
        // before aborting.
        for v in &violations {
            println!("cargo:warning={}", v.trim());
        }
        panic!(
            "\n\
             ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
             src/ported/ IS A PORT — NO NEW FUNCTIONS ALLOWED\n\
             ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n\
             Every `pub fn` / `fn` under src/ported/ MUST be a faithful\n\
             port of a function that exists in zsh's upstream C source\n\
             (~/forkedRepos/zsh/Src/, snapshotted at\n\
             tests/data/zsh_c_fn_names.txt). Rust-original helpers,\n\
             refactored extractions, convenience wrappers, and\n\
             ad-hoc abstractions DO NOT BELONG HERE — they create\n\
             drift between the port and the spec.\n\n\
             {} fn(s) violate this rule:\n\n\
             {}\n\n\
             To fix:\n\n\
               1. Preferred: inline the body at every call site\n\
                  (it isn't a real port, it shouldn't be a function).\n\
               2. Or: rename to match the actual C function it ports.\n\
                  Cite Src/<file>.c:<line> in the doc comment.\n\
               3. Last resort: add the name to\n\
                  tests/data/fake_fn_allowlist.txt with a comment\n\
                  explaining why no C analog exists (architectural\n\
                  Rust-only helpers like singleton accessors only).\n\n\
             Enforced by build.rs on every `cargo build` / `cargo test`\n\
             / `cargo check` whenever src/ported/** changes. Cannot be\n\
             bypassed by `cargo test --test X`.\n\
             ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
            violations.len(),
            violations.join("\n")
        );
    }
}
/// Emit the `config.h` constants that C's `./configure` *derives* on the
/// build host, as `cargo:rustc-env` values consumed by
/// `src/ported/config_h.rs` via `env!()`.
///
/// C computes these once, at configure time, and freezes the result into
/// `config.h`; `Src/params.c:989-992` is the only reader for the host-triple
/// three. Freezing them as Rust literals reproduces one specific machine's
/// `./configure` run forever, which is wrong on every other machine and on
/// every other target.
///
/// Emitted here (each with its C derivation):
///   * `ZSHRS_CONFIG_OSTYPE`       — `configure.ac:47`  `AC_DEFINE_UNQUOTED(OSTYPE,   "$host_os", ...)`
///   * `ZSHRS_CONFIG_VENDOR`       — `configure.ac:45`  `AC_DEFINE_UNQUOTED(VENDOR,   "$host_vendor", ...)`
///   * `ZSHRS_CONFIG_DEFAULT_PATH` — `configure.ac:1954 AC_DEFINE_UNQUOTED(DEFAULT_PATH, "$zsh_cv_cs_path", ...)`
///   * `ZSHRS_CONFIG_PATH_DEV_FD`  — `configure.ac:1973 AC_DEFINE_UNQUOTED(PATH_DEV_FD, "$zsh_cv_sys_path_dev_fd")`
///
/// `MACHTYPE` (`configure.ac:43`, `"$host_cpu"`) is already derived in
/// `config_h.rs` from `std::env::consts::ARCH` and stays there — it needs no
/// build-script input.
fn emit_config_h_env() {
    let target = env::var("TARGET").unwrap_or_default();
    let host = env::var("HOST").unwrap_or_default();
    let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
    let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
    let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();

    println!(
        "cargo:rustc-env=ZSHRS_CONFIG_OSTYPE={}",
        config_guess_host_os(&target, &host, &target_os, &target_env)
    );
    println!(
        "cargo:rustc-env=ZSHRS_CONFIG_VENDOR={}",
        config_guess_host_vendor(&target_os, &target_arch)
    );
    println!("cargo:rustc-env=ZSHRS_CONFIG_DEFAULT_PATH={}", cs_path());
    println!(
        "cargo:rustc-env=ZSHRS_CONFIG_PATH_DEV_FD={}",
        // configure.ac:1969 probes `/proc/self/fd` first, then `/dev/fd`.
        // Linux always satisfies the first (procfs); Darwin has no procfs
        // and satisfies the second.
        if target_os == "linux" || target_os == "android" {
            "/proc/self/fd"
        } else {
            "/dev/fd"
        }
    );
}

/// `$host_os` — the third field of the canonical triple that
/// `AC_CANONICAL_HOST` obtains from `config.guess` (then `config.sub`,
/// which is the identity on every triple zshrs targets).
///
/// The shape is *platform-specific*, which is why a bare `uname -r` is the
/// wrong derivation:
///
///   * Darwin — `config.guess:1463` `GUESS=aarch64-apple-darwin$UNAME_RELEASE`
///     and `config.guess:1500` `GUESS=$UNAME_PROCESSOR-apple-darwin$UNAME_RELEASE`,
///     with `config.guess:148` `UNAME_RELEASE=`(uname -r) 2>/dev/null``.
///     So `$host_os` is `darwin` immediately followed by the kernel release:
///     `darwin25.5.0`.
///   * Linux — `config.guess:1222` `GUESS=$CPU-pc-linux-$LIBCABI` (x86_64),
///     `config.guess:1009` `GUESS=$CPU-unknown-linux-$LIBCABI` (aarch64),
///     `config.guess:1177` `GUESS=$UNAME_MACHINE-unknown-linux-$LIBC`
///     (riscv32/riscv64). `$host_os` is `linux-$LIBC` — the C *library*, never
///     the kernel version. `$LIBC` is `gnu` (`config.guess:167`), `musl`
///     (`:176`, `:188`), `uclibc` (`:163`), or `android` (`:159`), and
///     `config.guess:193-195` falls back to `gnu` when it cannot tell.
///
/// Cross-compilation: `configure --host=aarch64-apple-darwin23` bypasses
/// `config.guess` entirely and takes `$host_os` straight from the triple, so
/// a versioned `darwinNN` suffix in `$TARGET` wins. The `uname -r` probe is
/// used only when the build host is itself Darwin, i.e. exactly the native
/// case `config.guess` handles.
fn config_guess_host_os(target: &str, host: &str, target_os: &str, target_env: &str) -> String {
    match target_os {
        "macos" => {
            // `aarch64-apple-darwin23` → "darwin23"; `aarch64-apple-darwin`
            // (Rust's unversioned spelling) → fall through to the probe.
            if let Some(rel) = target
                .rsplit('-')
                .next()
                .and_then(|f| f.strip_prefix("darwin"))
            {
                if !rel.is_empty() {
                    return format!("darwin{rel}");
                }
            }
            if host.contains("-darwin") {
                if let Some(rel) = uname_release() {
                    return format!("darwin{rel}");
                }
            }
            // Cross-compiled to macOS from a non-Darwin host with no version
            // in the triple: there is nothing to read a kernel release from.
            // Emit the un-suffixed name rather than a fabricated version.
            "darwin".to_string()
        }
        "linux" => format!(
            "linux-{}",
            match target_env {
                // Rust spells the glibc environment `gnu`, musl `musl`,
                // uClibc `uclibc` — the same tokens config.guess uses.
                "" => "gnu", // config.guess:193-195 — default to glibc
                other => other,
            }
        ),
        // config.guess:158-159 — `#if defined(__ANDROID__) LIBC=android`,
        // fed into the same `linux-$LIBC` shape as the branches above.
        "android" => "linux-android".to_string(),
        // Any other target: emit the triple's OS field verbatim. config.guess
        // appends a release number for several of these (`freebsd14.0`), which
        // is not recoverable from the Rust triple, so the value is the OS name
        // without a version rather than a fabricated one.
        "" => "unknown".to_string(),
        other => other.to_string(),
    }
}

/// `$host_vendor` — the second field of the canonical triple. It is a
/// function of (OS, CPU), not of the OS alone, so it cannot be derived from
/// `uname -s`:
///
///   * Darwin → `apple` (`config.guess:1463`, `config.guess:1500`).
///   * Linux x86_64 → `pc` (`config.guess:1222` `GUESS=$CPU-pc-linux-$LIBCABI`);
///     Linux i386..i686 → `pc` (`config.guess:1067`
///     `GUESS=$UNAME_MACHINE-pc-linux-$LIBC`).
///   * Linux s390/s390x → `ibm` (`config.guess:1180`
///     `GUESS=$UNAME_MACHINE-ibm-linux-$LIBC`).
///   * Linux aarch64 → `unknown` (`config.guess:1009`); Linux riscv32/riscv64
///     → `unknown` (`config.guess:1177`); Linux arm* → `unknown`
///     (`config.guess:1037`).
///
/// So on Linux the answer differs between the two architectures zshrs ships:
/// `x86_64-pc-linux-gnu` but `aarch64-unknown-linux-gnu`.
fn config_guess_host_vendor(target_os: &str, target_arch: &str) -> &'static str {
    match (target_os, target_arch) {
        ("macos" | "ios" | "tvos" | "watchos" | "visionos", _) => "apple",
        ("linux" | "android", "x86_64" | "x86") => "pc",
        ("linux" | "android", "s390x") => "ibm",
        // config.guess's dominant vendor field for every other Linux CPU,
        // and the safe default elsewhere.
        _ => "unknown",
    }
}

/// `$zsh_cv_cs_path` — `configure.ac:1944-1953`:
///
/// ```text
/// AC_CACHE_VAL(zsh_cv_cs_path,
/// [if getconf _CS_PATH >/dev/null 2>&1; then
///   zsh_cv_cs_path=`getconf _CS_PATH`
/// elif getconf CS_PATH >/dev/null 2>&1; then
///   zsh_cv_cs_path=`getconf CS_PATH`
/// elif getconf PATH >/dev/null 2>&1; then
///   zsh_cv_cs_path=`getconf PATH`
/// else
///   zsh_cv_cs_path="/bin:/usr/bin"
/// fi])
/// ```
///
/// This is a build-host probe in C as well (autoconf runs `getconf` on the
/// build machine even under `--host=`), so running it here reproduces C's
/// behaviour including its cross-compilation limitation. On macOS the first
/// two names are rejected (`getconf: no such configuration parameter
/// '_CS_PATH'`, exit 64) and `getconf PATH` answers
/// `/usr/bin:/bin:/usr/sbin:/sbin`.
fn cs_path() -> String {
    for name in ["_CS_PATH", "CS_PATH", "PATH"] {
        if let Ok(out) = std::process::Command::new("getconf").arg(name).output() {
            if out.status.success() {
                let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
                if !s.is_empty() {
                    return s;
                }
            }
        }
    }
    "/bin:/usr/bin".to_string()
}

/// `config.guess:148` — ``UNAME_RELEASE=`(uname -r) 2>/dev/null` ||
/// UNAME_RELEASE=unknown``. Returns `None` on the failure branch so the
/// caller can decide what to emit instead.
fn uname_release() -> Option<String> {
    let out = std::process::Command::new("uname")
        .arg("-r")
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if s.is_empty() {
        None
    } else {
        Some(s)
    }
}

/// Parse `Config/version.mk` for the `VERSION=...` and
/// `VERSION_DATE='...'` lines. The file is a Makefile fragment +
/// shell script (see the file's header comment); the assignments use
/// `KEY=VALUE` with no spaces around the `=`.
fn parse_version_mk(path: &Path) -> (String, String) {
    let s = fs::read_to_string(path).unwrap_or_else(|_| String::new());
    let mut version = String::new();
    let mut version_date = String::new();
    for line in s.lines() {
        let line = line.trim();
        if let Some(v) = line.strip_prefix("VERSION=") {
            version = v.trim().trim_matches('\'').trim_matches('"').to_string();
        } else if let Some(v) = line.strip_prefix("VERSION_DATE=") {
            version_date = v.trim().trim_matches('\'').trim_matches('"').to_string();
        }
    }
    if version.is_empty() {
        // version.mk missing or malformed — fall back to a marker so
        // the build still produces a valid const but the wrong value
        // surfaces as a visible "unknown" in `$ZSH_VERSION`.
        version = "unknown".to_string();
    }
    (version, version_date)
}

fn collect_rust_files(root: &Path, out: &mut Vec<PathBuf>) {
    let entries = match fs::read_dir(root) {
        Ok(e) => e,
        Err(_) => return,
    };
    for ent in entries.flatten() {
        let path = ent.path();
        if path.is_dir() {
            collect_rust_files(&path, out);
        } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
            out.push(path);
        }
    }
}

/// Find free `fn NAME(` declarations at module level (depth 0).
/// Skips methods (anything inside `impl`/`trait`) and `mod tests`
/// blocks. Mirror of the test's `collect_free_fns` — keep in sync.
///
/// Brace-counting state machine ignores `{`/`}` that appear inside
/// `// line comments`, `/* block comments */`, `"string literals"`,
/// `'char literals'`, and `r"raw strings"` / `r#"hashed"#` — without
/// this, a test that contains `"{"` in a string literal corrupts the
/// depth tracker and the gate misfires after any reordering.
fn collect_free_fns(src: &str) -> Vec<(String, usize)> {
    let mut fns: Vec<(String, usize)> = Vec::new();
    let mut depth: i32 = 0;
    let mut in_test_mod = false;
    let mut test_mod_depth: i32 = 0;
    let mut in_block_comment: i32 = 0;

    for (lineno, line) in src.lines().enumerate() {
        let lineno = lineno + 1;
        let trimmed = line.trim_start();

        if depth == 0 && (trimmed.starts_with("mod tests {") || trimmed.starts_with("mod test {")) {
            in_test_mod = true;
            test_mod_depth = depth + 1;
        }

        let bytes = line.as_bytes();
        let mut i = 0;
        let mut delta: i32 = 0;
        while i < bytes.len() {
            let b = bytes[i];
            if in_block_comment > 0 {
                if b == b'*' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
                    in_block_comment -= 1;
                    i += 2;
                    continue;
                }
                if b == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
                    in_block_comment += 1;
                    i += 2;
                    continue;
                }
                i += 1;
                continue;
            }
            match b {
                b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'/' => break,
                b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => {
                    in_block_comment += 1;
                    i += 2;
                }
                b'"' => {
                    i += 1;
                    while i < bytes.len() {
                        let c = bytes[i];
                        if c == b'\\' {
                            i += 2;
                            continue;
                        }
                        if c == b'"' {
                            i += 1;
                            break;
                        }
                        i += 1;
                    }
                }
                b'r' if i + 1 < bytes.len() && (bytes[i + 1] == b'"' || bytes[i + 1] == b'#') => {
                    let mut hashes = 0;
                    let mut j = i + 1;
                    while j < bytes.len() && bytes[j] == b'#' {
                        hashes += 1;
                        j += 1;
                    }
                    if j < bytes.len() && bytes[j] == b'"' {
                        i = j + 1;
                        loop {
                            if i >= bytes.len() {
                                break;
                            }
                            if bytes[i] == b'"' {
                                let mut closed = 0;
                                let mut k = i + 1;
                                while k < bytes.len() && bytes[k] == b'#' && closed < hashes {
                                    closed += 1;
                                    k += 1;
                                }
                                if closed >= hashes {
                                    i = k;
                                    break;
                                }
                            }
                            i += 1;
                        }
                    } else {
                        i += 1;
                    }
                }
                b'\'' => {
                    let mut j = i + 1;
                    let mut found_close = false;
                    let mut escape = false;
                    while j < bytes.len() && j - i < 12 {
                        if !escape && bytes[j] == b'\'' {
                            found_close = true;
                            break;
                        }
                        escape = bytes[j] == b'\\' && !escape;
                        j += 1;
                    }
                    if found_close {
                        i = j + 1;
                    } else {
                        i += 1;
                        while i < bytes.len()
                            && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_')
                        {
                            i += 1;
                        }
                    }
                }
                b'{' => {
                    delta += 1;
                    i += 1;
                }
                b'}' => {
                    delta -= 1;
                    i += 1;
                }
                _ => i += 1,
            }
        }
        let pre_depth = depth;
        depth += delta;
        if in_test_mod && depth < test_mod_depth {
            in_test_mod = false;
        }

        if in_test_mod {
            continue;
        }
        if pre_depth != 0 {
            continue;
        }

        let stripped = trimmed
            .strip_prefix("pub(crate) ")
            .or_else(|| trimmed.strip_prefix("pub(super) "))
            .unwrap_or_else(|| trimmed.strip_prefix("pub ").unwrap_or(trimmed));
        let stripped = stripped.strip_prefix("unsafe ").unwrap_or(stripped);
        let stripped = stripped.strip_prefix("async ").unwrap_or(stripped);
        let stripped = stripped.strip_prefix(r#"extern "C" "#).unwrap_or(stripped);

        if let Some(rest) = stripped.strip_prefix("fn ") {
            let name_end = rest
                .find(|c: char| c == '(' || c == '<' || c.is_whitespace())
                .unwrap_or(0);
            if name_end > 0 {
                let name = rest[..name_end].to_string();
                if name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
                    fns.push((name, lineno));
                }
            }
        }
    }
    fns
}

fn load_c_fn_index(path: &Path) -> Result<HashMap<String, HashSet<String>>, std::io::Error> {
    let src = fs::read_to_string(path)?;
    let mut index: HashMap<String, HashSet<String>> = HashMap::new();
    for line in src.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some((file, name)) = line.split_once(':') {
            index
                .entry(name.to_string())
                .or_default()
                .insert(file.to_string());
        }
    }
    Ok(index)
}


/// Pack the vendored zsh function tree into a single zstd blob for
/// `crate::bundled_functions` to materialise into `~/.zshrs/functions`.
///
/// Source of truth is `vendor/zsh/`, which is TRACKED. It used to be
/// `src/zsh/Completion` + `src/zsh/Functions` + `completions/`, and all
/// three were absent from the published crate: `src/zsh/` is gitignored
/// (it is the upstream C checkout used as the porting reference) and
/// `/completions/` was in Cargo's exclude list. `cargo package --list`
/// showed ZERO files from any of them, so every `cargo install zshrs`
/// built a bundle of nothing and materialised an empty
/// `~/.zshrs/functions`. Nothing failed loudly because the walk below
/// swallowed a missing directory with `continue`; it now hard-errors
/// instead.
///
/// The tree is FLAT, matching what zsh's own `make install` produces --
/// it flattens `Completion/**` and `Functions/**` into one directory --
/// so the bundle is keyed by basename and the installed layout matches.
/// zshrs's own completions live in the same directory for the same
/// reason: at runtime they are peers of zsh's. `completions/` is walked
/// FIRST because `seen` keeps the first basename it meets -- vendor/zsh
/// held byte-identical copies of all 26 of them until this commit, and
/// with vendor first an edit to `completions/` would have been silently
/// shadowed by the stale vendored copy.
///
/// Format: repeated `u32 name_len | name | u32 body_len | body`, all
/// little-endian, then zstd. Deliberately not tar: this avoids a second
/// build-dependency for a payload we both write and read.
fn bundle_zsh_functions() {
    use std::io::Write;
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let mut files: Vec<(String, Vec<u8>)> = Vec::new();
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    // Per-root counts ride along in the summary line: a tree that quietly
    // stops contributing is the failure mode that shipped a 26-file
    // ~/.zshrs/functions, and a single total hides it.
    let mut per_root: Vec<String> = Vec::new();
    // Completions of runtimes that are linked INTO the shell as builtins when
    // zshrs is vendored under `zshrs-native/vendor/` (`arb`, `stryke`/`st`/`s`
    // keep their `_arb` / `_stryke` in their own repos, siblings of this one).
    // Without them `arb <TAB>` completes nothing in the native shell although
    // `arb` is one of its builtins. They are OPTIONAL: a standalone checkout or
    // the published crate has no such siblings, and this root is then skipped
    // rather than a build error. Walked last, so a same-named file above wins.
    const OPTIONAL_ROOTS: &[&str] = &["../arb/completions", "../strykelang/completions"];
    for root in ["functions", "completions", "vendor/zsh/functions"]
        .iter()
        .chain(OPTIONAL_ROOTS)
        .copied()
    {
        let optional = OPTIONAL_ROOTS.contains(&root);
        if optional && !PathBuf::from(root).is_dir() {
            continue;
        }
        let before = files.len();
        let mut stack = vec![PathBuf::from(root)];
        while let Some(dir) = stack.pop() {
            let rd = match fs::read_dir(&dir) {
                Ok(rd) => rd,
                Err(_) => continue,
            };
            for e in rd.flatten() {
                let p = e.path();
                if p.is_dir() {
                    stack.push(p);
                    continue;
                }
                let name = match p.file_name().and_then(|n| n.to_str()) {
                    Some(n) => n.to_string(),
                    None => continue,
                };
                // Mirror what zsh's install skips: docs and build inputs.
                // LICENCE and the provenance README sit in the vendored
                // directory so the notice travels with the code, and are
                // not functions.
                if name.starts_with('.')
                    || name.starts_with("README")
                    || name == "LICENCE"
                    || name == "Makefile"
                    || name.ends_with(".md")
                    || name.ends_with(".txt")
                    || name.ends_with(".in")
                    || name.ends_with(".mdd")
                    || name.ends_with(".pro")
                {
                    continue;
                }
                if !seen.insert(name.clone()) {
                    continue;
                }
                if let Ok(body) = fs::read(&p) {
                    files.push((name, body));
                }
            }
        }
        // A root that yielded nothing is a BUILD ERROR, not a quiet
        // short bundle. Checking the TOTAL is not enough: when
        // `src/zsh/{Completion,Functions}` stopped existing, the walk
        // still returned the 26 files from `completions/`, the build
        // stayed green, and a 26-file `~/.zshrs/functions` shipped with
        // no compinit, no _git, no is-at-least.
        per_root.push(format!("{root} {}", files.len() - before));
        if files.len() == before && !optional {
            panic!(
                "{root} contributed no functions -- the tree must be present \
                 and non-empty for the bundle to be built."
            );
        }
    }
    files.sort_by(|a, b| a.0.cmp(&b.0));
    let mut raw: Vec<u8> = Vec::new();
    for (name, body) in &files {
        raw.extend_from_slice(&(name.len() as u32).to_le_bytes());
        raw.extend_from_slice(name.as_bytes());
        raw.extend_from_slice(&(body.len() as u32).to_le_bytes());
        raw.extend_from_slice(body);
    }
    let packed = zstd::encode_all(&raw[..], 19).expect("zstd encode zsh function bundle");
    let dest = out_dir.join("zsh_functions.zst");
    let mut f = fs::File::create(&dest).expect("create zsh_functions.zst");
    f.write_all(&packed).expect("write zsh_functions.zst");
    // Identify the bundle by content, not by crate version: the tree can
    // change within one version (it did -- a build.rs root that no longer
    // existed silently shrank it from 1271 files to 26), and a
    // version-only stamp leaves that stale tree on disk forever.
    // FNV-1a over the packed bytes, computed here so startup pays nothing.
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in &packed {
        hash ^= u64::from(*b);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    fs::write(
        out_dir.join("zsh_functions_id.rs"),
        format!(
            "/// FNV-1a of the packed function bundle, from build.rs.\n\
             /// Stamped into `~/.zshrs/functions` so a changed bundle is\n\
             /// rewritten even when the crate version did not move.\n\
             pub const BUNDLE_ID: &str = \"{hash:016x}\";\n"
        ),
    )
    .expect("write zsh_functions_id.rs");
    println!(
        "cargo:warning=bundled {} zsh functions ({} KiB packed; {})",
        files.len(),
        packed.len() / 1024,
        per_root.join(", ")
    );
}

/// Make the bundled `zshall.1` carry the zshrs superset: list `zshrsall` in
/// its OVERVIEW and `.so`-include `man1/zshrsall.1` after the last zsh page,
/// so `man zshall` documents everything zshrs adds on top of zsh. The
/// vendored file on disk is untouched; only the shipped copy is spliced.
fn splice_zshrsall_into_zshall(files: &mut [(String, Vec<u8>)]) {
    const LAST_ZSH_PAGE: &str = ".so man1/zshcontrib.1\n";
    const OVERVIEW_ANCHOR: &str = "\\fIzshcontrib\\fP";
    let Some((_, body)) = files.iter_mut().find(|(n, _)| n == "man/man1/zshall.1") else {
        return;
    };
    let text = String::from_utf8_lossy(body).into_owned();
    if text.contains("zshrsall") {
        return;
    }
    let mut out = text.replacen(
        LAST_ZSH_PAGE,
        &format!("{LAST_ZSH_PAGE}.so man1/zshrsall.1\n"),
        1,
    );
    // Add the OVERVIEW list entry after the zshcontrib `.TP` item.
    if let Some(at) = out.find(OVERVIEW_ANCHOR) {
        if let Some(nl) = out[at..].find('\n') {
            let end = at + nl + 1;
            out.insert_str(
                end,
                ".TP\n\\fIzshrsall\\fP      Everything zshrs adds on top of zsh\n",
            );
        }
    }
    *body = out.into_bytes();
}

/// Pack zsh's man and info pages into a zstd blob for
/// `crate::bundled_docs` to materialise into `~/.zshrs/{man,info}`.
///
/// Same reasoning as the function tree: zshrs is a drop-in binary, not a
/// program installed under a zsh `--prefix`, so `man zshall` and
/// `info zsh` only worked on a host that happened to have zsh installed.
/// The pages describe the language zshrs implements, so it ships them.
///
/// Unlike the function bundle this one is NOT flat -- entries keep their
/// `man1/…` or `info/…` prefix, because `man` resolves a page by section
/// directory and `INFOPATH` expects the split `zsh.info-N` files beside
/// their `zsh.info` index.
///
/// Format: repeated `u32 name_len | name | u32 body_len | body`, all
/// little-endian, then zstd -- identical to the function bundle.
fn bundle_zsh_docs() {
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let root = PathBuf::from("vendor/zsh");
    let mut files: Vec<(String, Vec<u8>)> = Vec::new();
    // Only the doc subdirectories -- `functions/` is the function bundle's
    // and must not be duplicated into the doc tree. Each is paired with the
    // path it INSTALLS to, which is not its vendored name: `man` has to be
    // the MANPATH entry with the section directory beneath it, so
    // `vendor/zsh/man1/zsh.1` ships as `man/man1/zsh.1`. Emitting the
    // vendored name verbatim put the pages in `~/.zshrs/man1` while
    // MANPATH named `~/.zshrs/man`, which did not exist.
    // (vendored dir, installed path, required). `info` and `man1` are the
    // OPTIONAL trees: both are excluded from the published crate to keep
    // the .crate under crates.io's size ceiling, so a crates.io build has
    // neither vendor/zsh/info nor vendor/zsh/man1 to read. Every other
    // tree is required -- a missing one is a build error, never a quiet
    // short bundle.
    //
    // `info` gave way first (0.12.5x): `zshall.1` carries the same content
    // as the Texinfo manual, so nothing was lost that the man pages did
    // not already say. `man1` followed at 0.12.60, when the tarball hit
    // 10.13 MiB against the 10 MiB ceiling with no required tree left to
    // trade. It is the largest remaining removable tree (0.44 MiB
    // compressed, vs 0.10 for `help`), and it is the one whose absence is
    // least load-bearing: these are ZSH's pages, and a host that wants
    // them can install zsh. zshrs's OWN pages are `man/man1/zshrs.1` and
    // `zshrsall.1`, bundled below from `man/man1` in every build and
    // `.so`-included by the shipped `zshall.1`. A git or Homebrew
    // build has both trees and bundles them exactly as before, so this
    // only affects `cargo install zshrs`.
    //
    // Restore `man1` to required the moment crates.io grants this crate a
    // size-limit increase -- these pages are `run-help`'s deep content and
    // the crate should carry them whenever it fits.
    let trees = [
        ("man1", "man/man1", false),
        ("info", "info", false),
        // `run-help`'s help database. The vendored `run-help` defaults
        // HELPDIR to the <prefix>/share/zsh/<ver>/help of whichever zsh
        // built it, which is a dead path on a host without that exact
        // install -- so zshrs ships the tree and points HELPDIR at it.
        ("help", "help", true),
        // `newuser`, sourced by zsh's first-run path.
        ("scripts", "scripts", true),
    ];
    for (src, installed, required) in trees {
        let dir = root.join(src);
        let before = files.len();
        let rd = match fs::read_dir(&dir) {
            Ok(rd) => rd,
            Err(_) => continue,
        };
        for e in rd.flatten() {
            let p = e.path();
            if p.is_dir() {
                continue;
            }
            let base = match p.file_name().and_then(|n| n.to_str()) {
                Some(n) if !n.starts_with('.') => n.to_string(),
                _ => continue,
            };
            if let Ok(body) = fs::read(&p) {
                files.push((format!("{installed}/{base}"), body));
            }
        }
        if required && files.len() == before {
            panic!("vendor/zsh/{src} is missing or empty -- zsh's {src} pages must be vendored");
        }
    }
    // zshrs's own pages (`zshrs.1`, `zshrsall.1`) live outside vendor/zsh
    // and ship in every build, crates.io included.
    if let Ok(rd) = fs::read_dir("man/man1") {
        for e in rd.flatten() {
            let p = e.path();
            let Some(base) = p.file_name().and_then(|n| n.to_str()) else { continue };
            if base.starts_with('.') || !p.is_file() {
                continue;
            }
            if let Ok(body) = fs::read(&p) {
                files.push((format!("man/man1/{base}"), body));
            }
        }
    }
    splice_zshrsall_into_zshall(&mut files);
    files.sort_by(|a, b| a.0.cmp(&b.0));
    let mut raw: Vec<u8> = Vec::new();
    for (name, body) in &files {
        raw.extend_from_slice(&(name.len() as u32).to_le_bytes());
        raw.extend_from_slice(name.as_bytes());
        raw.extend_from_slice(&(body.len() as u32).to_le_bytes());
        raw.extend_from_slice(body);
    }
    let packed = zstd::encode_all(&raw[..], 19).expect("zstd encode zsh doc bundle");
    fs::write(out_dir.join("zsh_docs.zst"), &packed).expect("write zsh_docs.zst");
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in &packed {
        hash ^= u64::from(*b);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    fs::write(
        out_dir.join("zsh_docs_id.rs"),
        format!(
            "/// FNV-1a of the packed man/info bundle, from build.rs.\n\
             pub const DOCS_ID: &str = \"{hash:016x}\";\n"
        ),
    )
    .expect("write zsh_docs_id.rs");
    println!(
        "cargo:warning=bundled {} zsh doc files ({} KiB packed)",
        files.len(),
        packed.len() / 1024
    );
}