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, or None if all are unset/empty.
266fn resolve_program_from_envs(env_vars: &[&str]) -> Option<String> {
267    resolve_program_from_envs_with(env_vars, |var| std::env::var(var).ok())
268}
269
270/// Same as [`resolve_program_from_envs`], but takes an injectable lookup so the
271/// priority order can be unit-tested without touching real process environment.
272fn resolve_program_from_envs_with(
273    env_vars: &[&str],
274    lookup: impl Fn(&str) -> Option<String>,
275) -> Option<String> {
276    for var in env_vars {
277        if let Some(path) = lookup(var)
278            && !path.trim().is_empty()
279        {
280            return Some(path);
281        }
282    }
283    None
284}
285
286/// Resolves the rust-analyzer command with special handling.
287/// Checks in order:
288/// 1. RUST_ANALYZER environment variable
289/// 2. RUST_ANALYZER_PATH environment variable
290/// 3. Direct rust-analyzer command
291/// 4. rustup which rust-analyzer
292fn resolve_rust_analyzer_command() -> Result<String, String> {
293    resolve_rust_analyzer_command_with(
294        |var| std::env::var(var).ok(),
295        || Command::new("rust-analyzer").arg("--version").output().is_ok(),
296        || {
297            let output = Command::new("rustup")
298                .args(["which", "rust-analyzer"])
299                .output()
300                .ok()?;
301            if !output.status.success() {
302                return None;
303            }
304            let path =
305                String::from_utf8_lossy(&output.stdout).trim().to_string();
306            (!path.is_empty()).then_some(path)
307        },
308    )
309}
310
311/// Same as [`resolve_rust_analyzer_command`], but takes injectable checks for the
312/// environment lookup, the PATH probe, and the `rustup which` fallback so the
313/// priority order can be unit-tested without spawning real subprocesses.
314fn resolve_rust_analyzer_command_with(
315    lookup: impl Fn(&str) -> Option<String>,
316    is_on_path: impl Fn() -> bool,
317    rustup_which: impl Fn() -> Option<String>,
318) -> Result<String, String> {
319    if let Some(path) = resolve_program_from_envs_with(
320        &["RUST_ANALYZER", "RUST_ANALYZER_PATH"],
321        &lookup,
322    ) {
323        return Ok(path);
324    }
325    if is_on_path() {
326        return Ok("rust-analyzer".to_string());
327    }
328    if let Some(path) = rustup_which() {
329        return Ok(path);
330    }
331    Err(
332        "rust-analyzer not found. Please run rustup component add rust-analyzer or brew install rust-analyzer"
333            .to_string(),
334    )
335}
336
337/// Resolves the gopls command with special handling.
338/// Checks in order:
339/// 1. GOPLS / GOPLS_PATH environment variables
340/// 2. Direct gopls command on PATH
341/// 3. `$GOBIN/gopls`
342/// 4. `$GOPATH/bin/gopls` for each `GOPATH` entry (platform path-list
343///    separator: `;` on Windows, `:` elsewhere)
344fn resolve_gopls_command() -> Result<String, String> {
345    resolve_gopls_command_with(
346        |var| std::env::var(var).ok(),
347        || Command::new("gopls").arg("version").output().is_ok(),
348        || go_env_var("GOBIN"),
349        || go_env_var("GOPATH"),
350        Path::exists,
351    )
352}
353
354/// Runs `go env <var>` and returns its trimmed stdout, or `None` on failure.
355fn go_env_var(var: &str) -> Option<String> {
356    let output = Command::new("go").args(["env", var]).output().ok()?;
357    if !output.status.success() {
358        return None;
359    }
360    let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
361    (!value.is_empty()).then_some(value)
362}
363
364/// Same as [`resolve_gopls_command`], but takes injectable checks for the
365/// environment lookup, the PATH probe, the `$GOBIN`/`$GOPATH` lookups, and the
366/// filesystem existence check, so the priority order can be unit-tested without
367/// spawning real subprocesses or touching the real filesystem.
368fn resolve_gopls_command_with(
369    lookup: impl Fn(&str) -> Option<String>,
370    is_on_path: impl Fn() -> bool,
371    gobin: impl Fn() -> Option<String>,
372    gopath: impl Fn() -> Option<String>,
373    exists: impl Fn(&Path) -> bool,
374) -> Result<String, String> {
375    if let Some(path) =
376        resolve_program_from_envs_with(&["GOPLS", "GOPLS_PATH"], &lookup)
377    {
378        return Ok(path);
379    }
380    if is_on_path() {
381        return Ok("gopls".to_string());
382    }
383    if let Some(gobin_path) = gobin() {
384        let candidate = PathBuf::from(gobin_path).join("gopls");
385        if exists(&candidate) {
386            return Ok(candidate.to_string_lossy().to_string());
387        }
388    }
389    if let Some(gopath_value) = gopath() {
390        // Platform path-list separator (`;` on Windows, `:` elsewhere), not a
391        // literal colon: `GOPATH` follows the same convention as `PATH`.
392        for path in std::env::split_paths(&gopath_value) {
393            if path.as_os_str().is_empty() {
394                continue;
395            }
396            let candidate = path.join("bin").join("gopls");
397            if exists(&candidate) {
398                return Ok(candidate.to_string_lossy().to_string());
399            }
400        }
401    }
402    Err(
403        "gopls not found. Please set GOPLS/GOPLS_PATH or add GOPATH/bin to PATH"
404            .to_string(),
405    )
406}
407
408/// Ensures rust-analyzer configuration directory exists on macOS.
409///
410/// Creates the configuration directory and an empty config file if they don't exist.
411/// This prevents rust-analyzer from failing on first run on macOS.
412///
413/// # Examples
414///
415/// ```no_run
416/// use iced_code_editor::ensure_rust_analyzer_config;
417///
418/// // Safe to call on any platform; no-op on non-macOS.
419/// ensure_rust_analyzer_config();
420/// ```
421#[cfg(target_os = "macos")]
422pub fn ensure_rust_analyzer_config() {
423    let Some(home) = std::env::var_os("HOME") else { return };
424    let mut path = std::path::PathBuf::from(home);
425    path.push("Library");
426    path.push("Application Support");
427    path.push("rust-analyzer");
428    let _ = std::fs::create_dir_all(&path);
429    path.push("rust-analyzer.toml");
430    if !path.exists() {
431        let _ = std::fs::write(path, "");
432    }
433}
434
435/// No-op on non-macOS platforms.
436///
437/// # Examples
438///
439/// ```no_run
440/// use iced_code_editor::ensure_rust_analyzer_config;
441///
442/// // Safe to call on any platform; no-op on non-macOS.
443/// ensure_rust_analyzer_config();
444/// ```
445#[cfg(not(target_os = "macos"))]
446pub fn ensure_rust_analyzer_config() {}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use std::collections::HashMap;
452
453    fn lookup_from(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
454        let map: HashMap<&str, &str> = vars.iter().copied().collect();
455        move |var: &str| map.get(var).map(|v| v.to_string())
456    }
457
458    // ---- lsp_language_for_extension ----
459
460    #[test]
461    #[allow(clippy::unwrap_used)]
462    fn test_lsp_language_for_extension_known() {
463        let lang = lsp_language_for_extension("rs").unwrap();
464        assert_eq!(lang.language_id, "rust");
465        assert_eq!(lang.server_key, "rust-analyzer");
466    }
467
468    #[test]
469    #[allow(clippy::unwrap_used)]
470    fn test_lsp_language_for_extension_is_case_insensitive() {
471        let lang = lsp_language_for_extension("RS").unwrap();
472        assert_eq!(lang.language_id, "rust");
473    }
474
475    #[test]
476    #[allow(clippy::unwrap_used)]
477    fn test_lsp_language_for_extension_shared_by_multiple_extensions() {
478        let jsx = lsp_language_for_extension("jsx").unwrap();
479        let ts = lsp_language_for_extension("tsx").unwrap();
480        assert_eq!(jsx.server_key, "typescript-language-server");
481        assert_eq!(ts.language_id, "typescript");
482    }
483
484    #[test]
485    fn test_lsp_language_for_extension_unknown() {
486        assert!(lsp_language_for_extension("xyz").is_none());
487    }
488
489    // ---- lsp_language_for_path ----
490
491    #[test]
492    #[allow(clippy::unwrap_used)]
493    fn test_lsp_language_for_path_known_extension() {
494        let lang = lsp_language_for_path(Path::new("src/main.go")).unwrap();
495        assert_eq!(lang.server_key, "gopls");
496    }
497
498    #[test]
499    fn test_lsp_language_for_path_no_extension() {
500        assert!(lsp_language_for_path(Path::new("Makefile")).is_none());
501    }
502
503    #[test]
504    fn test_lsp_language_for_path_unknown_extension() {
505        assert!(lsp_language_for_path(Path::new("data.xyz")).is_none());
506    }
507
508    // ---- lsp_server_config ----
509
510    #[test]
511    #[allow(clippy::unwrap_used)]
512    fn test_lsp_server_config_known() {
513        let cfg = lsp_server_config("gopls").unwrap();
514        assert_eq!(cfg.env_vars, &["GOPLS", "GOPLS_PATH"]);
515        assert_eq!(cfg.default_command, &["gopls"]);
516    }
517
518    #[test]
519    fn test_lsp_server_config_unknown() {
520        assert!(lsp_server_config("unknown-server").is_none());
521    }
522
523    // ---- resolve_program_from_envs_with ----
524
525    #[test]
526    fn test_resolve_program_from_envs_with_first_set_var_wins() {
527        let lookup = lookup_from(&[("SECOND", "/bin/second")]);
528        let result =
529            resolve_program_from_envs_with(&["FIRST", "SECOND"], lookup);
530        assert_eq!(result, Some("/bin/second".to_string()));
531    }
532
533    #[test]
534    fn test_resolve_program_from_envs_with_skips_blank_values() {
535        let lookup =
536            lookup_from(&[("FIRST", "   "), ("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_none_when_all_unset() {
544        let lookup = lookup_from(&[]);
545        let result =
546            resolve_program_from_envs_with(&["FIRST", "SECOND"], lookup);
547        assert_eq!(result, None);
548    }
549
550    // ---- resolve_rust_analyzer_command_with ----
551
552    #[test]
553    fn test_resolve_rust_analyzer_command_with_env_var_takes_priority() {
554        let lookup = lookup_from(&[("RUST_ANALYZER", "/custom/rust-analyzer")]);
555        let result =
556            resolve_rust_analyzer_command_with(lookup, || true, || None);
557        assert_eq!(result, Ok("/custom/rust-analyzer".to_string()));
558    }
559
560    #[test]
561    fn test_resolve_rust_analyzer_command_with_falls_back_to_path() {
562        let lookup = lookup_from(&[]);
563        let result =
564            resolve_rust_analyzer_command_with(lookup, || true, || None);
565        assert_eq!(result, Ok("rust-analyzer".to_string()));
566    }
567
568    #[test]
569    fn test_resolve_rust_analyzer_command_with_falls_back_to_rustup() {
570        let lookup = lookup_from(&[]);
571        let result = resolve_rust_analyzer_command_with(
572            lookup,
573            || false,
574            || Some("/home/user/.rustup/bin/rust-analyzer".to_string()),
575        );
576        assert_eq!(
577            result,
578            Ok("/home/user/.rustup/bin/rust-analyzer".to_string())
579        );
580    }
581
582    #[test]
583    #[allow(clippy::unwrap_used)]
584    fn test_resolve_rust_analyzer_command_with_returns_err_when_nothing_found()
585    {
586        let lookup = lookup_from(&[]);
587        let result =
588            resolve_rust_analyzer_command_with(lookup, || false, || None);
589        result.unwrap_err();
590    }
591
592    // ---- resolve_gopls_command_with ----
593
594    #[test]
595    fn test_resolve_gopls_command_with_env_var_takes_priority() {
596        let lookup = lookup_from(&[("GOPLS", "/custom/gopls")]);
597        let result = resolve_gopls_command_with(
598            lookup,
599            || true,
600            || None,
601            || None,
602            |_| true,
603        );
604        assert_eq!(result, Ok("/custom/gopls".to_string()));
605    }
606
607    #[test]
608    fn test_resolve_gopls_command_with_falls_back_to_path() {
609        let lookup = lookup_from(&[]);
610        let result = resolve_gopls_command_with(
611            lookup,
612            || true,
613            || None,
614            || None,
615            |_| true,
616        );
617        assert_eq!(result, Ok("gopls".to_string()));
618    }
619
620    #[test]
621    fn test_resolve_gopls_command_with_falls_back_to_gobin_when_it_exists() {
622        let lookup = lookup_from(&[]);
623        let result = resolve_gopls_command_with(
624            lookup,
625            || false,
626            || Some("/home/user/go/bin".to_string()),
627            || None,
628            |p| p == Path::new("/home/user/go/bin/gopls"),
629        );
630        assert_eq!(result, Ok("/home/user/go/bin/gopls".to_string()));
631    }
632
633    #[test]
634    fn test_resolve_gopls_command_with_falls_back_to_gopath_when_it_exists() {
635        let lookup = lookup_from(&[]);
636        let result = resolve_gopls_command_with(
637            lookup,
638            || false,
639            || None,
640            || Some("/nonexistent:/home/user/go".to_string()),
641            |p| p == Path::new("/home/user/go/bin/gopls"),
642        );
643        assert_eq!(result, Ok("/home/user/go/bin/gopls".to_string()));
644    }
645
646    #[test]
647    #[allow(clippy::unwrap_used)]
648    fn test_resolve_gopls_command_with_skips_gobin_when_gopls_does_not_exist_there()
649     {
650        let lookup = lookup_from(&[]);
651        let result = resolve_gopls_command_with(
652            lookup,
653            || false,
654            || Some("/home/user/go/bin".to_string()),
655            || Some("/home/user/go".to_string()),
656            |_| false,
657        );
658        result.unwrap_err();
659    }
660
661    #[test]
662    #[allow(clippy::unwrap_used)]
663    fn test_resolve_gopls_command_with_returns_err_when_nothing_found() {
664        let lookup = lookup_from(&[]);
665        let result = resolve_gopls_command_with(
666            lookup,
667            || false,
668            || None,
669            || None,
670            |_| false,
671        );
672        result.unwrap_err();
673    }
674}