croft-software 0.2.132

VSCode-style TUI written in Rust
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
//! The language table: the data-driven replacement for the old closed
//! `Language` enum's hardcoded match arms.
//!
//! Every loaded extension's `[[languages]]` blocks are merged into one table
//! mapping file extension -> language, plus per-language project-root markers
//! and the server "family". [`crate::lsp::config::Language`]'s resolution
//! methods read this table, so adding a language is pure data — a new
//! `[[languages]]` block in some extension's manifest, no Rust change.
//!
//! The table holds the bundled manifests plus the user-installed ones. It is
//! rebuilt whenever the installed set changes, so an extension added
//! mid-session resolves its files at once (#1842).

use std::collections::{BTreeSet, HashMap};
use std::path::Path;
use std::sync::{Arc, Mutex, PoisonError, RwLock};

use crate::lsp::config::Language;
use crate::lsp::manifest;

struct LangRecord {
    root_markers: &'static [&'static str],
    family: Option<&'static str>,
}

struct LangTable {
    by_ext: HashMap<String, Language>,
    /// File-name patterns, split on `/`, checked before `by_ext`.
    by_name: Vec<(Vec<String>, Language)>,
    records: HashMap<&'static str, LangRecord>,
}

/// The root-marker slices handed out by [`intern_markers`], so a rebuilt
/// table reuses the slice each language got the first time.
static INTERNED_MARKERS: Mutex<BTreeSet<&'static [&'static str]>> = Mutex::new(BTreeSet::new());

/// A `&'static [&'static str]` for a language's root markers, leaked at most
/// once per distinct list. Sound because a language identity lives for the
/// whole process; bounded by the distinct lists the manifests carry, not by
/// how often the table is rebuilt.
fn intern_markers(markers: &[String]) -> &'static [&'static str] {
    let markers: Vec<&'static str> = markers.iter().map(|m| manifest::intern(m)).collect();
    let mut set = INTERNED_MARKERS
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    if let Some(existing) = set.get(markers.as_slice()) {
        return existing;
    }
    let leaked: &'static [&'static str] = Box::leak(markers.into_boxed_slice());
    set.insert(leaked);
    leaked
}

impl LangTable {
    fn from_sources(sources: &[&str]) -> Self {
        let mut by_ext = HashMap::new();
        let mut by_name = Vec::new();
        let mut records = HashMap::new();
        for src in sources {
            let Ok(m) = manifest::parse(src) else {
                continue;
            };
            for decl in &m.languages {
                let id = manifest::intern(&decl.id);
                let lang = Language(id);
                for ext in &decl.extensions {
                    by_ext.insert(ext.to_ascii_lowercase(), lang);
                }
                for pattern in &decl.filenames {
                    let parts = pattern.split('/').map(str::to_string).collect();
                    by_name.push((parts, lang));
                }
                records.insert(
                    id,
                    LangRecord {
                        root_markers: intern_markers(&decl.root_markers),
                        family: decl.family.as_deref().map(manifest::intern),
                    },
                );
            }
        }
        LangTable {
            by_ext,
            by_name,
            records,
        }
    }
}

/// The active table. Readers take a snapshot, so a rebuild never waits on
/// a lookup in progress, and a lookup that calls another sees one table.
static TABLE: RwLock<Option<Arc<LangTable>>> = RwLock::new(None);

#[cfg(test)]
thread_local! {
    /// The table [`reload_with_user_sources`] built on this test thread.
    static TABLE_FOR_THIS_TEST_THREAD: std::cell::RefCell<Option<Arc<LangTable>>> =
        const { std::cell::RefCell::new(None) };
}

/// The active table. Lazily built from the bundled manifests only if
/// [`reload_with_user_sources`] was never called (the case on a test's LSP
/// worker, which keeps resolution there hermetic — no disk, no user state).
fn table() -> Arc<LangTable> {
    #[cfg(test)]
    if let Some(table) = TABLE_FOR_THIS_TEST_THREAD.with(|t| t.borrow().clone()) {
        return table;
    }
    if let Some(table) = TABLE
        .read()
        .unwrap_or_else(PoisonError::into_inner)
        .as_ref()
    {
        return table.clone();
    }
    TABLE
        .write()
        .unwrap_or_else(PoisonError::into_inner)
        .get_or_insert_with(|| Arc::new(LangTable::from_sources(manifest::BUNDLED_MANIFESTS)))
        .clone()
}

/// Rebuild the table from the bundled manifests plus `user`, the extensions
/// installed now. Called when the LSP manager starts and again whenever an
/// extension is added or removed (#1842), so the added one's files resolve
/// from then on and the removed one's stop. Under test the table serves only
/// the calling thread: a test that adds an extension must not change what
/// the tests running beside it resolve.
pub fn reload_with_user_sources(user: &[&str]) {
    let mut sources: Vec<&str> = manifest::BUNDLED_MANIFESTS.to_vec();
    sources.extend_from_slice(user);
    let table = Arc::new(LangTable::from_sources(&sources));
    #[cfg(test)]
    TABLE_FOR_THIS_TEST_THREAD.with(|t| *t.borrow_mut() = Some(table));
    #[cfg(not(test))]
    {
        *TABLE.write().unwrap_or_else(PoisonError::into_inner) = Some(table);
    }
}

/// The language a file extension maps to, or `None` if no extension claims it.
pub fn from_extension(ext: &str) -> Option<Language> {
    table().by_ext.get(&ext.to_ascii_lowercase()).copied()
}

/// The language a file maps to: a file-name pattern first, then its
/// extension.
pub fn from_path(path: &Path) -> Option<Language> {
    let names: Vec<&str> = path
        .components()
        .filter_map(|c| c.as_os_str().to_str())
        .collect();
    table()
        .by_name
        .iter()
        .find(|(parts, _)| {
            parts.len() <= names.len()
                && parts
                    .iter()
                    .rev()
                    .zip(names.iter().rev())
                    .all(|(pattern, name)| wildcard_match(pattern, name))
        })
        .map(|(_, lang)| *lang)
        .or_else(|| {
            path.extension()
                .and_then(|e| e.to_str())
                .and_then(from_extension)
        })
}

/// Whether `name` matches `pattern`, where `*` stands for any run of
/// characters and everything else matches itself.
fn wildcard_match(pattern: &str, name: &str) -> bool {
    match pattern.split_once('*') {
        None => pattern == name,
        Some((head, rest)) => {
            let Some(tail) = name.strip_prefix(head) else {
                return false;
            };
            (0..=tail.len())
                .filter(|&i| tail.is_char_boundary(i))
                .any(|i| wildcard_match(rest, &tail[i..]))
        }
    }
}

/// Resolve an LSP `languageId` to a known language, or `None`.
pub fn resolve(id: &str) -> Option<Language> {
    table().records.get_key_value(id).map(|(k, _)| Language(k))
}

/// Project-root markers for a language (empty slice when none / unknown).
pub fn root_markers(lang: Language) -> &'static [&'static str] {
    table()
        .records
        .get(lang.lsp_id())
        .map(|r| r.root_markers)
        .unwrap_or(&[])
}

/// Languages whose project-root markers sit directly in `dir` — the
/// workspace-open equivalent of VS Code's `workspaceContains` activation.
/// Used to pre-warm the evident language servers at startup so their cold
/// indexing overlaps with the user browsing the tree instead of starting
/// only when the first file opens (#27). Deliberately non-recursive: the
/// scan is a handful of stat calls, never a walk.
pub fn languages_evident_in(dir: &std::path::Path) -> Vec<Language> {
    let mut out: Vec<Language> = table()
        .records
        .keys()
        .filter_map(|id| resolve(id))
        .filter(|&lang| {
            root_markers(lang)
                .iter()
                .any(|marker| dir.join(marker).exists())
        })
        .collect();
    // The table is a HashMap; a stable order keeps spawn logs and tests
    // deterministic.
    out.sort_by_key(|l| l.lsp_id());
    out.dedup();
    out
}

/// The server family a language belongs to; itself when it has no `family`.
pub fn server_family(lang: Language) -> Language {
    table()
        .records
        .get(lang.lsp_id())
        .and_then(|r| r.family)
        .map(Language)
        .unwrap_or(lang)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bundled_extensions_map_to_languages() {
        assert_eq!(from_extension("py"), Some(Language::PYTHON));
        assert_eq!(from_extension("PY"), Some(Language::PYTHON));
        assert_eq!(from_extension("rs"), Some(Language::RUST));
        assert_eq!(from_extension("yml"), Some(Language::YAML));
        assert_eq!(from_extension("xyz"), None);
    }

    /// #578: the CodeQL extension maps `.ql` queries and `.qll` libraries
    /// to the `ql` language, rooted at the nearest pack file. It is not
    /// built in (#1842), so only once it is added, and from the moment it
    /// is: the table is rebuilt, not fixed at the first lookup.
    #[test]
    fn codeql_sources_map_to_the_ql_language_once_added() {
        assert_eq!(from_extension("ql"), None, "not built in");
        reload_with_user_sources(&[crate::mcp::registry_index::CODEQL_MANIFEST]);
        assert_eq!(from_extension("ql"), Some(Language("ql")));
        assert_eq!(from_extension("qll"), Some(Language("ql")));
        assert_eq!(resolve("ql"), Some(Language("ql")));
        assert_eq!(
            root_markers(Language("ql")),
            &["qlpack.yml", "codeql-pack.yml"]
        );
        // Uninstalled, its files stop resolving.
        reload_with_user_sources(&[]);
        assert_eq!(from_extension("ql"), None);
        assert_eq!(resolve("ql"), None);
    }

    /// Rebuilding the table as extensions come and go hands back what the
    /// last build leaked rather than leaking it again.
    #[test]
    fn a_rebuilt_table_leaks_nothing_new() {
        reload_with_user_sources(&[]);
        let markers = root_markers(Language::LUA);
        let id = resolve("lua").expect("bundled").lsp_id();
        reload_with_user_sources(&[]);
        assert!(std::ptr::eq(markers, root_markers(Language::LUA)));
        assert!(std::ptr::eq(id, resolve("lua").expect("bundled").lsp_id()));
    }

    /// #27: the workspace-open scan behind server pre-warm. A marker at
    /// the root makes its language evident; nothing recurses, so a marker
    /// buried in a subdirectory does not.
    #[test]
    fn languages_evident_in_reads_root_markers_non_recursively() {
        let dir = tempfile::tempdir().unwrap();
        assert!(languages_evident_in(dir.path()).is_empty());
        std::fs::write(dir.path().join("Cargo.toml"), "[package]\n").unwrap();
        assert_eq!(languages_evident_in(dir.path()), vec![Language::RUST]);
        std::fs::write(dir.path().join("go.mod"), "module x\n").unwrap();
        let both = languages_evident_in(dir.path());
        assert!(both.contains(&Language::RUST) && both.contains(&Language::GO));
        // Buried markers stay invisible: the scan is stat calls, not a walk.
        std::fs::create_dir(dir.path().join("sub")).unwrap();
        std::fs::write(dir.path().join("sub").join("pyproject.toml"), "").unwrap();
        assert!(!languages_evident_in(dir.path()).contains(&Language::PYTHON));
    }

    #[test]
    fn bundled_root_markers_and_family() {
        assert_eq!(root_markers(Language::RUST), &["Cargo.toml"]);
        assert_eq!(root_markers(Language::GO), &["go.mod"]);
        assert_eq!(
            root_markers(Language::LUA),
            &[
                ".luarc.json",
                // lua-language-server reads the JSONC spelling too, and a
                // project carrying only that one would otherwise fall through
                // to the linter/formatter markers or get no root at all.
                ".luarc.jsonc",
                ".luacheckrc",
                ".stylua.toml",
                "stylua.toml",
                "selene.toml"
            ]
        );
        assert!(root_markers(Language::JSON).is_empty());
        // vtsls family: the React/JS ids collapse onto TypeScript; TypeScript
        // is its own family.
        assert_eq!(server_family(Language::TSX), Language::TYPESCRIPT);
        assert_eq!(server_family(Language::JSX), Language::TYPESCRIPT);
        assert_eq!(server_family(Language::JAVASCRIPT), Language::TYPESCRIPT);
        assert_eq!(server_family(Language::TYPESCRIPT), Language::TYPESCRIPT);
        assert_eq!(server_family(Language::RUST), Language::RUST);
        assert_eq!(server_family(Language::LUA), Language::LUA);
    }

    const ZIG_MANIFEST: &str = r#"
id = "lsp-zig"
name = "Zig"
api_version = 1
[[languages]]
id = "zig"
extensions = ["zig", "zon"]
root_markers = ["build.zig", "build.zig.zon"]
"#;

    #[test]
    fn a_user_manifest_contributes_a_new_language_with_zero_rust() {
        // Built locally (not the global table) so the test stays hermetic, but
        // exercises the exact code path init_with_user_sources uses at startup.
        let t = LangTable::from_sources(&[ZIG_MANIFEST]);
        let zig = Language("zig");
        assert_eq!(t.by_ext.get("zig"), Some(&zig));
        assert_eq!(t.by_ext.get("zon"), Some(&zig));
        let rec = t.records.get("zig").expect("zig language recorded");
        assert_eq!(rec.root_markers, &["build.zig", "build.zig.zon"]);
        assert!(rec.family.is_none());
    }

    /// #1084: the files whose format is JSON with comments open as `jsonc`,
    /// by name or by the directory they sit in, and share the JSON server.
    #[test]
    fn json_with_comments_files_map_to_jsonc() {
        let jsonc = Language("jsonc");
        for path in [
            "/repo/tsconfig.json",
            "/repo/packages/web/tsconfig.app.json",
            "/repo/tsconfig-base.json",
            "/repo/jsconfig.json",
            "/repo/.vscode/tasks.json",
            "/repo/.vscode/settings.json",
            "/repo/.devcontainer/devcontainer.json",
            "/repo/app.code-workspace",
            "/repo/.eslintrc",
            "/repo/.eslintrc.json",
            "/repo/.babelrc",
            "/repo/packages/app/babel.config.json",
            "/repo/.croft/config.json",
            "/repo/notes.jsonc",
            "/repo/NOTES.JSONC",
        ] {
            assert_eq!(from_path(Path::new(path)), Some(jsonc), "{path}");
        }
        assert_eq!(server_family(jsonc), Language::JSON);
    }

    /// The patterns stay narrow: plain JSON, a near-miss name, a file a
    /// level below `.vscode`, and other languages keep their own ids.
    #[test]
    fn other_json_files_stay_json() {
        for path in [
            "/repo/package.json",
            "/repo/my-tsconfig.json",
            "/repo/vscode/tasks.json",
            "/repo/.vscode/sub/tasks.json",
            "/repo/.vscode.json",
            "tsconfig/package.json",
        ] {
            assert_eq!(from_path(Path::new(path)), Some(Language::JSON), "{path}");
        }
        assert_eq!(from_path(Path::new("/repo/main.rs")), Some(Language::RUST));
        assert_eq!(
            from_path(Path::new("/repo/.eslintrc.js")),
            Some(Language::JAVASCRIPT)
        );
        assert_eq!(from_path(Path::new("/repo/README")), None);
        assert_eq!(from_path(Path::new("/repo/.vscode")), None);
    }

    #[test]
    fn wildcards_match_any_run_of_characters() {
        assert!(wildcard_match("tsconfig.*.json", "tsconfig.app.json"));
        assert!(wildcard_match("*.json", ".json"));
        assert!(wildcard_match("*", ""));
        assert!(wildcard_match("a*b*c", "a-b-b-c"));
        assert!(wildcard_match("*é.json", "café.json"));
        assert!(!wildcard_match("tsconfig.*.json", "tsconfig.json"));
        assert!(!wildcard_match("a*b*c", "a-c-b"));
        assert!(!wildcard_match(".babelrc", ".babelrc.js"));
    }
}