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