1use anyhow::Result;
2use async_trait::async_trait;
3use gpui::AppContext;
4use gpui::AsyncAppContext;
5use language::{ContextProvider, LanguageServerName, LspAdapter, LspAdapterDelegate};
6use lsp::LanguageServerBinary;
7use node_runtime::NodeRuntime;
8use project::project_settings::ProjectSettings;
9use serde_json::Value;
10use settings::Settings;
11use std::{
12 any::Any,
13 borrow::Cow,
14 ffi::OsString,
15 path::{Path, PathBuf},
16 sync::Arc,
17};
18use task::{TaskTemplate, TaskTemplates, VariableName};
19use util::ResultExt;
20
21const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
22
23fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
24 vec![server_path.into(), "--stdio".into()]
25}
26
27pub struct PythonLspAdapter {
28 node: Arc<dyn NodeRuntime>,
29}
30
31impl PythonLspAdapter {
32 const SERVER_NAME: &'static str = "pyright";
33
34 pub fn new(node: Arc<dyn NodeRuntime>) -> Self {
35 PythonLspAdapter { node }
36 }
37}
38
39#[async_trait(?Send)]
40impl LspAdapter for PythonLspAdapter {
41 fn name(&self) -> LanguageServerName {
42 LanguageServerName(Self::SERVER_NAME.into())
43 }
44
45 async fn fetch_latest_server_version(
46 &self,
47 _: &dyn LspAdapterDelegate,
48 ) -> Result<Box<dyn 'static + Any + Send>> {
49 Ok(Box::new(
50 self.node
51 .npm_package_latest_version(Self::SERVER_NAME)
52 .await?,
53 ) as Box<_>)
54 }
55
56 async fn fetch_server_binary(
57 &self,
58 latest_version: Box<dyn 'static + Send + Any>,
59 container_dir: PathBuf,
60 _: &dyn LspAdapterDelegate,
61 ) -> Result<LanguageServerBinary> {
62 let latest_version = latest_version.downcast::<String>().unwrap();
63 let server_path = container_dir.join(SERVER_PATH);
64 let package_name = Self::SERVER_NAME;
65
66 let should_install_language_server = self
67 .node
68 .should_install_npm_package(package_name, &server_path, &container_dir, &latest_version)
69 .await;
70
71 if should_install_language_server {
72 self.node
73 .npm_install_packages(&container_dir, &[(package_name, latest_version.as_str())])
74 .await?;
75 }
76
77 Ok(LanguageServerBinary {
78 path: self.node.binary_path().await?,
79 env: None,
80 arguments: server_binary_arguments(&server_path),
81 })
82 }
83
84 async fn cached_server_binary(
85 &self,
86 container_dir: PathBuf,
87 _: &dyn LspAdapterDelegate,
88 ) -> Option<LanguageServerBinary> {
89 get_cached_server_binary(container_dir, &*self.node).await
90 }
91
92 async fn installation_test_binary(
93 &self,
94 container_dir: PathBuf,
95 ) -> Option<LanguageServerBinary> {
96 get_cached_server_binary(container_dir, &*self.node).await
97 }
98
99 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
100 // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
101 // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
102 // and `name` is the symbol name itself.
103 //
104 // Because the symbol name is included, there generally are not ties when
105 // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
106 // into account. Here, we remove the symbol name from the sortText in order
107 // to allow our own fuzzy score to be used to break ties.
108 //
109 // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
110 for item in items {
111 let Some(sort_text) = &mut item.sort_text else {
112 continue;
113 };
114 let mut parts = sort_text.split('.');
115 let Some(first) = parts.next() else { continue };
116 let Some(second) = parts.next() else { continue };
117 let Some(_) = parts.next() else { continue };
118 sort_text.replace_range(first.len() + second.len() + 1.., "");
119 }
120 }
121
122 async fn label_for_completion(
123 &self,
124 item: &lsp::CompletionItem,
125 language: &Arc<language::Language>,
126 ) -> Option<language::CodeLabel> {
127 let label = &item.label;
128 let grammar = language.grammar()?;
129 let highlight_id = match item.kind? {
130 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
131 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
132 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
133 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
134 _ => return None,
135 };
136 Some(language::CodeLabel {
137 text: label.clone(),
138 runs: vec![(0..label.len(), highlight_id)],
139 filter_range: 0..label.len(),
140 })
141 }
142
143 async fn label_for_symbol(
144 &self,
145 name: &str,
146 kind: lsp::SymbolKind,
147 language: &Arc<language::Language>,
148 ) -> Option<language::CodeLabel> {
149 let (text, filter_range, display_range) = match kind {
150 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
151 let text = format!("def {}():\n", name);
152 let filter_range = 4..4 + name.len();
153 let display_range = 0..filter_range.end;
154 (text, filter_range, display_range)
155 }
156 lsp::SymbolKind::CLASS => {
157 let text = format!("class {}:", name);
158 let filter_range = 6..6 + name.len();
159 let display_range = 0..filter_range.end;
160 (text, filter_range, display_range)
161 }
162 lsp::SymbolKind::CONSTANT => {
163 let text = format!("{} = 0", name);
164 let filter_range = 0..name.len();
165 let display_range = 0..filter_range.end;
166 (text, filter_range, display_range)
167 }
168 _ => return None,
169 };
170
171 Some(language::CodeLabel {
172 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
173 text: text[display_range].to_string(),
174 filter_range,
175 })
176 }
177
178 async fn workspace_configuration(
179 self: Arc<Self>,
180 _: &Arc<dyn LspAdapterDelegate>,
181 cx: &mut AsyncAppContext,
182 ) -> Result<Value> {
183 cx.update(|cx| {
184 ProjectSettings::get_global(cx)
185 .lsp
186 .get(Self::SERVER_NAME)
187 .and_then(|s| s.settings.clone())
188 .unwrap_or_default()
189 })
190 }
191}
192
193async fn get_cached_server_binary(
194 container_dir: PathBuf,
195 node: &dyn NodeRuntime,
196) -> Option<LanguageServerBinary> {
197 let server_path = container_dir.join(SERVER_PATH);
198 if server_path.exists() {
199 Some(LanguageServerBinary {
200 path: node.binary_path().await.log_err()?,
201 env: None,
202 arguments: server_binary_arguments(&server_path),
203 })
204 } else {
205 log::error!("missing executable in directory {:?}", server_path);
206 None
207 }
208}
209
210pub(crate) struct PythonContextProvider;
211
212const PYTHON_UNITTEST_TARGET_TASK_VARIABLE: VariableName =
213 VariableName::Custom(Cow::Borrowed("PYTHON_UNITTEST_TARGET"));
214
215impl ContextProvider for PythonContextProvider {
216 fn build_context(
217 &self,
218 variables: &task::TaskVariables,
219 _location: &project::Location,
220 _cx: &mut gpui::AppContext,
221 ) -> Result<task::TaskVariables> {
222 let python_module_name = python_module_name_from_relative_path(
223 variables.get(&VariableName::RelativeFile).unwrap_or(""),
224 );
225 let unittest_class_name =
226 variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
227 let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
228 "_unittest_method_name",
229 )));
230
231 let unittest_target_str = match (unittest_class_name, unittest_method_name) {
232 (Some(class_name), Some(method_name)) => {
233 format!("{}.{}.{}", python_module_name, class_name, method_name)
234 }
235 (Some(class_name), None) => format!("{}.{}", python_module_name, class_name),
236 (None, None) => python_module_name,
237 (None, Some(_)) => return Ok(task::TaskVariables::default()), // should never happen, a TestCase class is the unit of testing
238 };
239
240 let unittest_target = (
241 PYTHON_UNITTEST_TARGET_TASK_VARIABLE.clone(),
242 unittest_target_str,
243 );
244
245 Ok(task::TaskVariables::from_iter([unittest_target]))
246 }
247
248 fn associated_tasks(
249 &self,
250 _: Option<Arc<dyn language::File>>,
251 _: &AppContext,
252 ) -> Option<TaskTemplates> {
253 Some(TaskTemplates(vec![
254 TaskTemplate {
255 label: "execute selection".to_owned(),
256 command: "python3".to_owned(),
257 args: vec!["-c".to_owned(), VariableName::SelectedText.template_value()],
258 ..TaskTemplate::default()
259 },
260 TaskTemplate {
261 label: format!("run '{}'", VariableName::File.template_value()),
262 command: "python3".to_owned(),
263 args: vec![VariableName::File.template_value()],
264 ..TaskTemplate::default()
265 },
266 TaskTemplate {
267 label: format!("unittest '{}'", VariableName::File.template_value()),
268 command: "python3".to_owned(),
269 args: vec![
270 "-m".to_owned(),
271 "unittest".to_owned(),
272 VariableName::File.template_value(),
273 ],
274 ..TaskTemplate::default()
275 },
276 TaskTemplate {
277 label: "unittest $ZED_CUSTOM_PYTHON_UNITTEST_TARGET".to_owned(),
278 command: "python3".to_owned(),
279 args: vec![
280 "-m".to_owned(),
281 "unittest".to_owned(),
282 "$ZED_CUSTOM_PYTHON_UNITTEST_TARGET".to_owned(),
283 ],
284 tags: vec![
285 "python-unittest-class".to_owned(),
286 "python-unittest-method".to_owned(),
287 ],
288 ..TaskTemplate::default()
289 },
290 ]))
291 }
292}
293
294fn python_module_name_from_relative_path(relative_path: &str) -> String {
295 let path_with_dots = relative_path.replace('/', ".");
296 path_with_dots
297 .strip_suffix(".py")
298 .unwrap_or(&path_with_dots)
299 .to_string()
300}
301
302#[cfg(test)]
303mod tests {
304 use gpui::{BorrowAppContext, Context, ModelContext, TestAppContext};
305 use language::{language_settings::AllLanguageSettings, AutoindentMode, Buffer};
306 use settings::SettingsStore;
307 use std::num::NonZeroU32;
308
309 #[gpui::test]
310 async fn test_python_autoindent(cx: &mut TestAppContext) {
311 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
312 let language = crate::language("python", tree_sitter_python::language());
313 cx.update(|cx| {
314 let test_settings = SettingsStore::test(cx);
315 cx.set_global(test_settings);
316 language::init(cx);
317 cx.update_global::<SettingsStore, _>(|store, cx| {
318 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
319 s.defaults.tab_size = NonZeroU32::new(2);
320 });
321 });
322 });
323
324 cx.new_model(|cx| {
325 let mut buffer = Buffer::local("", cx).with_language(language, cx);
326 let append = |buffer: &mut Buffer, text: &str, cx: &mut ModelContext<Buffer>| {
327 let ix = buffer.len();
328 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
329 };
330
331 // indent after "def():"
332 append(&mut buffer, "def a():\n", cx);
333 assert_eq!(buffer.text(), "def a():\n ");
334
335 // preserve indent after blank line
336 append(&mut buffer, "\n ", cx);
337 assert_eq!(buffer.text(), "def a():\n \n ");
338
339 // indent after "if"
340 append(&mut buffer, "if a:\n ", cx);
341 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
342
343 // preserve indent after statement
344 append(&mut buffer, "b()\n", cx);
345 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
346
347 // preserve indent after statement
348 append(&mut buffer, "else", cx);
349 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
350
351 // dedent "else""
352 append(&mut buffer, ":", cx);
353 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
354
355 // indent lines after else
356 append(&mut buffer, "\n", cx);
357 assert_eq!(
358 buffer.text(),
359 "def a():\n \n if a:\n b()\n else:\n "
360 );
361
362 // indent after an open paren. the closing paren is not indented
363 // because there is another token before it on the same line.
364 append(&mut buffer, "foo(\n1)", cx);
365 assert_eq!(
366 buffer.text(),
367 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
368 );
369
370 // dedent the closing paren if it is shifted to the beginning of the line
371 let argument_ix = buffer.text().find('1').unwrap();
372 buffer.edit(
373 [(argument_ix..argument_ix + 1, "")],
374 Some(AutoindentMode::EachLine),
375 cx,
376 );
377 assert_eq!(
378 buffer.text(),
379 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
380 );
381
382 // preserve indent after the close paren
383 append(&mut buffer, "\n", cx);
384 assert_eq!(
385 buffer.text(),
386 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
387 );
388
389 // manually outdent the last line
390 let end_whitespace_ix = buffer.len() - 4;
391 buffer.edit(
392 [(end_whitespace_ix..buffer.len(), "")],
393 Some(AutoindentMode::EachLine),
394 cx,
395 );
396 assert_eq!(
397 buffer.text(),
398 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
399 );
400
401 // preserve the newly reduced indentation on the next newline
402 append(&mut buffer, "\n", cx);
403 assert_eq!(
404 buffer.text(),
405 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
406 );
407
408 // reset to a simple if statement
409 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
410
411 // dedent "else" on the line after a closing paren
412 append(&mut buffer, "\n else:\n", cx);
413 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n ");
414
415 buffer
416 });
417 }
418}