1use anyhow::{anyhow, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use gpui::AsyncAppContext;
5use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
6use lsp::{CodeActionKind, LanguageServerBinary};
7use node_runtime::NodeRuntime;
8use project::project_settings::ProjectSettings;
9use serde_json::{json, Value};
10use settings::Settings;
11use std::{
12 any::Any,
13 ffi::OsString,
14 path::{Path, PathBuf},
15 sync::Arc,
16};
17use util::{maybe, ResultExt};
18
19fn typescript_server_binary_arguments(server_path: &Path) -> Vec<OsString> {
20 vec![server_path.into(), "--stdio".into()]
21}
22
23pub struct VtslsLspAdapter {
24 node: Arc<dyn NodeRuntime>,
25}
26
27impl VtslsLspAdapter {
28 const SERVER_PATH: &'static str = "node_modules/@vtsls/language-server/bin/vtsls.js";
29
30 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
31 VtslsLspAdapter { node }
32 }
33 async fn tsdk_path(adapter: &Arc<dyn LspAdapterDelegate>) -> &'static str {
34 let is_yarn = adapter
35 .read_text_file(PathBuf::from(".yarn/sdks/typescript/lib/typescript.js"))
36 .await
37 .is_ok();
38
39 if is_yarn {
40 ".yarn/sdks/typescript/lib"
41 } else {
42 "node_modules/typescript/lib"
43 }
44 }
45}
46
47struct TypeScriptVersions {
48 typescript_version: String,
49 server_version: String,
50}
51
52const SERVER_NAME: &'static str = "vtsls";
53#[async_trait(?Send)]
54impl LspAdapter for VtslsLspAdapter {
55 fn name(&self) -> LanguageServerName {
56 LanguageServerName(SERVER_NAME.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("@vtsls/language-server")
68 .await?,
69 }) as Box<_>)
70 }
71
72 async fn fetch_server_binary(
73 &self,
74 latest_version: Box<dyn 'static + Send + Any>,
75 container_dir: PathBuf,
76 _: &dyn LspAdapterDelegate,
77 ) -> Result<LanguageServerBinary> {
78 let latest_version = latest_version.downcast::<TypeScriptVersions>().unwrap();
79 let server_path = container_dir.join(Self::SERVER_PATH);
80 let package_name = "typescript";
81
82 let should_install_language_server = self
83 .node
84 .should_install_npm_package(
85 package_name,
86 &server_path,
87 &container_dir,
88 latest_version.typescript_version.as_str(),
89 )
90 .await;
91
92 if should_install_language_server {
93 self.node
94 .npm_install_packages(
95 &container_dir,
96 &[
97 (package_name, latest_version.typescript_version.as_str()),
98 (
99 "@vtsls/language-server",
100 latest_version.server_version.as_str(),
101 ),
102 ],
103 )
104 .await?;
105 }
106
107 Ok(LanguageServerBinary {
108 path: self.node.binary_path().await?,
109 env: None,
110 arguments: typescript_server_binary_arguments(&server_path),
111 })
112 }
113
114 async fn cached_server_binary(
115 &self,
116 container_dir: PathBuf,
117 _: &dyn LspAdapterDelegate,
118 ) -> Option<LanguageServerBinary> {
119 get_cached_ts_server_binary(container_dir, &*self.node).await
120 }
121
122 async fn installation_test_binary(
123 &self,
124 container_dir: PathBuf,
125 ) -> Option<LanguageServerBinary> {
126 get_cached_ts_server_binary(container_dir, &*self.node).await
127 }
128
129 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
130 Some(vec![
131 CodeActionKind::QUICKFIX,
132 CodeActionKind::REFACTOR,
133 CodeActionKind::REFACTOR_EXTRACT,
134 CodeActionKind::SOURCE,
135 ])
136 }
137
138 async fn label_for_completion(
139 &self,
140 item: &lsp::CompletionItem,
141 language: &Arc<language::Language>,
142 ) -> Option<language::CodeLabel> {
143 use lsp::CompletionItemKind as Kind;
144 let len = item.label.len();
145 let grammar = language.grammar()?;
146 let highlight_id = match item.kind? {
147 Kind::CLASS | Kind::INTERFACE | Kind::ENUM => grammar.highlight_id_for_name("type"),
148 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
149 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
150 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
151 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
152 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
153 _ => None,
154 }?;
155
156 let one_line = |s: &str| s.replace(" ", "").replace('\n', " ");
157
158 let text = if let Some(description) = item
159 .label_details
160 .as_ref()
161 .and_then(|label_details| label_details.description.as_ref())
162 {
163 format!("{} {}", item.label, one_line(description))
164 } else if let Some(detail) = &item.detail {
165 format!("{} {}", item.label, one_line(detail))
166 } else {
167 item.label.clone()
168 };
169
170 Some(language::CodeLabel {
171 text,
172 runs: vec![(0..len, highlight_id)],
173 filter_range: 0..len,
174 })
175 }
176
177 async fn initialization_options(
178 self: Arc<Self>,
179 adapter: &Arc<dyn LspAdapterDelegate>,
180 ) -> Result<Option<serde_json::Value>> {
181 let tsdk_path = Self::tsdk_path(&adapter).await;
182 Ok(Some(json!({
183 "typescript": {
184 "tsdk": tsdk_path,
185 "suggest": {
186 "completeFunctionCalls": true
187 },
188 "inlayHints": {
189 "parameterNames": {
190 "enabled": "all",
191 "suppressWhenArgumentMatchesName": false,
192 },
193 "parameterTypes": {
194 "enabled": true
195 },
196 "variableTypes": {
197 "enabled": true,
198 "suppressWhenTypeMatchesName": false,
199 },
200 "propertyDeclarationTypes": {
201 "enabled": true,
202 },
203 "functionLikeReturnTypes": {
204 "enabled": true,
205 },
206 "enumMemberValues": {
207 "enabled": true,
208 }
209 }
210 },
211 "javascript": {
212 "suggest": {
213 "completeFunctionCalls": true
214 }
215 },
216 "vtsls": {
217 "experimental": {
218 "completion": {
219 "enableServerSideFuzzyMatch": true,
220 "entriesLimit": 5000,
221 }
222 },
223 "autoUseWorkspaceTsdk": true
224 }
225 })))
226 }
227
228 async fn workspace_configuration(
229 self: Arc<Self>,
230 adapter: &Arc<dyn LspAdapterDelegate>,
231 cx: &mut AsyncAppContext,
232 ) -> Result<Value> {
233 let override_options = cx.update(|cx| {
234 ProjectSettings::get_global(cx)
235 .lsp
236 .get(SERVER_NAME)
237 .and_then(|s| s.initialization_options.clone())
238 })?;
239 if let Some(options) = override_options {
240 return Ok(options);
241 }
242 self.initialization_options(adapter)
243 .await
244 .map(|o| o.unwrap())
245 }
246
247 fn language_ids(&self) -> HashMap<String, String> {
248 HashMap::from_iter([
249 ("TypeScript".into(), "typescript".into()),
250 ("JavaScript".into(), "javascript".into()),
251 ("TSX".into(), "typescriptreact".into()),
252 ])
253 }
254}
255
256async fn get_cached_ts_server_binary(
257 container_dir: PathBuf,
258 node: &dyn NodeRuntime,
259) -> Option<LanguageServerBinary> {
260 maybe!(async {
261 let server_path = container_dir.join(VtslsLspAdapter::SERVER_PATH);
262 if server_path.exists() {
263 Ok(LanguageServerBinary {
264 path: node.binary_path().await?,
265 env: None,
266 arguments: typescript_server_binary_arguments(&server_path),
267 })
268 } else {
269 Err(anyhow!(
270 "missing executable in directory {:?}",
271 container_dir
272 ))
273 }
274 })
275 .await
276 .log_err()
277}