1use anyhow::{anyhow, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use async_trait::async_trait;
5use collections::HashMap;
6use gpui::AppContext;
7use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
8use lsp::{CodeActionKind, LanguageServerBinary};
9use node_runtime::NodeRuntime;
10use project::project_settings::ProjectSettings;
11use serde_json::{json, Value};
12use settings::Settings;
13use smol::{fs, io::BufReader, stream::StreamExt};
14use std::{
15 any::Any,
16 ffi::OsString,
17 path::{Path, PathBuf},
18 sync::Arc,
19};
20use util::{
21 async_maybe,
22 fs::remove_matching,
23 github::{latest_github_release, GitHubLspBinaryVersion},
24 ResultExt,
25};
26
27fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
28 vec![server_path.into(), "--stdio".into()]
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 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 env: None,
103 arguments: typescript_server_binary_arguments(&server_path),
104 })
105 }
106
107 async fn cached_server_binary(
108 &self,
109 container_dir: PathBuf,
110 _: &dyn LspAdapterDelegate,
111 ) -> Option<LanguageServerBinary> {
112 get_cached_ts_server_binary(container_dir, &*self.node).await
113 }
114
115 async fn installation_test_binary(
116 &self,
117 container_dir: PathBuf,
118 ) -> Option<LanguageServerBinary> {
119 get_cached_ts_server_binary(container_dir, &*self.node).await
120 }
121
122 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
123 Some(vec![
124 CodeActionKind::QUICKFIX,
125 CodeActionKind::REFACTOR,
126 CodeActionKind::REFACTOR_EXTRACT,
127 CodeActionKind::SOURCE,
128 ])
129 }
130
131 async fn label_for_completion(
132 &self,
133 item: &lsp::CompletionItem,
134 language: &Arc<language::Language>,
135 ) -> Option<language::CodeLabel> {
136 use lsp::CompletionItemKind as Kind;
137 let len = item.label.len();
138 let grammar = language.grammar()?;
139 let highlight_id = match item.kind? {
140 Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
141 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
142 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
143 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
144 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
145 _ => None,
146 }?;
147
148 let text = match &item.detail {
149 Some(detail) => format!("{} {}", item.label, detail),
150 None => item.label.clone(),
151 };
152
153 Some(language::CodeLabel {
154 text,
155 runs: vec![(0..len, highlight_id)],
156 filter_range: 0..len,
157 })
158 }
159
160 fn initialization_options(&self) -> Option<serde_json::Value> {
161 Some(json!({
162 "provideFormatter": true,
163 "tsserver": {
164 "path": "node_modules/typescript/lib",
165 },
166 "preferences": {
167 "includeInlayParameterNameHints": "all",
168 "includeInlayParameterNameHintsWhenArgumentMatchesName": true,
169 "includeInlayFunctionParameterTypeHints": true,
170 "includeInlayVariableTypeHints": true,
171 "includeInlayVariableTypeHintsWhenTypeMatchesName": true,
172 "includeInlayPropertyDeclarationTypeHints": true,
173 "includeInlayFunctionLikeReturnTypeHints": true,
174 "includeInlayEnumMemberValueHints": true,
175 }
176 }))
177 }
178
179 fn language_ids(&self) -> HashMap<String, String> {
180 HashMap::from_iter([
181 ("TypeScript".into(), "typescript".into()),
182 ("JavaScript".into(), "javascript".into()),
183 ("TSX".into(), "typescriptreact".into()),
184 ])
185 }
186}
187
188async fn get_cached_ts_server_binary(
189 container_dir: PathBuf,
190 node: &dyn NodeRuntime,
191) -> Option<LanguageServerBinary> {
192 async_maybe!({
193 let old_server_path = container_dir.join(TypeScriptLspAdapter::OLD_SERVER_PATH);
194 let new_server_path = container_dir.join(TypeScriptLspAdapter::NEW_SERVER_PATH);
195 if new_server_path.exists() {
196 Ok(LanguageServerBinary {
197 path: node.binary_path().await?,
198 env: None,
199 arguments: typescript_server_binary_arguments(&new_server_path),
200 })
201 } else if old_server_path.exists() {
202 Ok(LanguageServerBinary {
203 path: node.binary_path().await?,
204 env: None,
205 arguments: typescript_server_binary_arguments(&old_server_path),
206 })
207 } else {
208 Err(anyhow!(
209 "missing executable in directory {:?}",
210 container_dir
211 ))
212 }
213 })
214 .await
215 .log_err()
216}
217
218pub struct EsLintLspAdapter {
219 node: Arc<dyn NodeRuntime>,
220}
221
222impl EsLintLspAdapter {
223 const SERVER_PATH: &'static str = "vscode-eslint/server/out/eslintServer.js";
224 const SERVER_NAME: &'static str = "eslint";
225
226 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
227 EsLintLspAdapter { node }
228 }
229}
230
231#[async_trait]
232impl LspAdapter for EsLintLspAdapter {
233 fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
234 let eslint_user_settings = ProjectSettings::get_global(cx)
235 .lsp
236 .get(Self::SERVER_NAME)
237 .and_then(|s| s.settings.clone())
238 .unwrap_or_default();
239
240 let mut code_action_on_save = json!({
241 // We enable this, but without also configuring `code_actions_on_format`
242 // in the Zed configuration, it doesn't have an effect.
243 "enable": true,
244 });
245
246 if let Some(code_action_settings) = eslint_user_settings
247 .get("codeActionOnSave")
248 .and_then(|settings| settings.as_object())
249 {
250 if let Some(enable) = code_action_settings.get("enable") {
251 code_action_on_save["enable"] = enable.clone();
252 }
253 if let Some(mode) = code_action_settings.get("mode") {
254 code_action_on_save["mode"] = mode.clone();
255 }
256 if let Some(rules) = code_action_settings.get("rules") {
257 code_action_on_save["rules"] = rules.clone();
258 }
259 }
260
261 json!({
262 "": {
263 "validate": "on",
264 "rulesCustomizations": [],
265 "run": "onType",
266 "nodePath": null,
267 "workingDirectory": {"mode": "auto"},
268 "workspaceFolder": {
269 "uri": workspace_root,
270 "name": workspace_root.file_name()
271 .unwrap_or_else(|| workspace_root.as_os_str()),
272 },
273 "problems": {},
274 "codeActionOnSave": code_action_on_save,
275 "experimental": {
276 "useFlatConfig": workspace_root.join("eslint.config.js").is_file(),
277 },
278 }
279 })
280 }
281
282 fn name(&self) -> LanguageServerName {
283 LanguageServerName(Self::SERVER_NAME.into())
284 }
285
286 fn short_name(&self) -> &'static str {
287 "eslint"
288 }
289
290 async fn fetch_latest_server_version(
291 &self,
292 delegate: &dyn LspAdapterDelegate,
293 ) -> Result<Box<dyn 'static + Send + Any>> {
294 // At the time of writing the latest vscode-eslint release was released in 2020 and requires
295 // special custom LSP protocol extensions be handled to fully initialize. Download the latest
296 // prerelease instead to sidestep this issue
297 let release = latest_github_release(
298 "microsoft/vscode-eslint",
299 false,
300 true,
301 delegate.http_client(),
302 )
303 .await?;
304 Ok(Box::new(GitHubLspBinaryVersion {
305 name: release.tag_name,
306 url: release.tarball_url,
307 }))
308 }
309
310 async fn fetch_server_binary(
311 &self,
312 version: Box<dyn 'static + Send + Any>,
313 container_dir: PathBuf,
314 delegate: &dyn LspAdapterDelegate,
315 ) -> Result<LanguageServerBinary> {
316 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
317 let destination_path = container_dir.join(format!("vscode-eslint-{}", version.name));
318 let server_path = destination_path.join(Self::SERVER_PATH);
319
320 if fs::metadata(&server_path).await.is_err() {
321 remove_matching(&container_dir, |entry| entry != destination_path).await;
322
323 let mut response = delegate
324 .http_client()
325 .get(&version.url, Default::default(), true)
326 .await
327 .map_err(|err| anyhow!("error downloading release: {}", err))?;
328 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
329 let archive = Archive::new(decompressed_bytes);
330 archive.unpack(&destination_path).await?;
331
332 let mut dir = fs::read_dir(&destination_path).await?;
333 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
334 let repo_root = destination_path.join("vscode-eslint");
335 fs::rename(first.path(), &repo_root).await?;
336
337 self.node
338 .run_npm_subcommand(Some(&repo_root), "install", &[])
339 .await?;
340
341 self.node
342 .run_npm_subcommand(Some(&repo_root), "run-script", &["compile"])
343 .await?;
344 }
345
346 Ok(LanguageServerBinary {
347 path: self.node.binary_path().await?,
348 env: None,
349 arguments: eslint_server_binary_arguments(&server_path),
350 })
351 }
352
353 async fn cached_server_binary(
354 &self,
355 container_dir: PathBuf,
356 _: &dyn LspAdapterDelegate,
357 ) -> Option<LanguageServerBinary> {
358 get_cached_eslint_server_binary(container_dir, &*self.node).await
359 }
360
361 async fn installation_test_binary(
362 &self,
363 container_dir: PathBuf,
364 ) -> Option<LanguageServerBinary> {
365 get_cached_eslint_server_binary(container_dir, &*self.node).await
366 }
367
368 async fn label_for_completion(
369 &self,
370 _item: &lsp::CompletionItem,
371 _language: &Arc<language::Language>,
372 ) -> Option<language::CodeLabel> {
373 None
374 }
375
376 fn initialization_options(&self) -> Option<serde_json::Value> {
377 None
378 }
379}
380
381async fn get_cached_eslint_server_binary(
382 container_dir: PathBuf,
383 node: &dyn NodeRuntime,
384) -> Option<LanguageServerBinary> {
385 async_maybe!({
386 // This is unfortunate but we don't know what the version is to build a path directly
387 let mut dir = fs::read_dir(&container_dir).await?;
388 let first = dir.next().await.ok_or(anyhow!("missing first file"))??;
389 if !first.file_type().await?.is_dir() {
390 return Err(anyhow!("First entry is not a directory"));
391 }
392 let server_path = first.path().join(EsLintLspAdapter::SERVER_PATH);
393
394 Ok(LanguageServerBinary {
395 path: node.binary_path().await?,
396 env: None,
397 arguments: eslint_server_binary_arguments(&server_path),
398 })
399 })
400 .await
401 .log_err()
402}
403
404#[cfg(test)]
405mod tests {
406 use gpui::{Context, TestAppContext};
407 use text::BufferId;
408 use unindent::Unindent;
409
410 #[gpui::test]
411 async fn test_outline(cx: &mut TestAppContext) {
412 let language = crate::language(
413 "typescript",
414 tree_sitter_typescript::language_typescript(),
415 None,
416 )
417 .await;
418
419 let text = r#"
420 function a() {
421 // local variables are omitted
422 let a1 = 1;
423 // all functions are included
424 async function a2() {}
425 }
426 // top-level variables are included
427 let b: C
428 function getB() {}
429 // exported variables are included
430 export const d = e;
431 "#
432 .unindent();
433
434 let buffer = cx.new_model(|cx| {
435 language::Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
436 .with_language(language, cx)
437 });
438 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
439 assert_eq!(
440 outline
441 .items
442 .iter()
443 .map(|item| (item.text.as_str(), item.depth))
444 .collect::<Vec<_>>(),
445 &[
446 ("function a()", 0),
447 ("async function a2()", 1),
448 ("let b", 0),
449 ("function getB()", 0),
450 ("const d", 0),
451 ]
452 );
453 }
454}