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