Skip to main content

zsh/extensions/
compinit_bg.rs

1//! Background compinit pre-warm — extension; no zsh C counterpart.
2use crate::compsys::cache::CompsysCache;
3use crate::compsys::CompInitResult;
4#[allow(unused_imports)]
5use crate::ported::vm_helper::ShellExecutor;
6#[allow(unused_imports)]
7use std::{collections::HashMap, env, path::PathBuf};
8
9/// Result from background compinit thread.
10/// Outcome of background `compinit` autoload.
11/// zshrs-original — Src/Modules/complete.c blocks on `compinit`
12/// inline. The Rust port runs it on the worker pool.
13pub struct CompInitBgResult {
14    /// `result` field.
15    pub result: CompInitResult,
16    /// `cache` field.
17    pub cache: CompsysCache,
18}
19
20// ===========================================================
21// Methods moved verbatim from src/ported/vm_helper because their
22// C counterpart's source file maps 1:1 to this Rust module.
23// Phase: drift
24// ===========================================================
25
26// BEGIN moved-from-exec-rs
27impl crate::ported::vm_helper::ShellExecutor {
28    /// Non-blocking drain of background compinit results.
29    /// Call this before any completion lookup (prompt, tab-complete, etc.).
30    /// If the background thread hasn't finished yet, this is a no-op.
31    pub fn drain_compinit_bg(&mut self) {
32        tracing::debug!(target: "compsys_args", pending = self.compinit_pending.is_some(), "drain_compinit_bg ENTER");
33        if let Some((rx, start)) = self.compinit_pending.take() {
34            match rx.try_recv() {
35                Ok(bg) => {
36                    let comps = bg.result.comps.len();
37                    // `#compdef -k`/`-K` header bindings — must run on the
38                    // shell thread (dispatches zle -C + bindkey).
39                    crate::compsys::ported::compinit::apply_keybindings(&bg.result);
40                    // compinit sh:337/sh:541 — `compdef -na` autoloads every
41                    // completer it registers, so `${(k)functions}` holds a stub
42                    // for each one (see `register_autoload_stubs`).
43                    let mut stubs = crate::compsys::ported::compinit::register_scanned_autoload_stubs(
44                        &bg.result,
45                        &self.fpath,
46                    );
47                    // `autoload_stub_names` reads `result.files`, which only a
48                    // fresh `$fpath` scan fills: `load_from_cache`
49                    // (compinit.rs) rebuilds `comps`/`patcomps`/`postpatcomps`
50                    // out of SQLite and leaves `files` empty. The background
51                    // thread returns whichever of the two it ended up taking,
52                    // so on every cache-hit start the call above registered
53                    // ZERO stubs and `${(k)functions}` came back holding no
54                    // `_*` name at all -- measured `${#${(M)${(k)functions}:#_*}}`
55                    // = 0 against a 1822-entry `$_comps`. `zle -C`'s entry
56                    // point `_main_complete` was one of the missing names, so
57                    // every completion widget compinit binds called an
58                    // undefined function and inserted nothing. The `autoloads`
59                    // table carries the same names the scan would have
60                    // produced, so read it whenever the file list came back in
61                    // the empty cache shape.
62                    if bg.result.files.is_empty() {
63                        if let Ok(names) = bg.cache.list_autoload_names() {
64                            stubs += crate::compsys::ported::compinit::register_autoload_stubs(
65                                &names,
66                            );
67                        }
68                    }
69                    tracing::info!(stubs, "compinit: autoload stubs from background result");
70                    self.set_assoc("_comps".to_string(), bg.result.comps.into_iter().collect());
71                    self.set_assoc(
72                        "_services".to_string(),
73                        bg.result.services.into_iter().collect(),
74                    );
75                    self.set_assoc(
76                        "_patcomps".to_string(),
77                        bg.result.patcomps.into_iter().collect(),
78                    );
79                    self.compsys_cache = std::cell::OnceCell::from(Some(bg.cache));
80                    tracing::info!(
81                        wall_ms = start.elapsed().as_millis() as u64,
82                        comps,
83                        "compinit: background results merged"
84                    );
85                }
86                Err(std::sync::mpsc::TryRecvError::Empty) => {
87                    // Not ready yet — put the receiver back for next poll
88                    self.compinit_pending = Some((rx, start));
89                }
90                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
91                    tracing::warn!("compinit: background thread died without sending results");
92                }
93            }
94        }
95    }
96    /// Traditional zsh compinit (--zsh-compat mode)
97    /// Uses fpath scanning, .zcompdump files, no SQLite
98    pub(crate) fn compinit_compat(
99        &mut self,
100        quiet: bool,
101        no_dump: bool,
102        dump_file: Option<String>,
103        use_cache: bool,
104    ) -> i32 {
105        let zdotdir = self
106            .scalar("ZDOTDIR")
107            .or_else(|| std::env::var("ZDOTDIR").ok())
108            .unwrap_or_else(|| std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string()));
109
110        let dump_path = dump_file
111            .map(PathBuf::from)
112            .unwrap_or_else(|| PathBuf::from(&zdotdir).join(".zcompdump"));
113
114        // -C: Try to use existing .zcompdump if valid
115        if use_cache
116            && dump_path.exists()
117            && crate::compsys::check_dump(&dump_path, &self.fpath, "zshrs-0.1.0")
118        {
119            // Valid dump - source it to load _comps
120            // For now, just rescan (proper impl would source the dump file)
121            if !quiet {
122                tracing::info!("compinit: .zcompdump valid, rescanning for compat");
123            }
124        }
125
126        // Full fpath scan (traditional zsh algorithm)
127        let result = crate::compsys::compinit(&self.fpath);
128
129        if !quiet {
130            tracing::info!(
131                functions = result.files_scanned,
132                comps = result.comps.len(),
133                dirs = result.dirs_scanned,
134                ms = result.scan_time_ms,
135                "compinit: fpath scan complete"
136            );
137        }
138
139        // Write .zcompdump unless -D
140        if !no_dump {
141            let _ = crate::compsys::compdump(&result, &dump_path, "zshrs-0.1.0");
142        }
143
144        // compinit sh:337/sh:541 — `compdef -na` autoloads every completer it
145        // registers, so `${(k)functions}` holds a stub for each one (see
146        // `register_autoload_stubs`).
147        crate::compsys::ported::compinit::register_scanned_autoload_stubs(&result, &self.fpath);
148
149        // Set up _comps associative array
150        self.set_assoc(
151            "_comps".to_string(),
152            result.comps.clone().into_iter().collect(),
153        );
154        self.set_assoc(
155            "_services".to_string(),
156            result.services.clone().into_iter().collect(),
157        );
158        self.set_assoc(
159            "_patcomps".to_string(),
160            result.patcomps.clone().into_iter().collect(),
161        );
162
163        // `#compdef -k`/`-K` header bindings (^X? _complete_debug,
164        // ^Xh _complete_help, …) — the in-shell half of the scan.
165        crate::compsys::ported::compinit::apply_keybindings(&result);
166
167        // No SQLite cache in compat mode
168        self.compsys_cache = std::cell::OnceCell::from(None);
169
170        0
171    }
172}
173// END moved-from-exec-rs