Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ jobs:
- name: Install pytest for the host suite
run: python -m pip install --disable-pip-version-check pytest
- name: Verify Python highlighting, run configurations, and dependencies on Lithe 0.8.9
run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(PinnedInterpreter)?|ManualRunAndDependencies)$'
run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride|PinnedInterpreter)?|ManualRunAndDependencies)$'
- name: Run the full Python host suite on the pinned desktop
env:
GOFLAGS: -tags=vivahead
Expand Down
18 changes: 10 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,22 @@ Pyrefly 和 debugpy 随插件包分发,Python 解释器、pytest、uv、conda

## 设置

**插件设置**(「语言与框架 › Python」,也在 设置 → 插件 → Python Support →「设置」),都立即生效:
**插件设置**(「语言与框架 › Python」,也在 设置 → 插件 → Python Support →「设置」),除覆盖路径外都立即生效:

| 设置 | 默认 | 说明 |
| --- | --- | --- |
| 类型检查模式 | 默认 | Pyrefly 的预设:默认、自动、关闭、基础、宽松、严格、全部。项目有 `pyrefly.toml` 或 `[tool.pyrefly]` 时以项目配置为准;“自动”沿用附近的 mypy 或 Pyright 配置,没有时按“基础” |
| 隐藏类型错误 | 关 | 所有文件都不显示类型错误,包括有自己 Pyrefly 配置的项目;悬停、跳转、补全照常。开启后类型检查模式选什么都不显示类型错误 |
| 显示类型错误 | 始终开启 | 在哪些文件里显示类型错误:始终开启(没有 Pyrefly 配置的文件按类型检查模式)、仅已配置项目(只在 `pyrefly.toml` 或 `[tool.pyrefly]` 覆盖的文件里)、仅报告缺失导入、关闭(所有文件都不显示,包括有自己 Pyrefly 配置的项目)。Pyrefly 已经没有只报缺失导入的模式,所以“仅报告缺失导入”让没有 Pyrefly 配置的文件按“基础”检查:报告无法解析的导入和少数 Pyrefly 确定的错误。悬停、跳转、补全在各档都照常 |
| 诊断范围 | 仅打开的文件 | 或者“整个工作区”:没打开的文件也报告错误级别的问题 |
| 自动导入补全 | 开 | 补全列出还没导入的名字,确认时插入 `import` |
| 自动导入路径风格 | 绝对导入 | 插入导入时用完整模块路径还是包内相对路径。也用于“移动符号”“转换模块”代码操作;关闭自动导入补全后只有这两个操作用它 |
| 补全函数括号 | 关 | 补全函数或方法时加上 `()`,光标停在括号里 |
| Python 解释器覆盖路径 | 空 | 填一个 Python 可执行文件后,构建任务、运行和 pytest 都用它,不再按下文的顺序查找;Pyrefly 分析和调试仍用查找到的解释器。修改后重新加载项目生效 |

## Python 解释器

Pyrefly 分析代码、运行、测试、调试、读取依赖、安装依赖都用同一个解释器。Lithe 按这个顺序找:
Pyrefly 分析代码、运行、测试、调试、读取依赖、安装依赖都用同一个解释器,除非设置了“Python 解释器覆盖路径”:那时构建任务、运行和
pytest 用覆盖路径,Pyrefly 和调试仍用下面找到的解释器。Lithe 按这个顺序找:

1. **项目环境**:为项目固定的解释器;项目里的 `.venv`、`venv`、`.conda`(项目要先被信任);项目的 `.python-version` 和
`pyproject.toml` 的 `requires-python` 决定选哪个版本。
Expand All @@ -63,17 +65,17 @@ Python,固定也不行。受影响的有:
在此之前请把环境建在项目里:`python3 -m venv .venv` 或 `uv venv`;Poetry 先运行 `poetry config virtualenvs.in-project true`,
Pipenv 设置 `PIPENV_VENV_IN_PROJECT=1`。也可以固定 uv、pyenv、python.org 装的基础解释器,但那里没有环境里装的包。

1.0.0 的“Python 解释器覆盖”设置在 1.1.0 删除了:它只管运行,Pyrefly 却用工具链里的解释器,两边可能不一致。原来填过的路径不再生效,请在工具链页固定它。
项目外的环境暂时也可以填进“Python 解释器覆盖路径”,让运行和 pytest 先用上它。

## 设置预览

两块预览由插件后端按界面语言、外观和设置窗口宽度画出。它们用示例代码,不读取打开的项目;截图里的路径和版本是测试数据。

**语言与框架 › Python**:顶部是当前用的 Python 解释器。下面四张卡片各对应一项设置:
**语言与框架 › Python**:顶部是当前用的 Python 解释器;设置了覆盖路径时,下面多一行说明哪些流程改用它。下面四张卡片各对应一项设置:

| 卡片 | 画出什么 |
| --- | --- |
| 类型检查模式 | 示例代码在所选预设下报告哪些错误;隐藏类型错误开启时标为“已隐藏” |
| 类型检查模式 | 示例代码在所选预设下报告哪些错误;示例没有 Pyrefly 配置,“显示类型错误”不是始终开启时,卡片按它画出实际效果 |
| 诊断范围 | 一个小项目里哪些文件会被检查 |
| 自动导入补全 | 补全列出未导入的 `greet`,确认后按绝对或相对路径插入导入;关闭时只补全已导入的名字 |
| 补全函数括号 | 确认补全后是 `greet()` 还是 `greet` |
Expand All @@ -84,7 +86,7 @@ Pipenv 设置 `PIPENV_VENV_IN_PROJECT=1`。也可以固定 uv、pyenv、python.o

<img src="docs/assets/settings-previews/language-en-draft-light.png" alt="还没应用的修改先显示在预览里,英文浅色外观" width="720">

**构建工具 › Python**:画出上面三步查找顺序,以及解释器用在哪些流程。这一页没有设置项,换解释器要到工具链页。
**构建工具 › Python**:先画覆盖路径(有没有设置、设置后谁用它),再画上面三步查找顺序,以及查找到的解释器用在哪些流程。这一页没有设置项,换解释器要到工具链页。

<img src="docs/assets/settings-previews/build-tools-zh-Hans-dark.png" alt="构建工具 › Python 画出 Lithe 查找 Python 解释器的顺序,深色外观" width="720">

Expand Down Expand Up @@ -165,7 +167,7 @@ export LITHE_TEST_PYTHON_PLUGIN_ARCHIVE="$PWD/dist/python-support-1.1.0-darwin-a
PYTEST_PYTHON=/path/to/python3.12 node scripts/e2e-host.mjs
# 用同一个包检查 0.8.9:高亮、当前文件运行、固定解释器、手动运行
PYTEST_PYTHON=/path/to/python3.12 node scripts/e2e-host.mjs --ref desktop-v0.8.9 \
--run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(PinnedInterpreter)?|ManualRunAndDependencies)$'
--run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride|PinnedInterpreter)?|ManualRunAndDependencies)$'
```

插件包路径要写绝对路径。脚本把宿主检出到 `.artifacts/lithe-host`,复制 `e2e/host/desktop/` 下的测试后运行;`--source`、`--ref`、`--run`
Expand Down
1 change: 1 addition & 0 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod discovery;
mod inspect;
mod pyrefly;
mod requirements;
mod type_errors;
mod view;

use lithe_plugin_sdk::Backend;
Expand Down
17 changes: 15 additions & 2 deletions backend/src/pyrefly.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Produces the packaged Pyrefly launch and its settings using the host's interpreter hint.

use crate::type_errors::Display;
use lithe_plugin_sdk::{Context, FunctionError, PluginError};
use serde_json::{json, Value};
use std::collections::VecDeque;
Expand Down Expand Up @@ -31,10 +32,22 @@ impl LaunchResolver {
let settings = &params["settings"];
let diagnostic_mode =
enum_setting(settings, "diagnosticMode", &["openFilesOnly", "workspace"]);
let preset = enum_setting(
settings,
"typeCheckingMode",
&["default", "auto", "off", "basic", "legacy", "strict", "all"],
);
let display = Display::parse(enum_setting(
settings,
"displayTypeErrors",
&Display::VALUES,
))
.expect("a declared value parses");
let (preset, disabled) = display.pyrefly(preset);
let mut python = json!({
"pyrefly": {
"typeCheckingMode": enum_setting(settings, "typeCheckingMode", &["default", "auto", "off", "basic", "legacy", "strict", "all"]),
"disableTypeErrors": settings["disableTypeErrors"].as_bool().unwrap_or(false),
"typeCheckingMode": preset,
"disableTypeErrors": disabled,
"diagnosticMode": diagnostic_mode,
},
"analysis": {
Expand Down
74 changes: 74 additions & 0 deletions backend/src/type_errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! The `displayTypeErrors` setting, and the Pyrefly settings it stands for.
//!
//! Pyrefly 1.4.1, the version `vendor-lock.json` packages, deprecates
//! `python.pyrefly.displayTypeErrors` for `typeCheckingMode` and
//! `disableTypeErrors`, and the new settings win whenever both are sent. The
//! plugin always sends `typeCheckingMode`, so passing the old value on would
//! leave only `force-off` in effect. The plugin keeps its four choices and
//! sends Pyrefly the pair that does what each choice's title says instead.

/// Where type errors appear: the `displayTypeErrors` setting.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Display {
/// `force-on`: every file, files without a Pyrefly config by the preset.
AlwaysOn,
/// `default`: only files a `pyrefly.toml` or `[tool.pyrefly]` covers.
ConfiguredOnly,
/// `error-missing-imports`. Pyrefly 0.64 removed this mode, so files
/// without a Pyrefly config are checked with the `basic` preset, which
/// reports unresolved imports and a few errors Pyrefly is sure of.
MissingImports,
/// `force-off`: no file, whatever its own Pyrefly config says.
Off,
}

impl Display {
/// The declared option values, the default first.
pub const VALUES: [&'static str; 4] =
["force-on", "default", "error-missing-imports", "force-off"];

pub fn parse(value: &str) -> Option<Self> {
Some(match value {
"force-on" => Display::AlwaysOn,
"default" => Display::ConfiguredOnly,
"error-missing-imports" => Display::MissingImports,
"force-off" => Display::Off,
_ => return None,
})
}

/// The `typeCheckingMode` and `disableTypeErrors` Pyrefly gets, where
/// `preset` is the `typeCheckingMode` setting. A preset reaches only the
/// files no Pyrefly config covers; a configured project keeps its own.
pub fn pyrefly(self, preset: &str) -> (&str, bool) {
match self {
Display::AlwaysOn => (preset, false),
Display::ConfiguredOnly => ("off", false),
Display::MissingImports => ("basic", false),
Display::Off => (preset, true),
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn every_declared_value_parses_and_nothing_else_does() {
for value in Display::VALUES {
assert!(Display::parse(value).is_some(), "{value}");
}
for value in ["", "on", "Force-On", "disable"] {
assert_eq!(Display::parse(value), None, "{value}");
}
}

#[test]
fn each_choice_sends_the_settings_that_do_what_its_title_says() {
assert_eq!(Display::AlwaysOn.pyrefly("strict"), ("strict", false));
assert_eq!(Display::ConfiguredOnly.pyrefly("strict"), ("off", false));
assert_eq!(Display::MissingImports.pyrefly("strict"), ("basic", false));
assert_eq!(Display::Off.pyrefly("strict"), ("strict", true));
}
}
52 changes: 34 additions & 18 deletions backend/src/view/language.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use super::scene::{
code, column, group, pair, path, pill, rect, runs, squiggle, text, text_width, token, Node,
CAPTION, STRONG,
};
use super::settings::{ImportFormat, Mode, Scope, Settings};
use super::settings::{Display, ImportFormat, Mode, Scope, Settings};
use super::words::Words;
use serde_json::{json, Value};

Expand All @@ -32,7 +32,7 @@ pub const TOOLS: [&str; 1] = ["python"];
/// The settings the cards show; a draft of any of them marks the preview.
pub const SETTINGS: [&str; 6] = [
"typeCheckingMode",
"disableTypeErrors",
"displayTypeErrors",
"diagnosticMode",
"autoImportCompletions",
"importFormat",
Expand Down Expand Up @@ -139,12 +139,21 @@ struct Card<'a> {
preview: Vec<Node>,
}

/// The region's nodes: the interpreter row, then the preview.
/// The region's nodes: the interpreter row, then the preview. While the
/// override path is set, a banner under the row says which commands use it
/// instead.
pub fn view(settings: &Settings, words: &Words, width: Option<f64>) -> Vec<Value> {
let tools: Vec<Value> = TOOLS
let mut tools: Vec<Value> = TOOLS
.iter()
.map(|tool| json!({ "type": "tool", "tool": tool }))
.collect();
if let Some(path) = &settings.interpreter_override {
tools.push(json!({
"type": "banner",
"text": (words.override_banner)(path),
"tone": "accent",
}));
}
vec![
json!({
"type": "section",
Expand Down Expand Up @@ -174,15 +183,20 @@ fn mode_index(mode: Mode) -> usize {
/// order the cards stand.
fn values<'a>(settings: &Settings, words: &'a Words) -> [(&'a str, bool, &'a str); 4] {
let switch = |on: bool| if on { words.on } else { words.off };
let mode = if settings.hide_type_errors {
(words.hidden, false, words.hidden_note)
} else {
let index = mode_index(settings.mode);
(
words.modes[index],
settings.mode != Mode::Off,
words.mode_notes[index],
)
let display =
|index: usize, lit: bool| (words.displays[index], lit, words.display_notes[index]);
let mode = match settings.display {
Display::AlwaysOn => {
let index = mode_index(settings.mode);
(
words.modes[index],
settings.mode != Mode::Off,
words.mode_notes[index],
)
}
Display::ConfiguredOnly => display(0, false),
Display::MissingImports => display(1, true),
Display::Off => display(2, false),
};
let scope = match settings.scope {
Scope::OpenFiles => (words.scope_open, false, words.scope_open_note),
Expand Down Expand Up @@ -235,7 +249,10 @@ pub fn canvas(settings: &Settings, words: &Words, width: Option<f64>) -> Value {
value: mode.0,
lit: mode.1,
note: mode.2,
changed: settings.any_changed(&["typeCheckingMode", "disableTypeErrors"]),
// The preset decides this card only while type errors are always on.
changed: settings.is_changed("displayTypeErrors")
|| (settings.display == Display::AlwaysOn
&& settings.is_changed("typeCheckingMode")),
preview: type_check_preview(settings.reporting(), words, box_w),
},
Card {
Expand Down Expand Up @@ -435,7 +452,7 @@ fn reported(mode: Mode) -> (usize, Option<usize>) {

/// A function missing an annotation, a call with a string for a float, and a
/// misspelled name, in a box `box_w` wide; under it what the preset in force
/// reports. Nothing is reported while type errors are hidden or off.
/// reports. Nothing is reported while the preset is off or type errors are.
fn type_check_preview(reporting: Option<Mode>, words: &Words, box_w: f64) -> Vec<Node> {
let mut nodes = numbered(vec![
vec![
Expand Down Expand Up @@ -708,7 +725,7 @@ mod tests {
let mut pairs: Vec<(&str, &str)> = w
.modes
.iter()
.chain([&w.hidden])
.chain(&w.displays)
.map(|value| (w.mode_title, *value))
.collect();
pairs.extend([w.scope_open, w.scope_workspace].map(|value| (w.scope_title, value)));
Expand All @@ -734,8 +751,7 @@ mod tests {
fn every_note_fits_the_narrowest_card() {
for language in ["en", "zh-Hans"] {
let w = words::for_language(language);
let notes = w.mode_notes.iter().copied().chain([
w.hidden_note,
let notes = w.mode_notes.iter().chain(&w.display_notes).copied().chain([
w.scope_open_note,
w.scope_workspace_note,
w.import_absolute_note,
Expand Down
Loading
Loading