diff --git a/changelog.d/965.md b/changelog.d/965.md new file mode 100644 index 000000000..0814fdcf3 --- /dev/null +++ b/changelog.d/965.md @@ -0,0 +1,5 @@ +- #965 Clean up star-list handling, autoimport parsing and worder naming, + and fix same-package import filtering in autoimport: comparing + `package_name` with `is` instead of `==` meant same-package imports + were not recognised as such, so they leaked into autoimport results + instead of being skipped. (@Ketankhunti) diff --git a/rope/base/worder.py b/rope/base/worder.py index 97ea8d405..11261ba9f 100644 --- a/rope/base/worder.py +++ b/rope/base/worder.py @@ -33,7 +33,7 @@ def __init__(self, code, handle_ignores=False): def _init_ignores(self): ignores = rope.base.simplify.ignored_regions(self.code) - self.dumb_finder = _RealFinder(self.code, self.code) + self.fallback_finder = _RealFinder(self.code, self.code) self.starts = [ignored[0] for ignored in ignores] self.ends = [ignored[1] for ignored in ignores] @@ -43,7 +43,7 @@ def _context_call(self, name, offset): self._init_ignores() start = bisect.bisect(self.starts, offset) if start > 0 and offset < self.ends[start - 1]: - return getattr(self.dumb_finder, name)(offset) + return getattr(self.fallback_finder, name)(offset) return getattr(self.code_finder, name)(offset) def get_primary_at(self, offset): diff --git a/rope/contrib/autoimport/parse.py b/rope/contrib/autoimport/parse.py index d468fe90b..cd71d1580 100644 --- a/rope/contrib/autoimport/parse.py +++ b/rope/contrib/autoimport/parse.py @@ -26,14 +26,18 @@ logger = logging.getLogger(__name__) +_NODE_TYPE_MAP = ( + (ast.ClassDef, NameType.Class), + (ast.FunctionDef, NameType.Function), + (ast.Assign, NameType.Variable), +) + + def get_type_ast(node: ast.AST) -> NameType: """Get the lsp type of a node.""" - if isinstance(node, ast.ClassDef): - return NameType.Class - if isinstance(node, ast.FunctionDef): - return NameType.Function - if isinstance(node, ast.Assign): - return NameType.Variable + for node_type, name_type in _NODE_TYPE_MAP: + if isinstance(node, node_type): + return name_type return NameType.Variable # default value @@ -69,21 +73,25 @@ def get_names_from_file( get_type_ast(node), ) elif process_imports and isinstance(node, ast.ImportFrom): - # When we process imports, we want to include names in it's own package. - if node.level == 0: - continue - if not node.module or package_name is node.module.split(".")[0]: - continue - for name in node.names: - if isinstance(name, ast.alias): - if name.asname: - real_name = name.asname - else: - real_name = name.name - else: - real_name = name - if underlined or not real_name.startswith("_"): - yield PartialName(real_name, get_type_ast(node)) + yield from _names_from_importfrom(node, package_name, underlined) + + +def _names_from_importfrom( + node: ast.ImportFrom, + package_name: str, + underlined: bool, +) -> Generator[PartialName, None, None]: + """Yield re-exported names from a relative from-import.""" + # When we process imports, we want to include names in it's own package. + if node.level == 0: + return + if not node.module or package_name == node.module.split(".")[0]: + return + for name in node.names: + if isinstance(name, ast.alias): + real_name = name.asname if name.asname else name.name + if underlined or not real_name.startswith("_"): + yield PartialName(real_name, get_type_ast(node)) def get_type_object(imported_object) -> NameType: diff --git a/rope/refactor/importutils/module_imports.py b/rope/refactor/importutils/module_imports.py index f35b22521..fb61cf8ce 100644 --- a/rope/refactor/importutils/module_imports.py +++ b/rope/refactor/importutils/module_imports.py @@ -4,6 +4,21 @@ from rope.refactor.importutils import actions, importinfo +def _resolve_assigned_names( + name: Union[pynamesdef.AssignedName, pynames.ImportedName], +) -> List: + """Follow import aliases to the underlying assigned names.""" + while isinstance(name, pynames.ImportedName): + try: + name = name.imported_module.get_object().get_attribute( + name.imported_name, + ) + except exceptions.AttributeNotFoundError: + return [] + assert isinstance(name, pynamesdef.AssignedName) + return name.assignments + + class ModuleImports: def __init__(self, project, pymodule, import_filter=None): self.project = project @@ -30,19 +45,6 @@ def _get_unbound_names(self, defined_pyobject): return visitor.unbound def _get_all_star_list(self, pymodule): - def _resolve_name( - name: Union[pynamesdef.AssignedName, pynames.ImportedName], - ) -> List: - while isinstance(name, pynames.ImportedName): - try: - name = name.imported_module.get_object().get_attribute( - name.imported_name, - ) - except exceptions.AttributeNotFoundError: - return [] - assert isinstance(name, pynamesdef.AssignedName) - return name.assignments - result = set() try: all_star_list = pymodule.get_attribute("__all__") @@ -50,7 +52,7 @@ def _resolve_name( return result assignments = [ - assignment.ast_node for assignment in _resolve_name(all_star_list) + assignment.ast_node for assignment in _resolve_assigned_names(all_star_list) ] # FIXME: Need a better way to recursively infer possible values. @@ -69,22 +71,23 @@ def _resolve_name( elif isinstance(el, ast.Starred): assignments.append(el.value) else: - if isinstance(el, ast.Constant) and isinstance(el.value, str): + is_str_constant = isinstance(el, ast.Constant) and isinstance( + el.value, str + ) + is_name_ref = isinstance(el, ast.Name) + if is_str_constant: result.add(el.value) - elif isinstance(el, ast.Name): + elif is_name_ref: try: name = pymodule.get_attribute(el.id) except exceptions.AttributeNotFoundError: continue else: - for av in _resolve_name(name): - if isinstance( - av.ast_node, - ast.Constant, - ) and isinstance( - av.ast_node.value, - str, - ): + for av in _resolve_assigned_names(name): + is_str_assignment = isinstance( + av.ast_node, ast.Constant + ) and isinstance(av.ast_node.value, str) + if is_str_assignment: result.add(av.ast_node.value) elif isinstance(assignment, ast.Name): try: @@ -93,7 +96,8 @@ def _resolve_name( continue else: assignments.extend( - assignment.ast_node for assignment in _resolve_name(name) + assignment.ast_node + for assignment in _resolve_assigned_names(name) ) elif isinstance(assignment, ast.BinOp): assignments.append(assignment.left) diff --git a/ropetest/contrib/autoimport/parsetest.py b/ropetest/contrib/autoimport/parsetest.py index cbc9a16e4..deb140ab3 100644 --- a/ropetest/contrib/autoimport/parsetest.py +++ b/ropetest/contrib/autoimport/parsetest.py @@ -1,5 +1,7 @@ import logging +import pytest + from rope.contrib.autoimport import parse from rope.contrib.autoimport.defs import Name, NameType, PartialName, Source @@ -28,3 +30,70 @@ def test_find_sys(): def test_find_underlined(): names = list(parse.get_names_from_compiled("os", Source.BUILTIN, underlined=True)) assert Name("_exit", "os", "os", Source.BUILTIN, NameType.Function) in names + + +@pytest.mark.parametrize( + ("source_text", "expected"), + [ + ("from .sub import helper\n", "helper"), + ("from .sub import helper as h\n", "h"), + ], +) +def test_names_from_relative_import(tmp_path, source_text, expected): + source = tmp_path / "mod.py" + source.write_text(source_text, encoding="utf-8") + names = list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + assert PartialName(expected, NameType.Variable) in names + + +@pytest.mark.parametrize( + ("source_text", "package_name"), + [ + ("from os import path\n", "pkg"), # absolute import: level == 0 + ("from . import helper\n", "pkg"), # bare relative: no module + # Same package: guards the == fix in _names_from_importfrom. + # A plain "pkg" literal is enough here, since + # node.module.split(".")[0] always creates a new string object. + ("from .pkg import thing\n", "pkg"), + ], +) +def test_import_is_skipped(tmp_path, source_text, package_name): + source = tmp_path / "mod.py" + source.write_text(source_text, encoding="utf-8") + assert ( + list( + parse.get_names_from_file( + source, package_name=package_name, process_imports=True + ) + ) + == [] + ) + + +def test_underlined_import_name_is_skipped_by_default(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from .sub import _private\n", encoding="utf-8") + assert ( + list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True + ) + ) + == [] + ) + names = list( + parse.get_names_from_file( + source, package_name="pkg", process_imports=True, underlined=True + ) + ) + assert PartialName("_private", NameType.Variable) in names + + +def test_imports_ignored_without_process_imports(tmp_path): + source = tmp_path / "mod.py" + source.write_text("from . import helper\n", encoding="utf-8") + assert list(parse.get_names_from_file(source, package_name="pkg")) == []