Skip to main content

iced_code_editor/canvas_editor/lsp/process/
config.rs

1//! LSP (Language Server Protocol) configuration module.
2//!
3//! This module handles language server detection, configuration, and command resolution
4//! for various programming languages. It maps file extensions to language servers and
5//! provides functionality to resolve the correct server command based on environment
6//! variables and system availability.
7
8use std::path::{Path, PathBuf};
9use std::process::Command;
10
11/// Represents a language supported by an LSP server.
12///
13/// Contains the language identifier and the associated server key.
14///
15/// # Examples
16///
17/// ```no_run
18/// use iced_code_editor::lsp_language_for_extension;
19///
20/// if let Some(lang) = lsp_language_for_extension("rs") {
21///     assert_eq!(lang.language_id, "rust");
22///     assert_eq!(lang.server_key, "rust-analyzer");
23/// }
24/// ```
25#[derive(Clone, Copy)]
26pub struct LspLanguage {
27    /// Language identifier (e.g., "rust", "python", "typescript")
28    pub language_id: &'static str,
29    /// Key identifying the LSP server (e.g., "rust-analyzer", "pyright")
30    pub server_key: &'static str,
31}
32
33/// Internal mapping between file extensions and language/server configurations.
34#[derive(Clone, Copy)]
35struct LspLanguageMapping {
36    /// File extensions associated with this language (e.g., ["rs"], ["ts", "tsx"])
37    extensions: &'static [&'static str],
38    /// Language identifier for LSP protocol
39    language_id: &'static str,
40    /// Key to look up the server configuration
41    server_key: &'static str,
42}
43
44/// Configuration for an LSP server.
45///
46/// Defines how to locate and run the language server.
47///
48/// # Examples
49///
50/// ```no_run
51/// use iced_code_editor::lsp_server_config;
52///
53/// if let Some(config) = lsp_server_config("rust-analyzer") {
54///     println!("key: {}", config.key);
55/// }
56/// ```
57#[derive(Clone, Copy)]
58pub struct LspServerConfig {
59    /// Unique identifier for this server configuration
60    pub key: &'static str,
61    /// Environment variables to check for custom server paths (checked in order)
62    pub env_vars: &'static [&'static str],
63    /// Default command and arguments to run the server
64    pub default_command: &'static [&'static str],
65}
66
67/// Resolved command to execute an LSP server.
68///
69/// # Examples
70///
71/// ```no_run
72/// use iced_code_editor::{lsp_server_config, resolve_lsp_command};
73///
74/// if let Some(config) = lsp_server_config("gopls") {
75///     if let Ok(cmd) = resolve_lsp_command(config) {
76///         println!("program: {}", cmd.program);
77///     }
78/// }
79/// ```
80pub struct LspCommand {
81    /// Program path or name
82    pub program: String,
83    /// Command-line arguments
84    pub args: Vec<String>,
85}
86
87/// Supported language mappings: file extensions -> language ID -> server key
88const LSP_LANGUAGE_MAPPINGS: &[LspLanguageMapping] = &[
89    LspLanguageMapping {
90        extensions: &["rs"],
91        language_id: "rust",
92        server_key: "rust-analyzer",
93    },
94    LspLanguageMapping {
95        extensions: &["py"],
96        language_id: "python",
97        server_key: "pyright",
98    },
99    LspLanguageMapping {
100        extensions: &["js", "jsx"],
101        language_id: "javascript",
102        server_key: "typescript-language-server",
103    },
104    LspLanguageMapping {
105        extensions: &["ts", "tsx"],
106        language_id: "typescript",
107        server_key: "typescript-language-server",
108    },
109    LspLanguageMapping {
110        extensions: &["lua"],
111        language_id: "lua",
112        server_key: "lua-language-server",
113    },
114    LspLanguageMapping {
115        extensions: &["go"],
116        language_id: "go",
117        server_key: "gopls",
118    },
119];
120
121/// Server configurations for each supported LSP server.
122/// Defines environment variables and default commands for each server.
123const LSP_SERVER_CONFIGS: &[LspServerConfig] = &[
124    LspServerConfig {
125        key: "rust-analyzer",
126        env_vars: &["RUST_ANALYZER", "RUST_ANALYZER_PATH"],
127        default_command: &["rust-analyzer"],
128    },
129    LspServerConfig {
130        key: "pyright",
131        env_vars: &["PYRIGHT_LANGSERVER", "PYRIGHT_LANGSERVER_PATH"],
132        default_command: &["pyright-langserver", "--stdio"],
133    },
134    LspServerConfig {
135        key: "typescript-language-server",
136        env_vars: &[
137            "TYPESCRIPT_LANGUAGE_SERVER",
138            "TYPESCRIPT_LANGUAGE_SERVER_PATH",
139        ],
140        default_command: &["typescript-language-server", "--stdio"],
141    },
142    LspServerConfig {
143        key: "lua-language-server",
144        env_vars: &["LUA_LANGUAGE_SERVER", "LUA_LANGUAGE_SERVER_PATH"],
145        default_command: &["lua-language-server"],
146    },
147    LspServerConfig {
148        key: "gopls",
149        env_vars: &["GOPLS", "GOPLS_PATH"],
150        default_command: &["gopls"],
151    },
152];
153
154/// Looks up the LSP language configuration for a file extension.
155///
156/// Returns `None` if the extension is not supported.
157///
158/// # Examples
159///
160/// ```
161/// use iced_code_editor::lsp_language_for_extension;
162///
163/// let lang = lsp_language_for_extension("rs");
164/// assert!(lang.is_some());
165///
166/// let unknown = lsp_language_for_extension("xyz");
167/// assert!(unknown.is_none());
168/// ```
169pub fn lsp_language_for_extension(extension: &str) -> Option<LspLanguage> {
170    LSP_LANGUAGE_MAPPINGS
171        .iter()
172        .find(|mapping| {
173            mapping
174                .extensions
175                .iter()
176                .any(|ext| ext.eq_ignore_ascii_case(extension))
177        })
178        .map(|mapping| LspLanguage {
179            language_id: mapping.language_id,
180            server_key: mapping.server_key,
181        })
182}
183
184/// Looks up the LSP language configuration for a file path.
185///
186/// Extracts the extension and delegates to [`lsp_language_for_extension`].
187///
188/// # Examples
189///
190/// ```
191/// use std::path::Path;
192/// use iced_code_editor::lsp_language_for_path;
193///
194/// let lang = lsp_language_for_path(Path::new("main.rs"));
195/// assert!(lang.is_some());
196///
197/// let none = lsp_language_for_path(Path::new("noext"));
198/// assert!(none.is_none());
199/// ```
200pub fn lsp_language_for_path(path: &Path) -> Option<LspLanguage> {
201    let extension = path.extension()?.to_str()?;
202    lsp_language_for_extension(extension)
203}
204
205/// Retrieves the server configuration for a given server key.
206///
207/// # Examples
208///
209/// ```
210/// use iced_code_editor::lsp_server_config;
211///
212/// let cfg = lsp_server_config("rust-analyzer");
213/// assert!(cfg.is_some());
214///
215/// let missing = lsp_server_config("unknown-server");
216/// assert!(missing.is_none());
217/// ```
218pub fn lsp_server_config(key: &str) -> Option<&'static LspServerConfig> {
219    LSP_SERVER_CONFIGS.iter().find(|config| config.key == key)
220}
221
222/// Resolves the command to execute an LSP server.
223///
224/// Checks environment variables first, then falls back to the default command.
225/// Special handling for rust-analyzer to support rustup-installed versions.
226///
227/// # Errors
228///
229/// Returns an error string if the program cannot be located (e.g. rust-analyzer
230/// or gopls are not installed and not found via their fallback discovery logic).
231///
232/// # Examples
233///
234/// ```no_run
235/// use iced_code_editor::{lsp_server_config, resolve_lsp_command};
236///
237/// if let Some(config) = lsp_server_config("lua-language-server") {
238///     match resolve_lsp_command(config) {
239///         Ok(cmd) => println!("Run: {}", cmd.program),
240///         Err(e) => eprintln!("Not found: {e}"),
241///     }
242/// }
243/// ```
244pub fn resolve_lsp_command(
245    config: &LspServerConfig,
246) -> Result<LspCommand, String> {
247    let program = if config.key == "rust-analyzer" {
248        resolve_rust_analyzer_command()?
249    } else if config.key == "gopls" {
250        resolve_gopls_command()?
251    } else {
252        resolve_program_from_envs(config.env_vars)
253            .unwrap_or_else(|| config.default_command[0].to_string())
254    };
255    let args = config
256        .default_command
257        .iter()
258        .skip(1)
259        .map(|arg| arg.to_string())
260        .collect();
261    Ok(LspCommand { program, args })
262}
263
264/// Resolves a program path from a list of environment variables.
265/// Returns the first non-empty value found, trimmed, or None if all are
266/// unset/blank.
267fn resolve_program_from_envs(env_vars: &[&str]) -> Option<String> {
268    resolve_program_from_envs_with(env_vars, |var| std::env::var(var).ok())
269}
270
271/// Same as [`resolve_program_from_envs`], but takes an injectable lookup so the
272/// priority order can be unit-tested without touching real process environment.
273///
274/// The returned value is trimmed. Emptiness is judged on the trimmed value, so
275/// returning it untrimmed would accept a variable holding only whitespace as a
276/// "found" path — and hand a value like `" /usr/bin/gopls"` (a shell-config
277/// typo, or a CI variable with a trailing newline) straight to
278/// `Command::new`, which then fails with a confusing "No such file or
279/// directory".
280fn resolve_program_from_envs_with(
281    env_vars: &[&str],
282    lookup: impl Fn(&str) -> Option<String>,
283) -> Option<String> {
284    for var in env_vars {
285        if let Some(path) = lookup(var) {
286            let path = path.trim();
287            if !path.is_empty() {
288                return Some(path.to_string());
289            }
290        }
291    }
292    None
293}
294
295/// Resolves the rust-analyzer command with special handling.
296/// Checks in order:
297/// 1. RUST_ANALYZER environment variable
298/// 2. RUST_ANALYZER_PATH environment variable
299/// 3. Direct rust-analyzer command
300/// 4. rustup which rust-analyzer
301fn resolve_rust_analyzer_command() -> Result<String, String> {
302    resolve_rust_analyzer_command_with(
303        |var| std::env::var(var).ok(),
304        || Command::new("rust-analyzer").arg("--version").output().is_ok(),
305        || {
306            let output = Command::new("rustup")
307                .args(["which", "rust-analyzer"])
308                .output()
309                .ok()?;
310            if !output.status.success() {
311                return None;
312            }
313            let path =
314                String::from_utf8_lossy(&output.stdout).trim().to_string();
315            (!path.is_empty()).then_some(path)
316        },
317    )
318}
319
320/// Same as [`resolve_rust_analyzer_command`], but takes injectable checks for the
321/// environment lookup, the PATH probe, and the `rustup which` fallback so the
322/// priority order can be unit-tested without spawning real subprocesses.
323fn resolve_rust_analyzer_command_with(
324    lookup: impl Fn(&str) -> Option<String>,
325    is_on_path: impl Fn() -> bool,
326    rustup_which: impl Fn() -> Option<String>,
327) -> Result<String, String> {
328    if let Some(path) = resolve_program_from_envs_with(
329        &["RUST_ANALYZER", "RUST_ANALYZER_PATH"],
330        &lookup,
331    ) {
332        return Ok(path);
333    }
334    if is_on_path() {
335        return Ok("rust-analyzer".to_string());
336    }
337    if let Some(path) = rustup_which() {
338        return Ok(path);
339    }
340    Err(
341        "rust-analyzer not found. Please run rustup component add rust-analyzer or brew install rust-analyzer"
342            .to_string(),
343    )
344}
345
346/// Resolves the gopls command with special handling.
347/// Checks in order:
348/// 1. GOPLS / GOPLS_PATH environment variables
349/// 2. Direct gopls command on PATH
350/// 3. `$GOBIN/gopls`
351/// 4. `$GOPATH/bin/gopls` for each `GOPATH` entry (platform path-list
352///    separator: `;` on Windows, `:` elsewhere)
353fn resolve_gopls_command() -> Result<String, String> {
354    resolve_gopls_command_with(
355        |var| std::env::var(var).ok(),
356        || Command::new("gopls").arg("version").output().is_ok(),
357        || go_env_var("GOBIN"),
358        || go_env_var("GOPATH"),
359        Path::exists,
360    )
361}
362
363/// Runs `go env <var>` and returns its trimmed stdout, or `None` on failure.
364fn go_env_var(var: &str) -> Option<String> {
365    let output = Command::new("go").args(["env", var]).output().ok()?;
366    if !output.status.success() {
367        return None;
368    }
369    let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
370    (!value.is_empty()).then_some(value)
371}
372
373/// Same as [`resolve_gopls_command`], but takes injectable checks for the
374/// environment lookup, the PATH probe, the `$GOBIN`/`$GOPATH` lookups, and the
375/// filesystem existence check, so the priority order can be unit-tested without
376/// spawning real subprocesses or touching the real filesystem.
377fn resolve_gopls_command_with(
378    lookup: impl Fn(&str) -> Option<String>,
379    is_on_path: impl Fn() -> bool,
380    gobin: impl Fn() -> Option<String>,
381    gopath: impl Fn() -> Option<String>,
382    exists: impl Fn(&Path) -> bool,
383) -> Result<String, String> {
384    if let Some(path) =
385        resolve_program_from_envs_with(&["GOPLS", "GOPLS_PATH"], &lookup)
386    {
387        return Ok(path);
388    }
389    if is_on_path() {
390        return Ok("gopls".to_string());
391    }
392    if let Some(gobin_path) = gobin() {
393        let candidate = PathBuf::from(gobin_path).join("gopls");
394        if exists(&candidate) {
395            return Ok(candidate.to_string_lossy().to_string());
396        }
397    }
398    if let Some(gopath_value) = gopath() {
399        // Platform path-list separator (`;` on Windows, `:` elsewhere), not a
400        // literal colon: `GOPATH` follows the same convention as `PATH`.
401        for path in std::env::split_paths(&gopath_value) {
402            if path.as_os_str().is_empty() {
403                continue;
404            }
405            let candidate = path.join("bin").join("gopls");
406            if exists(&candidate) {
407                return Ok(candidate.to_string_lossy().to_string());
408            }
409        }
410    }
411    Err(
412        "gopls not found. Please set GOPLS/GOPLS_PATH or add GOPATH/bin to PATH"
413            .to_string(),
414    )
415}
416
417/// Ensures rust-analyzer configuration directory exists on macOS.
418///
419/// Creates the configuration directory and an empty config file if they don't exist.
420/// This prevents rust-analyzer from failing on first run on macOS.
421///
422/// # Examples
423///
424/// ```no_run
425/// use iced_code_editor::ensure_rust_analyzer_config;
426///
427/// // Safe to call on any platform; no-op on non-macOS.
428/// ensure_rust_analyzer_config();
429/// ```
430#[cfg(target_os = "macos")]
431pub fn ensure_rust_analyzer_config() {
432    let Some(home) = std::env::var_os("HOME") else { return };
433    let mut path = std::path::PathBuf::from(home);
434    path.push("Library");
435    path.push("Application Support");
436    path.push("rust-analyzer");
437    let _ = std::fs::create_dir_all(&path);
438    path.push("rust-analyzer.toml");
439    if !path.exists() {
440        let _ = std::fs::write(path, "");
441    }
442}
443
444/// No-op on non-macOS platforms.
445///
446/// # Examples
447///
448/// ```no_run
449/// use iced_code_editor::ensure_rust_analyzer_config;
450///
451/// // Safe to call on any platform; no-op on non-macOS.
452/// ensure_rust_analyzer_config();
453/// ```
454#[cfg(not(target_os = "macos"))]
455pub fn ensure_rust_analyzer_config() {}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460    use std::collections::HashMap;
461
462    fn lookup_from(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
463        let map: HashMap<&str, &str> = vars.iter().copied().collect();
464        move |var: &str| map.get(var).map(|v| v.to_string())
465    }
466
467    // ---- lsp_language_for_extension ----
468
469    #[test]
470    #[allow(clippy::unwrap_used)]
471    fn test_lsp_language_for_extension_known() {
472        let lang = lsp_language_for_extension("rs").unwrap();
473        assert_eq!(lang.language_id, "rust");
474        assert_eq!(lang.server_key, "rust-analyzer");
475    }
476
477    #[test]
478    #[allow(clippy::unwrap_used)]
479    fn test_lsp_language_for_extension_is_case_insensitive() {
480        let lang = lsp_language_for_extension("RS").unwrap();
481        assert_eq!(lang.language_id, "rust");
482    }
483
484    #[test]
485    #[allow(clippy::unwrap_used)]
486    fn test_lsp_language_for_extension_shared_by_multiple_extensions() {
487        let jsx = lsp_language_for_extension("jsx").unwrap();
488        let ts = lsp_language_for_extension("tsx").unwrap();
489        assert_eq!(jsx.server_key, "typescript-language-server");
490        assert_eq!(ts.language_id, "typescript");
491    }
492
493    #[test]
494    fn test_lsp_language_for_extension_unknown() {
495        assert!(lsp_language_for_extension("xyz").is_none());
496    }
497
498    // ---- lsp_language_for_path ----
499
500    #[test]
501    #[allow(clippy::unwrap_used)]
502    fn test_lsp_language_for_path_known_extension() {
503        let lang = lsp_language_for_path(Path::new("src/main.go")).unwrap();
504        assert_eq!(lang.server_key, "gopls");
505    }
506
507    #[test]
508    fn test_lsp_language_for_path_no_extension() {
509        assert!(lsp_language_for_path(Path::new("Makefile")).is_none());
510    }
511
512    #[test]
513    fn test_lsp_language_for_path_unknown_extension() {
514        assert!(lsp_language_for_path(Path::new("data.xyz")).is_none());
515    }
516
517    // ---- lsp_server_config ----
518
519    #[test]
520    #[allow(clippy::unwrap_used)]
521    fn test_lsp_server_config_known() {
522        let cfg = lsp_server_config("gopls").unwrap();
523        assert_eq!(cfg.env_vars, &["GOPLS", "GOPLS_PATH"]);
524        assert_eq!(cfg.default_command, &["gopls"]);
525    }
526
527    #[test]
528    fn test_lsp_server_config_unknown() {
529        assert!(lsp_server_config("unknown-server").is_none());
530    }
531
532    // ---- resolve_program_from_envs_with ----
533
534    #[test]
535    fn test_resolve_program_from_envs_with_first_set_var_wins() {
536        let lookup = lookup_from(&[("SECOND", "/bin/second")]);
537        let result =
538            resolve_program_from_envs_with(&["FIRST", "SECOND"], lookup);
539        assert_eq!(result, Some("/bin/second".to_string()));
540    }
541
542    #[test]
543    fn test_resolve_program_from_envs_with_skips_blank_values() {
544        let lookup =
545            lookup_from(&[("FIRST", "   "), ("SECOND", "/bin/second")]);
546        let result =
547            resolve_program_from_envs_with(&["FIRST", "SECOND"], lookup);
548        assert_eq!(result, Some("/bin/second".to_string()));
549    }
550
551    #[test]
552    fn test_resolve_program_from_envs_with_none_when_all_unset() {
553        let lookup = lookup_from(&[]);
554        let result =
555            resolve_program_from_envs_with(&["FIRST", "SECOND"], lookup);
556        assert_eq!(result, None);
557    }
558
559    #[test]
560    fn test_resolve_program_from_envs_with_trims_surrounding_whitespace() {
561        // Emptiness is judged on the trimmed value, so the returned value must
562        // be trimmed too. A shell-config typo or a CI variable carrying a
563        // trailing newline would otherwise reach `Command::new` verbatim and
564        // fail with a confusing "No such file or directory".
565        let lookup = lookup_from(&[("FIRST", "  /bin/first\n")]);
566        let result =
567            resolve_program_from_envs_with(&["FIRST", "SECOND"], lookup);
568        assert_eq!(result, Some("/bin/first".to_string()));
569    }
570
571    // ---- resolve_rust_analyzer_command_with ----
572
573    #[test]
574    fn test_resolve_rust_analyzer_command_with_env_var_takes_priority() {
575        let lookup = lookup_from(&[("RUST_ANALYZER", "/custom/rust-analyzer")]);
576        let result =
577            resolve_rust_analyzer_command_with(lookup, || true, || None);
578        assert_eq!(result, Ok("/custom/rust-analyzer".to_string()));
579    }
580
581    #[test]
582    fn test_resolve_rust_analyzer_command_with_falls_back_to_path() {
583        let lookup = lookup_from(&[]);
584        let result =
585            resolve_rust_analyzer_command_with(lookup, || true, || None);
586        assert_eq!(result, Ok("rust-analyzer".to_string()));
587    }
588
589    #[test]
590    fn test_resolve_rust_analyzer_command_with_falls_back_to_rustup() {
591        let lookup = lookup_from(&[]);
592        let result = resolve_rust_analyzer_command_with(
593            lookup,
594            || false,
595            || Some("/home/user/.rustup/bin/rust-analyzer".to_string()),
596        );
597        assert_eq!(
598            result,
599            Ok("/home/user/.rustup/bin/rust-analyzer".to_string())
600        );
601    }
602
603    #[test]
604    #[allow(clippy::unwrap_used)]
605    fn test_resolve_rust_analyzer_command_with_returns_err_when_nothing_found()
606    {
607        let lookup = lookup_from(&[]);
608        let result =
609            resolve_rust_analyzer_command_with(lookup, || false, || None);
610        result.unwrap_err();
611    }
612
613    // ---- resolve_gopls_command_with ----
614
615    #[test]
616    fn test_resolve_gopls_command_with_env_var_takes_priority() {
617        let lookup = lookup_from(&[("GOPLS", "/custom/gopls")]);
618        let result = resolve_gopls_command_with(
619            lookup,
620            || true,
621            || None,
622            || None,
623            |_| true,
624        );
625        assert_eq!(result, Ok("/custom/gopls".to_string()));
626    }
627
628    #[test]
629    fn test_resolve_gopls_command_with_falls_back_to_path() {
630        let lookup = lookup_from(&[]);
631        let result = resolve_gopls_command_with(
632            lookup,
633            || true,
634            || None,
635            || None,
636            |_| true,
637        );
638        assert_eq!(result, Ok("gopls".to_string()));
639    }
640
641    #[test]
642    fn test_resolve_gopls_command_with_falls_back_to_gobin_when_it_exists() {
643        let lookup = lookup_from(&[]);
644        let result = resolve_gopls_command_with(
645            lookup,
646            || false,
647            || Some("/home/user/go/bin".to_string()),
648            || None,
649            |p| p == Path::new("/home/user/go/bin/gopls"),
650        );
651        assert_eq!(result, Ok("/home/user/go/bin/gopls".to_string()));
652    }
653
654    #[test]
655    fn test_resolve_gopls_command_with_falls_back_to_gopath_when_it_exists() {
656        let lookup = lookup_from(&[]);
657        let result = resolve_gopls_command_with(
658            lookup,
659            || false,
660            || None,
661            || Some("/nonexistent:/home/user/go".to_string()),
662            |p| p == Path::new("/home/user/go/bin/gopls"),
663        );
664        assert_eq!(result, Ok("/home/user/go/bin/gopls".to_string()));
665    }
666
667    #[test]
668    #[allow(clippy::unwrap_used)]
669    fn test_resolve_gopls_command_with_skips_gobin_when_gopls_does_not_exist_there()
670     {
671        let lookup = lookup_from(&[]);
672        let result = resolve_gopls_command_with(
673            lookup,
674            || false,
675            || Some("/home/user/go/bin".to_string()),
676            || Some("/home/user/go".to_string()),
677            |_| false,
678        );
679        result.unwrap_err();
680    }
681
682    #[test]
683    #[allow(clippy::unwrap_used)]
684    fn test_resolve_gopls_command_with_returns_err_when_nothing_found() {
685        let lookup = lookup_from(&[]);
686        let result = resolve_gopls_command_with(
687            lookup,
688            || false,
689            || None,
690            || None,
691            |_| false,
692        );
693        result.unwrap_err();
694    }
695}