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