python.rs

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