vtsls.rs

  1use anyhow::{anyhow, Result};
  2use async_trait::async_trait;
  3use collections::HashMap;
  4use gpui::AsyncAppContext;
  5use language::{LanguageToolchainStore, LspAdapter, LspAdapterDelegate};
  6use lsp::{CodeActionKind, LanguageServerBinary, LanguageServerName};
  7use node_runtime::NodeRuntime;
  8use project::lsp_store::language_server_settings;
  9use serde_json::Value;
 10use std::{
 11    any::Any,
 12    ffi::OsString,
 13    path::{Path, PathBuf},
 14    sync::Arc,
 15};
 16use util::{maybe, merge_json_value_into, ResultExt};
 17
 18fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 19    vec![server_path.into(), "--stdio".into()]
 20}
 21
 22pub struct VtslsLspAdapter {
 23    node: NodeRuntime,
 24}
 25
 26impl VtslsLspAdapter {
 27    const PACKAGE_NAME: &'static str = "@vtsls/language-server";
 28    const SERVER_PATH: &'static str = "node_modules/@vtsls/language-server/bin/vtsls.js";
 29
 30    const TYPESCRIPT_PACKAGE_NAME: &'static str = "typescript";
 31    const TYPESCRIPT_TSDK_PATH: &'static str = "node_modules/typescript/lib";
 32
 33    pub fn new(node: NodeRuntime) -> Self {
 34        VtslsLspAdapter { node }
 35    }
 36
 37    async fn tsdk_path(adapter: &Arc<dyn LspAdapterDelegate>) -> &'static str {
 38        let is_yarn = adapter
 39            .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
 40            .await
 41            .is_ok();
 42
 43        if is_yarn {
 44            ".yarn/sdks/typescript/lib"
 45        } else {
 46            Self::TYPESCRIPT_TSDK_PATH
 47        }
 48    }
 49}
 50
 51struct TypeScriptVersions {
 52    typescript_version: String,
 53    server_version: String,
 54}
 55
 56const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("vtsls");
 57
 58#[async_trait(?Send)]
 59impl LspAdapter for VtslsLspAdapter {
 60    fn name(&self) -> LanguageServerName {
 61        SERVER_NAME.clone()
 62    }
 63
 64    async fn fetch_latest_server_version(
 65        &self,
 66        _: &dyn LspAdapterDelegate,
 67    ) -> Result<Box<dyn 'static + Send + Any>> {
 68        Ok(Box::new(TypeScriptVersions {
 69            typescript_version: self.node.npm_package_latest_version("typescript").await?,
 70            server_version: self
 71                .node
 72                .npm_package_latest_version("@vtsls/language-server")
 73                .await?,
 74        }) as Box<_>)
 75    }
 76
 77    async fn check_if_user_installed(
 78        &self,
 79        delegate: &dyn LspAdapterDelegate,
 80        _: Arc<dyn LanguageToolchainStore>,
 81        _: &AsyncAppContext,
 82    ) -> Option<LanguageServerBinary> {
 83        let env = delegate.shell_env().await;
 84        let path = delegate.which(SERVER_NAME.as_ref()).await?;
 85        Some(LanguageServerBinary {
 86            path: path.clone(),
 87            arguments: typescript_server_binary_arguments(&path),
 88            env: Some(env),
 89        })
 90    }
 91
 92    async fn fetch_server_binary(
 93        &self,
 94        latest_version: Box<dyn 'static + Send + Any>,
 95        container_dir: PathBuf,
 96        _: &dyn LspAdapterDelegate,
 97    ) -> Result<LanguageServerBinary> {
 98        let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
 99        let server_path = container_dir.join(Self::SERVER_PATH);
100
101        let mut packages_to_install = Vec::new();
102
103        if self
104            .node
105            .should_install_npm_package(
106                Self::PACKAGE_NAME,
107                &server_path,
108                &container_dir,
109                &latest_version.server_version,
110            )
111            .await
112        {
113            packages_to_install.push((Self::PACKAGE_NAME, latest_version.server_version.as_str()));
114        }
115
116        if self
117            .node
118            .should_install_npm_package(
119                Self::TYPESCRIPT_PACKAGE_NAME,
120                &container_dir.join(Self::TYPESCRIPT_TSDK_PATH),
121                &container_dir,
122                &latest_version.typescript_version,
123            )
124            .await
125        {
126            packages_to_install.push((
127                Self::TYPESCRIPT_PACKAGE_NAME,
128                latest_version.typescript_version.as_str(),
129            ));
130        }
131
132        self.node
133            .npm_install_packages(&container_dir, &packages_to_install)
134            .await?;
135
136        Ok(LanguageServerBinary {
137            path: self.node.binary_path().await?,
138            env: None,
139            arguments: typescript_server_binary_arguments(&server_path),
140        })
141    }
142
143    async fn cached_server_binary(
144        &self,
145        container_dir: PathBuf,
146        _: &dyn LspAdapterDelegate,
147    ) -> Option<LanguageServerBinary> {
148        get_cached_ts_server_binary(container_dir, &self.node).await
149    }
150
151    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
152        Some(vec![
153            CodeActionKind::QUICKFIX,
154            CodeActionKind::REFACTOR,
155            CodeActionKind::REFACTOR_EXTRACT,
156            CodeActionKind::SOURCE,
157        ])
158    }
159
160    async fn label_for_completion(
161        &self,
162        item: &lsp::CompletionItem,
163        language: &Arc<language::Language>,
164    ) -> Option<language::CodeLabel> {
165        use lsp::CompletionItemKind as Kind;
166        let len = item.label.len();
167        let grammar = language.grammar()?;
168        let highlight_id = match item.kind? {
169            Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
170            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
171            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
172            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
173            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
174            Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
175            _ => None,
176        }?;
177
178        let text = if let Some(description) = item
179            .label_details
180            .as_ref()
181            .and_then(|label_details| label_details.description.as_ref())
182        {
183            format!("{} {}", item.label, description)
184        } else if let Some(detail) = &item.detail {
185            format!("{} {}", item.label, detail)
186        } else {
187            item.label.clone()
188        };
189
190        Some(language::CodeLabel {
191            text,
192            runs: vec![(0..len, highlight_id)],
193            filter_range: 0..len,
194        })
195    }
196
197    async fn workspace_configuration(
198        self: Arc<Self>,
199        delegate: &Arc<dyn LspAdapterDelegate>,
200        _: Arc<dyn LanguageToolchainStore>,
201        cx: &mut AsyncAppContext,
202    ) -> Result<Value> {
203        let tsdk_path = Self::tsdk_path(delegate).await;
204        let config = serde_json::json!({
205            "tsdk": tsdk_path,
206            "suggest": {
207                "completeFunctionCalls": true
208            },
209            "inlayHints": {
210                "parameterNames": {
211                    "enabled": "all",
212                    "suppressWhenArgumentMatchesName": false
213                },
214                "parameterTypes": {
215                    "enabled": true
216                },
217                "variableTypes": {
218                    "enabled": true,
219                    "suppressWhenTypeMatchesName": false
220                },
221                "propertyDeclarationTypes": {
222                    "enabled": true
223                },
224                "functionLikeReturnTypes": {
225                    "enabled": true
226                },
227                "enumMemberValues": {
228                    "enabled": true
229                }
230            },
231            "tsserver": {
232                "maxTsServerMemory": 8092
233            },
234        });
235
236        let mut default_workspace_configuration = serde_json::json!({
237            "typescript": config,
238            "javascript": config,
239            "vtsls": {
240                "experimental": {
241                    "completion": {
242                        "enableServerSideFuzzyMatch": true,
243                        "entriesLimit": 5000,
244                    }
245                },
246               "autoUseWorkspaceTsdk": true
247            }
248        });
249
250        let override_options = cx.update(|cx| {
251            language_server_settings(delegate.as_ref(), &SERVER_NAME, cx)
252                .and_then(|s| s.settings.clone())
253        })?;
254
255        if let Some(override_options) = override_options {
256            merge_json_value_into(override_options, &mut default_workspace_configuration)
257        }
258
259        Ok(default_workspace_configuration)
260    }
261
262    fn language_ids(&self) -> HashMap<String, String> {
263        HashMap::from_iter([
264            ("TypeScript".into(), "typescript".into()),
265            ("JavaScript".into(), "javascript".into()),
266            ("TSX".into(), "typescriptreact".into()),
267        ])
268    }
269}
270
271async fn get_cached_ts_server_binary(
272    container_dir: PathBuf,
273    node: &NodeRuntime,
274) -> Option<LanguageServerBinary> {
275    maybe!(async {
276        let server_path = container_dir.join(VtslsLspAdapter::SERVER_PATH);
277        if server_path.exists() {
278            Ok(LanguageServerBinary {
279                path: node.binary_path().await?,
280                env: None,
281                arguments: typescript_server_binary_arguments(&server_path),
282            })
283        } else {
284            Err(anyhow!(
285                "missing executable in directory {:?}",
286                container_dir
287            ))
288        }
289    })
290    .await
291    .log_err()
292}