Файли
openidea/crates/ide-language/src/syntax/python_mentions.rs
T
LU XIANGRUIтаwildcatDownstairs fa0783ab03 feat(python): search in comments and strings when renaming a symbol (#7679)
The Python Rename dialog offers Search in comments and strings (off by default, remembered; in-place rename follows it). Whole-word, case-sensitive matches in comments and string text are merged into the language server's workspace edit, so they preview, apply and undo with it; a rename that gains text matches is always previewed with the matches under Non-code usages, and applying fails if a matched file changed after the preview. Locals and parameters are searched in their function, other symbols in the project's .py / .pyi files including unsaved buffers; symlinks leading out of the project are skipped.

Refs #4968

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:23:45 +08:00

255 рядки
11 KiB
Rust
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
//! Python 重命名的 "Search in comments and strings":注释和字符串里的整词匹配,
//! 以及局部符号(参数、局部变量)只在所在函数内查找。紧邻中日文字符的名字(`调用load_user函数`)
//! 不算整词,与按标识符字符分词一致。
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use ide_core::Range;
use tree_sitter::Node;
impl Syntax {
/// Whole-word, case-sensitive occurrences of `name` in the comments and string literals of a
/// Python `text`; f-string interpolations are code and are left to the language server.
/// With `within` not empty, only those inside one of them.
pub fn python_mentions(&self, text: &str, name: &str, within: &[Range]) -> Vec<Range> {
self.analyze(&LanguageId::new("python"), text, |_, tree, text| {
let idx = LineIndex::new(text);
let mut out = Vec::new();
walk(tree.root_node(), &mut |node| {
if !matches!(node.kind(), "comment" | "string_content") {
return;
}
let escapes: Vec<(usize, usize)> = (0..node.child_count())
.filter_map(|i| node.child(i))
.filter(|c| c.kind() == "escape_sequence")
.map(|c| (c.start_byte(), c.end_byte()))
.collect();
// 组合符号(NFD 的 `é`)是单词的一部分。
let word = |c: char| {
c.is_alphanumeric()
|| c == '_'
|| matches!(c, '\u{300}'..='\u{36f}' | '\u{1ab0}'..='\u{1aff}' | '\u{1dc0}'..='\u{1dff}'
| '\u{20d0}'..='\u{20ff}' | '\u{fe20}'..='\u{fe2f}')
};
for (at, _) in text[node.start_byte()..node.end_byte()].match_indices(name) {
let (start, end) = (node.start_byte() + at, node.start_byte() + at + name.len());
// `"\n" + name`:转义序列算分隔符,落在转义序列里面的匹配不算。
if escapes.iter().any(|&(a, b)| start < b && a < end) {
continue;
}
let joined_before = !escapes.iter().any(|&(_, b)| b == start)
&& text[..start].chars().next_back().is_some_and(word);
if joined_before || text[end..].chars().next().is_some_and(word) {
continue;
}
let range = Range::new(idx.pos(start), idx.pos(end));
if within.is_empty() || within.iter().any(|w| w.start <= range.start && range.end <= w.end) {
out.push(range);
}
}
});
Some(out)
})
.unwrap_or_default()
}
/// The functions (or lambdas) a renamed symbol is local to, judging by the rename's `edits`
/// of this `text`; empty when it is visible outside one. `only_file`: no other file is edited.
/// A parameter belongs to its function even when callers name it as a keyword elsewhere; a
/// method's parameter renamed with its overrides belongs to each of them.
pub fn python_rename_scope(&self, text: &str, name: &str, edits: &[Range], only_file: bool) -> Vec<Range> {
self.analyze(&LanguageId::new("python"), text, |_, tree, text| {
let idx = LineIndex::new(text);
let mut nodes = Vec::new();
let mut global = false;
walk(tree.root_node(), &mut |node| {
if node.kind() == "identifier" && text[node.start_byte()..node.end_byte()] == *name {
let start = idx.pos(node.start_byte());
if edits.iter().any(|e| e.start == start) {
// 只有服务器一起改了的 `global v` 才说明改的是模块级变量。
global |= node.parent().is_some_and(|p| p.kind() == "global_statement");
nodes.push(node);
}
}
});
let range = |f: Node| Range::new(idx.pos(f.start_byte()), idx.pos(f.end_byte()));
let owners: Vec<Range> =
nodes.iter().filter(|n| is_parameter(**n)).filter_map(|n| enclosing_function(*n)).map(range).collect();
if !owners.is_empty() {
return Some(owners);
}
// 属性(`self.x`)在函数外可见;`global x` 指向模块级变量。
if !only_file || global || nodes.len() != edits.len() || nodes.iter().any(|n| is_attribute(*n)) {
return None;
}
let mut scope = enclosing_function(*nodes.first()?);
while let Some(f) = scope {
let inside = |n: &Node| {
f.start_byte() <= n.start_byte()
&& n.end_byte() <= f.end_byte()
&& f.child_by_field_name("name") != Some(*n)
};
if nodes.iter().all(inside) {
return Some(vec![range(f)]);
}
scope = enclosing_function(f);
}
None
})
.unwrap_or_default()
}
}
fn walk<'a>(root: Node<'a>, f: &mut impl FnMut(Node<'a>)) {
let mut cursor = root.walk();
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
while !cursor.goto_next_sibling() {
if !cursor.goto_parent() {
return;
}
}
}
}
fn enclosing_function(node: Node) -> Option<Node> {
std::iter::successors(node.parent(), Node::parent).find(|p| matches!(p.kind(), "function_definition" | "lambda"))
}
fn is_attribute(node: Node) -> bool {
node.parent().is_some_and(|p| p.kind() == "attribute" && p.child_by_field_name("attribute") == Some(node))
}
fn is_parameter(node: Node) -> bool {
let Some(parent) = node.parent() else { return false };
match parent.kind() {
"parameters" | "lambda_parameters" => true,
"default_parameter" | "typed_default_parameter" => parent.child_by_field_name("name") == Some(node),
"typed_parameter" => parent.named_child(0) == Some(node),
// `*args` / `**kw`
"list_splat_pattern" | "dictionary_splat_pattern" => {
parent.parent().is_some_and(|p| matches!(p.kind(), "parameters" | "lambda_parameters" | "typed_parameter"))
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::Pos;
/// 匹配处用 `[[…]]` 标出。
fn marked(text: &str, name: &str, within: &[Range]) -> String {
let mut lines: Vec<Vec<u16>> = text.split('\n').map(|l| l.encode_utf16().collect()).collect();
for r in Syntax::new().python_mentions(text, name, within).into_iter().rev() {
let line = &mut lines[r.start.line as usize];
line.splice(r.end.col as usize..r.end.col as usize, "]]".encode_utf16());
line.splice(r.start.col as usize..r.start.col as usize, "[[".encode_utf16());
}
lines.iter().map(|l| String::from_utf16_lossy(l)).collect::<Vec<_>>().join("\n")
}
fn check(name: &str, expected: &str) {
let text = expected.replace("[[", "").replace("]]", "");
assert_eq!(marked(&text, name, &[]), expected);
}
#[test]
fn comments_and_docstrings() {
check("load", "# [[load]](): [[load]], x.[[load]]; reload load_all Load load2\nload()\n");
check(
"load",
"def load():\n \"\"\"[[load]] things.\n\n >>> [[load]]()\n :func:`[[load]]`\n \"\"\"\n",
);
check("load", "x = 1 #[[load]]\n'''[[load]]'''\nb'[[load]]'\nu\"[[load]]\" '[[load]]'\n");
}
#[test]
fn f_string_interpolations_are_code() {
check("user", "f\"[[user]] {user} {user.name!r:>{user}} {{[[user]]}} [[user]]={user=}\"\n");
check("user", "f\"\"\"\n[[user]]: {user}\n\"\"\"\n");
// 插值里的字符串仍然是字符串。
check("user", "f\"{row['[[user]]']}\"\n");
}
#[test]
fn escapes_and_raw_strings() {
check("name", r#"x = "\n[[name]]\t[[name]] \"[[name]]\" \\[[name]]""#);
check("name", r#"x = r"\nname [[name]]""#);
check("x41", r#"x = "\x41 [[x41]]""#);
check("n", r#"x = "\n [[n]]""#);
}
#[test]
fn unicode_names_and_utf16_columns() {
check("café", "# 😀 [[café]] cafés 中café\ns = '😀[[café]]😀'\n");
check("数据", "# 加载 [[数据]]。数据库\n");
}
#[test]
fn syntax_errors_and_limits() {
check("a", "def f(:\n # [[a]]\n");
check("a", "a = 1\nprint(a.a)\n");
let within = Range::new(Pos::new(1, 0), Pos::new(1, 10));
assert_eq!(marked("# a\n# a\n# a", "a", &[within]), "# a\n# [[a]]\n# a");
}
/// `^` 标出服务器改名的位置。
fn scope(code: &str, name: &str, only_file: bool) -> Option<u32> {
let mut edits = Vec::new();
let mut text = String::new();
for (n, line) in code.split('\n').enumerate() {
let mut parts = line.split('^');
let mut out = parts.next().unwrap_or_default().to_owned();
for part in parts {
let col = out.encode_utf16().count() as u32;
edits.push(Range::new(Pos::new(n as u32, col), Pos::new(n as u32, col + name.len() as u32)));
out.push_str(part);
}
text.push_str(&out);
text.push('\n');
}
Syntax::new().python_rename_scope(&text, name, &edits, only_file).first().map(|r| r.start.line)
}
#[test]
fn locals_and_parameters_stay_in_their_function() {
assert_eq!(scope("def f():\n ^v = 1\n return ^v\n", "v", true), Some(0));
for p in ["^v", "^v=1", "^v: int", "^v: int = 1", "*^v", "**^v", "*^v: int"] {
assert_eq!(scope(&format!("\ndef f({p}):\n pass\n"), "v", false), Some(1), "{p}");
}
assert_eq!(scope("g = lambda ^v: ^v\n", "v", true), Some(0));
// 闭包:包含全部引用的那一层函数。
assert_eq!(scope("def f():\n ^v = 1\n def g():\n return ^v\n", "v", true), Some(0));
assert_eq!(scope("def f():\n def ^g():\n ^g()\n ^g()\n", "g", true), Some(0));
}
#[test]
fn review_repros() {
// #5:别处的 `global v` 不影响无关的局部变量。
assert_eq!(scope("def f():\n ^v = 1\n return ^v\ndef g():\n global v\n", "v", true), Some(0));
// #6:参数在多个函数里一起改名时每个函数都算。
let two = "def f(v):\n pass\ndef g(v):\n pass\n";
let edit = |line| Range::new(Pos::new(line, 6), Pos::new(line, 7));
assert_eq!(Syntax::new().python_rename_scope(two, "v", &[edit(0), edit(2)], true).len(), 2);
// NFD 的 café 不是 cafe。
check("cafe", "# cafe\u{301} [[cafe]]\n");
}
#[test]
fn module_level_names_attributes_and_globals_are_project_wide() {
assert_eq!(scope("def ^f():\n ^f()\n", "f", true), None);
assert_eq!(scope("^v = 1\ndef f():\n return ^v\n", "v", true), None);
assert_eq!(scope("def f(self):\n self.^v = 1\n", "v", true), None);
assert_eq!(scope("def f():\n global ^v\n ^v = 1\n", "v", true), None);
assert_eq!(scope("def f():\n ^v()\n", "v", false), None);
assert_eq!(scope("class C:\n def ^m(self):\n pass\n", "m", true), None);
// 参数默认值不是参数名。
assert_eq!(scope("^v = 1\ndef f(a=^v):\n pass\n", "v", true), None);
}
}