typescript.rs

  1use anyhow::{anyhow, Result};
  2use async_compression::futures::bufread::GzipDecoder;
  3use async_tar::Archive;
  4use async_trait::async_trait;
  5use collections::HashMap;
  6use futures::{future::BoxFuture, FutureExt};
  7use gpui::AppContext;
  8use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
  9use lsp::{CodeActionKind, LanguageServerBinary};
 10use node_runtime::NodeRuntime;
 11use serde_json::{json, Value};
 12use smol::{fs, io::BufReader, stream::StreamExt};
 13use std::{
 14    any::Any,
 15    ffi::OsString,
 16    future,
 17    path::{Path, PathBuf},
 18    sync::Arc,
 19};
 20use util::{fs::remove_matching, github::latest_github_release};
 21use util::{github::GitHubLspBinaryVersion, ResultExt};
 22
 23fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 24    vec![server_path.into(), "--stdio".into()]
 25}
 26
 27fn eslint_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 28    vec![server_path.into(), "--stdio".into()]
 29}
 30
 31pub struct TypeScriptLspAdapter {
 32    node: Arc<dyn NodeRuntime>,
 33}
 34
 35impl TypeScriptLspAdapter {
 36    const OLD_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.js";
 37    const NEW_SERVER_PATH: &'static str = "node_modules/typescript-language-server/lib/cli.mjs";
 38
 39    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
 40        TypeScriptLspAdapter { node }
 41    }
 42}
 43
 44struct TypeScriptVersions {
 45    typescript_version: String,
 46    server_version: String,
 47}
 48
 49#[async_trait]
 50impl LspAdapter for TypeScriptLspAdapter {
 51    async fn name(&self) -> LanguageServerName {
 52        LanguageServerName("typescript-language-server".into())
 53    }
 54
 55    fn short_name(&self) -> &'static str {
 56        "tsserver"
 57    }
 58
 59    async fn fetch_latest_server_version(
 60        &self,
 61        _: &dyn LspAdapterDelegate,
 62    ) -> Result<Box<dyn 'static + Send + Any>> {
 63        Ok(Box::new(TypeScriptVersions {
 64            typescript_version: self.node.npm_package_latest_version("typescript").await?,
 65            server_version: self
 66                .node
 67                .npm_package_latest_version("typescript-language-server")
 68                .await?,
 69        }) as Box<_>)
 70    }
 71
 72    async fn fetch_server_binary(
 73        &self,
 74        version: Box<dyn 'static + Send + Any>,
 75        container_dir: PathBuf,
 76        _: &dyn LspAdapterDelegate,
 77    ) -> Result<LanguageServerBinary> {
 78        let version = version.downcast::<TypeScriptVersions>().unwrap();
 79        let server_path = container_dir.join(Self::NEW_SERVER_PATH);
 80
 81        if fs::metadata(&server_path).await.is_err() {
 82            self.node
 83                .npm_install_packages(
 84                    &container_dir,
 85                    &[
 86                        ("typescript", version.typescript_version.as_str()),
 87                        (
 88                            "typescript-language-server",
 89                            version.server_version.as_str(),
 90                        ),
 91                    ],
 92                )
 93                .await?;
 94        }
 95
 96        Ok(LanguageServerBinary {
 97            path: self.node.binary_path().await?,
 98            arguments: typescript_server_binary_arguments(&server_path),
 99        })
100    }
101
102    async fn cached_server_binary(
103        &self,
104        container_dir: PathBuf,
105        _: &dyn LspAdapterDelegate,
106    ) -> Option<LanguageServerBinary> {
107        get_cached_ts_server_binary(container_dir, &*self.node).await
108    }
109
110    async fn installation_test_binary(
111        &self,
112        container_dir: PathBuf,
113    ) -> Option<LanguageServerBinary> {
114        get_cached_ts_server_binary(container_dir, &*self.node).await
115    }
116
117    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
118        Some(vec![
119            CodeActionKind::QUICKFIX,
120            CodeActionKind::REFACTOR,
121            CodeActionKind::REFACTOR_EXTRACT,
122            CodeActionKind::SOURCE,
123        ])
124    }
125
126    async fn label_for_completion(
127        &self,
128        item: &lsp::CompletionItem,
129        language: &Arc<language::Language>,
130    ) -> Option<language::CodeLabel> {
131        use lsp::CompletionItemKind as Kind;
132        let len = item.label.len();
133        let grammar = language.grammar()?;
134        let highlight_id = match item.kind? {
135            Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
136            Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
137            Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
138            Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
139            Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
140            _ => None,
141        }?;
142
143        let text = match &item.detail {
144            Some(detail) => format!("{} {}", item.label, detail),
145            None => item.label.clone(),
146        };
147
148        Some(language::CodeLabel {
149            text,
150            runs: vec![(0..len, highlight_id)],
151            filter_range: 0..len,
152        })
153    }
154
155    async fn initialization_options(&self) -> Option<serde_json::Value> {
156        Some(json!({
157            "provideFormatter": true,
158            "tsserver": {
159                "path": "node_modules/typescript/lib",
160            },
161        }))
162    }
163
164    async fn language_ids(&self) -> HashMap<String, String> {
165        HashMap::from_iter([
166            ("TypeScript".into(), "typescript".into()),
167            ("JavaScript".into(), "javascript".into()),
168            ("TSX".into(), "typescriptreact".into()),
169        ])
170    }
171}
172
173async fn get_cached_ts_server_binary(
174    container_dir: PathBuf,
175    node: &dyn NodeRuntime,
176) -> Option<LanguageServerBinary> {
177    (|| async move {
178        let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
179        let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
180        if new_server_path.exists() {
181            Ok(LanguageServerBinary {
182                path: node.binary_path().await?,
183                arguments: typescript_server_binary_arguments(&new_server_path),
184            })
185        } else if old_server_path.exists() {
186            Ok(LanguageServerBinary {
187                path: node.binary_path().await?,
188                arguments: typescript_server_binary_arguments(&old_server_path),
189            })
190        } else {
191            Err(anyhow!(
192                "missing executable in directory {:?}",
193                container_dir
194            ))
195        }
196    })()
197    .await
198    .log_err()
199}
200
201pub struct EsLintLspAdapter {
202    node: Arc<dyn NodeRuntime>,
203}
204
205impl EsLintLspAdapter {
206    const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
207
208    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
209        EsLintLspAdapter { node }
210    }
211}
212
213#[async_trait]
214impl LspAdapter for EsLintLspAdapter {
215    fn workspace_configuration(
216        &self,
217        workspace_root: &Path,
218        _: &mut AppContext,
219    ) -> BoxFuture<'static, Value> {
220        future::ready(json!({
221            "": {
222                "validate": "on",
223                "rulesCustomizations": [],
224                "run": "onType",
225                "nodePath": null,
226                "workingDirectory": {"mode": "auto"},
227                "workspaceFolder": {
228                    "uri": workspace_root,
229                    "name": workspace_root.file_name()
230                        .unwrap_or_else(|| workspace_root.as_os_str()),
231                },
232            }
233        }))
234        .boxed()
235    }
236
237    async fn name(&self) -> LanguageServerName {
238        LanguageServerName("eslint".into())
239    }
240
241    fn short_name(&self) -> &'static str {
242        "eslint"
243    }
244
245    async fn fetch_latest_server_version(
246        &self,
247        delegate: &dyn LspAdapterDelegate,
248    ) -> Result<Box<dyn 'static + Send + Any>> {
249        // At the time of writing the latest vscode-eslint release was released in 2020 and requires
250        // special custom LSP protocol extensions be handled to fully initialize. Download the latest
251        // prerelease instead to sidestep this issue
252        let release =
253            latest_github_release("microsoft/vscode-eslint", true, delegate.http_client()).await?;
254        Ok(Box::new(GitHubLspBinaryVersion {
255            name: release.name,
256            url: release.tarball_url,
257        }))
258    }
259
260    async fn fetch_server_binary(
261        &self,
262        version: Box<dyn 'static + Send + Any>,
263        container_dir: PathBuf,
264        delegate: &dyn LspAdapterDelegate,
265    ) -> Result<LanguageServerBinary> {
266        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
267        let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
268        let server_path = destination_path.join(Self::SERVER_PATH);
269
270        if fs::metadata(&server_path).await.is_err() {
271            remove_matching(&container_dir, |entry| entry != destination_path).await;
272
273            let mut response = delegate
274                .http_client()
275                .get(&version.url, Default::default(), true)
276                .await
277                .map_err(|err| anyhow!("error downloading release: {}", err))?;
278            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
279            let archive = Archive::new(decompressed_bytes);
280            archive.unpack(&destination_path).await?;
281
282            let mut dir = fs::read_dir(&destination_path).await?;
283            let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
284            let repo_root = destination_path.join("vscode-eslint");
285            fs::rename(first.path(), &repo_root).await?;
286
287            self.node
288                .run_npm_subcommand(Some(&repo_root), "install", &[])
289                .await?;
290
291            self.node
292                .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
293                .await?;
294        }
295
296        Ok(LanguageServerBinary {
297            path: self.node.binary_path().await?,
298            arguments: eslint_server_binary_arguments(&server_path),
299        })
300    }
301
302    async fn cached_server_binary(
303        &self,
304        container_dir: PathBuf,
305        _: &dyn LspAdapterDelegate,
306    ) -> Option<LanguageServerBinary> {
307        get_cached_eslint_server_binary(container_dir, &*self.node).await
308    }
309
310    async fn installation_test_binary(
311        &self,
312        container_dir: PathBuf,
313    ) -> Option<LanguageServerBinary> {
314        get_cached_eslint_server_binary(container_dir, &*self.node).await
315    }
316
317    async fn label_for_completion(
318        &self,
319        _item: &lsp::CompletionItem,
320        _language: &Arc<language::Language>,
321    ) -> Option<language::CodeLabel> {
322        None
323    }
324
325    async fn initialization_options(&self) -> Option<serde_json::Value> {
326        None
327    }
328}
329
330async fn get_cached_eslint_server_binary(
331    container_dir: PathBuf,
332    node: &dyn NodeRuntime,
333) -> Option<LanguageServerBinary> {
334    (|| async move {
335        // This is unfortunate but we don't know what the version is to build a path directly
336        let mut dir = fs::read_dir(&container_dir).await?;
337        let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
338        if !first.file_type().await?.is_dir() {
339            return Err(anyhow!("First entry is not a directory"));
340        }
341        let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
342
343        Ok(LanguageServerBinary {
344            path: node.binary_path().await?,
345            arguments: eslint_server_binary_arguments(&server_path),
346        })
347    })()
348    .await
349    .log_err()
350}
351
352#[cfg(test)]
353mod tests {
354    use gpui::{Context, TestAppContext};
355    use unindent::Unindent;
356
357    #[gpui::test]
358    async fn test_outline(cx: &mut TestAppContext) {
359        let language = crate::languages::language(
360            "typescript",
361            tree_sitter_typescript::language_typescript(),
362            None,
363        )
364        .await;
365
366        let text = r#"
367            function a() {
368              // local variables are omitted
369              let a1 = 1;
370              // all functions are included
371              async function a2() {}
372            }
373            // top-level variables are included
374            let b: C
375            function getB() {}
376            // exported variables are included
377            export const d = e;
378        "#
379        .unindent();
380
381        let buffer = cx.build_model(|cx| {
382            language::Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
383        });
384        let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
385        assert_eq!(
386            outline
387                .items
388                .iter()
389                .map(|item| (item.text.as_str(), item.depth))
390                .collect::<Vec<_>>(),
391            &[
392                ("function a()", 0),
393                ("async function a2()", 1),
394                ("let b", 0),
395                ("function getB()", 0),
396                ("const d", 0),
397            ]
398        );
399    }
400}