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    #[allow(unused)]
209    pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
210        EsLintLspAdapter { node }
211    }
212}
213
214#[async_trait]
215impl LspAdapter for EsLintLspAdapter {
216    fn workspace_configuration(&self, _: &mut AppContext) -> BoxFuture<'static, Value> {
217        future::ready(json!({
218            "": {
219                "validate": "on",
220                "rulesCustomizations": [],
221                "run": "onType",
222                "nodePath": null,
223            }
224        }))
225        .boxed()
226    }
227
228    async fn name(&self) -> LanguageServerName {
229        LanguageServerName("eslint".into())
230    }
231
232    fn short_name(&self) -> &'static str {
233        "eslint"
234    }
235
236    async fn fetch_latest_server_version(
237        &self,
238        delegate: &dyn LspAdapterDelegate,
239    ) -> Result<Box<dyn 'static + Send + Any>> {
240        // At the time of writing the latest vscode-eslint release was released in 2020 and requires
241        // special custom LSP protocol extensions be handled to fully initialize. Download the latest
242        // prerelease instead to sidestep this issue
243        let release =
244            latest_github_release("microsoft/vscode-eslint", true, delegate.http_client()).await?;
245        Ok(Box::new(GitHubLspBinaryVersion {
246            name: release.name,
247            url: release.tarball_url,
248        }))
249    }
250
251    async fn fetch_server_binary(
252        &self,
253        version: Box<dyn 'static + Send + Any>,
254        container_dir: PathBuf,
255        delegate: &dyn LspAdapterDelegate,
256    ) -> Result<LanguageServerBinary> {
257        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
258        let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
259        let server_path = destination_path.join(Self::SERVER_PATH);
260
261        if fs::metadata(&server_path).await.is_err() {
262            remove_matching(&container_dir, |entry| entry != destination_path).await;
263
264            let mut response = delegate
265                .http_client()
266                .get(&version.url, Default::default(), true)
267                .await
268                .map_err(|err| anyhow!("error downloading release: {}", err))?;
269            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
270            let archive = Archive::new(decompressed_bytes);
271            archive.unpack(&destination_path).await?;
272
273            let mut dir = fs::read_dir(&destination_path).await?;
274            let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
275            let repo_root = destination_path.join("vscode-eslint");
276            fs::rename(first.path(), &repo_root).await?;
277
278            self.node
279                .run_npm_subcommand(Some(&repo_root), "install", &[])
280                .await?;
281
282            self.node
283                .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
284                .await?;
285        }
286
287        Ok(LanguageServerBinary {
288            path: self.node.binary_path().await?,
289            arguments: eslint_server_binary_arguments(&server_path),
290        })
291    }
292
293    async fn cached_server_binary(
294        &self,
295        container_dir: PathBuf,
296        _: &dyn LspAdapterDelegate,
297    ) -> Option<LanguageServerBinary> {
298        get_cached_eslint_server_binary(container_dir, &*self.node).await
299    }
300
301    async fn installation_test_binary(
302        &self,
303        container_dir: PathBuf,
304    ) -> Option<LanguageServerBinary> {
305        get_cached_eslint_server_binary(container_dir, &*self.node).await
306    }
307
308    async fn label_for_completion(
309        &self,
310        _item: &lsp::CompletionItem,
311        _language: &Arc<language::Language>,
312    ) -> Option<language::CodeLabel> {
313        None
314    }
315
316    async fn initialization_options(&self) -> Option<serde_json::Value> {
317        None
318    }
319}
320
321async fn get_cached_eslint_server_binary(
322    container_dir: PathBuf,
323    node: &dyn NodeRuntime,
324) -> Option<LanguageServerBinary> {
325    (|| async move {
326        // This is unfortunate but we don't know what the version is to build a path directly
327        let mut dir = fs::read_dir(&container_dir).await?;
328        let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
329        if !first.file_type().await?.is_dir() {
330            return Err(anyhow!("First entry is not a directory"));
331        }
332        let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
333
334        Ok(LanguageServerBinary {
335            path: node.binary_path().await?,
336            arguments: eslint_server_binary_arguments(&server_path),
337        })
338    })()
339    .await
340    .log_err()
341}
342
343#[cfg(test)]
344mod tests {
345    use gpui::{Context, TestAppContext};
346    use unindent::Unindent;
347
348    #[gpui::test]
349    async fn test_outline(cx: &mut TestAppContext) {
350        let language = crate::languages::language(
351            "typescript",
352            tree_sitter_typescript::language_typescript(),
353            None,
354        )
355        .await;
356
357        let text = r#"
358            function a() {
359              // local variables are omitted
360              let a1 = 1;
361              // all functions are included
362              async function a2() {}
363            }
364            // top-level variables are included
365            let b: C
366            function getB() {}
367            // exported variables are included
368            export const d = e;
369        "#
370        .unindent();
371
372        let buffer = cx.build_model(|cx| {
373            language::Buffer::new(0, cx.entity_id().as_u64(), text).with_language(language, cx)
374        });
375        let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
376        assert_eq!(
377            outline
378                .items
379                .iter()
380                .map(|item| (item.text.as_str(), item.depth))
381                .collect::<Vec<_>>(),
382            &[
383                ("function a()", 0),
384                ("async function a2()", 1),
385                ("let b", 0),
386                ("function getB()", 0),
387                ("const d", 0),
388            ]
389        );
390    }
391}