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: NodeRuntime,
 30}
 31
 32impl PythonLspAdapter {
 33    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
 34
 35    pub fn new(node: 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 process_completions(&self, items: &mut [lsp::CompletionItem]) {
101        // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
102        // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
103        // and `name` is the symbol name itself.
104        //
105        // Because the symbol name is included, there generally are not ties when
106        // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
107        // into account. Here, we remove the symbol name from the sortText in order
108        // to allow our own fuzzy score to be used to break ties.
109        //
110        // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
111        for item in items {
112            let Some(sort_text) = &mut item.sort_text else {
113                continue;
114            };
115            let mut parts = sort_text.split('.');
116            let Some(first) = parts.next() else { continue };
117            let Some(second) = parts.next() else { continue };
118            let Some(_) = parts.next() else { continue };
119            sort_text.replace_range(first.len() + second.len() + 1.., "");
120        }
121    }
122
123    async fn label_for_completion(
124        &self,
125        item: &lsp::CompletionItem,
126        language: &Arc<language::Language>,
127    ) -> Option<language::CodeLabel> {
128        let label = &item.label;
129        let grammar = language.grammar()?;
130        let highlight_id = match item.kind? {
131            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
132            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
133            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
134            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
135            _ => return None,
136        };
137        Some(language::CodeLabel {
138            text: label.clone(),
139            runs: vec![(0..label.len(), highlight_id)],
140            filter_range: 0..label.len(),
141        })
142    }
143
144    async fn label_for_symbol(
145        &self,
146        name: &str,
147        kind: lsp::SymbolKind,
148        language: &Arc<language::Language>,
149    ) -> Option<language::CodeLabel> {
150        let (text, filter_range, display_range) = match kind {
151            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
152                let text = format!("def {}():\n", name);
153                let filter_range = 4..4 + name.len();
154                let display_range = 0..filter_range.end;
155                (text, filter_range, display_range)
156            }
157            lsp::SymbolKind::CLASS => {
158                let text = format!("class {}:", name);
159                let filter_range = 6..6 + name.len();
160                let display_range = 0..filter_range.end;
161                (text, filter_range, display_range)
162            }
163            lsp::SymbolKind::CONSTANT => {
164                let text = format!("{} = 0", name);
165                let filter_range = 0..name.len();
166                let display_range = 0..filter_range.end;
167                (text, filter_range, display_range)
168            }
169            _ => return None,
170        };
171
172        Some(language::CodeLabel {
173            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
174            text: text[display_range].to_string(),
175            filter_range,
176        })
177    }
178
179    async fn workspace_configuration(
180        self: Arc<Self>,
181        adapter: &Arc<dyn LspAdapterDelegate>,
182        cx: &mut AsyncAppContext,
183    ) -> Result<Value> {
184        cx.update(|cx| {
185            language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
186                .and_then(|s| s.settings.clone())
187                .unwrap_or_default()
188        })
189    }
190}
191
192async fn get_cached_server_binary(
193    container_dir: PathBuf,
194    node: &NodeRuntime,
195) -> Option<LanguageServerBinary> {
196    let server_path = container_dir.join(SERVER_PATH);
197    if server_path.exists() {
198        Some(LanguageServerBinary {
199            path: node.binary_path().await.log_err()?,
200            env: None,
201            arguments: server_binary_arguments(&server_path),
202        })
203    } else {
204        log::error!("missing executable in directory {:?}", server_path);
205        None
206    }
207}
208
209pub(crate) struct PythonContextProvider;
210
211const PYTHON_UNITTEST_TARGET_TASK_VARIABLE: VariableName =
212    VariableName::Custom(Cow::Borrowed("PYTHON_UNITTEST_TARGET"));
213
214impl ContextProvider for PythonContextProvider {
215    fn build_context(
216        &self,
217        variables: &task::TaskVariables,
218        _location: &project::Location,
219        _: Option<&HashMap<String, String>>,
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.into());
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}