diff --git a/CHANGELOG.md b/CHANGELOG.md index 88e4748e2..f2cccb0b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - #937 Preserve non-ASCII argument expressions and default values when changing function signatures (@Jinyong-Li) - #826, #940 Keep star imports in other modules when inlining a function or method (@chinghar) - #948, #949 Don't treat string prefixes such as the `f` in `f"..."` as occurrences when renaming a variable named `f`, `b`, `u`, `rf`, etc. (@aliassar) +- #963 Take the body of `if typing.TYPE_CHECKING:` over its `else` branch when inferring assigned names (@marlon-costa-dc) # Release 1.15.1 diff --git a/rope/base/oi/soi.py b/rope/base/oi/soi.py index 090b10337..021112b53 100644 --- a/rope/base/oi/soi.py +++ b/rope/base/oi/soi.py @@ -6,7 +6,7 @@ """ import rope.base.builtins # Use full qualification for clarity. -from rope.base import arguments, evaluate, pynames, pyobjects, utils +from rope.base import arguments, ast, evaluate, pynames, pyobjects, utils from rope.base.oi.type_hinting.factory import get_type_hinting_factory _ignore_inferred = utils.ignore_exception(pyobjects.IsBeingInferredError) @@ -63,7 +63,10 @@ def _handle_first_parameter(pyobject, parameters): def infer_assigned_object(pyname): if not pyname.assignments: return + result = None for assignment in reversed(pyname.assignments): + if _in_type_checking_else(assignment, pyname.module): + continue result = _infer_assignment(assignment, pyname.module) if ( isinstance(result, rope.base.builtins.BuiltinUnknown) @@ -84,6 +87,73 @@ def infer_assigned_object(pyname): return result +def _in_type_checking_else(assignment, pymodule): + """Tell whether `assignment` is in the ``else`` of ``if TYPE_CHECKING:`` + + Static analysis assumes `typing.TYPE_CHECKING` is true (PEP 484), so + the ``else`` branch of such an ``if`` is never taken. + + """ + if not assignment.orelse_tests: + return False + decided = pymodule._type_checking_tests() + if decided.get() is None: + decided.set({}) + for test in assignment.orelse_tests: + if test not in decided.get(): + scope = pymodule.get_scope().get_inner_scope_for_line(test.lineno) + decided.get()[test] = _is_type_checking(scope, test) + if decided.get()[test]: + return True + return False + + +def _is_type_checking(scope, node): + """Tell whether `node` reads `typing.TYPE_CHECKING` + + Imports, attributes of imported modules and a name's single plain + assignment (like ``TYPE_CHECKING = typing.TYPE_CHECKING`` in + `typing_extensions`) are followed without inferring any object. The + constant is recognized as the ``TYPE_CHECKING`` attribute of the + module named `typing`, whatever its value. + + """ + pyname = _get_binding(scope, node) + followed = set() + while pyname is not None and pyname not in followed: + followed.add(pyname) + if isinstance(pyname, pynames.ImportedName): + pyname = pyname._get_imported_pyname() + continue + if not isinstance(pyname, pynames.AssignedName) or pyname.module is None: + return False + module = pyname.module + if ( + module.get_name() == "typing" + and module.get_attributes().get("TYPE_CHECKING") is pyname + ): + return True + if len(pyname.assignments) != 1: + return False + assignment = pyname.assignments[0] + if assignment.levels or assignment.evaluation: + return False + lineno = _get_lineno_for_node(assignment.ast_node) + scope = module.get_scope().get_inner_scope_for_line(lineno) + pyname = _get_binding(scope, assignment.ast_node) + return False + + +def _get_binding(scope, node): + if isinstance(node, ast.Name): + return scope.lookup(node.id) + if isinstance(node, ast.Attribute): + owner = _get_binding(scope, node.value) + if isinstance(owner, pynames.ImportedModule): + return owner.get_object().get_attributes().get(node.attr) + return None + + def get_passed_objects(pyfunction, parameter_index): object_info = pyfunction.pycore.object_info result = object_info.get_passed_objects(pyfunction, parameter_index) diff --git a/rope/base/pynames.py b/rope/base/pynames.py index 3febd2197..e9d0116f3 100644 --- a/rope/base/pynames.py +++ b/rope/base/pynames.py @@ -66,6 +66,9 @@ def __init__( The levels for for `a` is ``[0]``, for `b` is ``[1, 0]`` and for `c` is ``[1, 1]``. + `orelse_tests` holds the tests of the ``if`` statements whose + ``else`` branch contains this assignment. + """ self.ast_node = ast_node if levels is None: @@ -75,6 +78,7 @@ def __init__( self.evaluation = evaluation self.assign_type = assign_type self.type_hint = type_hint + self.orelse_tests = () def get_lineno(self): return self.ast_node.lineno diff --git a/rope/base/pyobjects.py b/rope/base/pyobjects.py index fbf1b34df..bc5c1b7b1 100644 --- a/rope/base/pyobjects.py +++ b/rope/base/pyobjects.py @@ -320,6 +320,14 @@ def _forget_concluded_data(self): for data in self.concluded_data: data._invalidate() + @utils.saveit + def _type_checking_tests(self): + """Branch tests of this module decided against `typing.TYPE_CHECKING` + + A decision reads other modules, so it is concluded data. + """ + return self._get_concluded_data() + def get_resource(self): return self.resource diff --git a/rope/base/pyobjectsdef.py b/rope/base/pyobjectsdef.py index 95bd15691..74791508a 100644 --- a/rope/base/pyobjectsdef.py +++ b/rope/base/pyobjectsdef.py @@ -405,6 +405,7 @@ def __init__(self, pycore, owner_object): self.owner_object = owner_object self.names = {} self.defineds = [] + self.orelse_tests = [] def get_module(self): if self.owner_object is not None: @@ -462,12 +463,22 @@ def _For(self, node): def _AsyncFor(self, node): return self._For(node) + def _If(self, node): + self.visit(node.test) + for child in node.body: + self.visit(child) + self.orelse_tests.append(node.test) + for child in node.orelse: + self.visit(child) + self.orelse_tests.pop() + def _assigned(self, name, assignment): pyname = self.names.get(name, None) if pyname is None: pyname = pynamesdef.AssignedName(module=self.get_module()) if isinstance(pyname, pynamesdef.AssignedName): if assignment is not None: + assignment.orelse_tests = tuple(self.orelse_tests) pyname.assignments.append(assignment) self.names[name] = pyname diff --git a/ropetest/pycoretest.py b/ropetest/pycoretest.py index 5ccd80d2a..8ee619c5c 100644 --- a/ropetest/pycoretest.py +++ b/ropetest/pycoretest.py @@ -255,6 +255,60 @@ def f(self): derived = mod["Derived"].get_object() self.assertTrue("f" in derived) + def _type_checking_module(self, guard_import, guard): + code = guard_import + "\n" + dedent(f"""\ + class Checked: + pass + class Runtime: + pass + if {guard}: + Alias = Checked + else: + Alias = Runtime + class Facade: + if {guard}: + Only = Checked + class Derived(Alias): + pass + """) + return libutils.get_string_module(self.project, code) + + def test_type_checking_body_is_taken_by_static_inference(self): + guards = ( + ("from typing import TYPE_CHECKING", "TYPE_CHECKING"), + ("import typing", "typing.TYPE_CHECKING"), + ("import typing as t", "t.TYPE_CHECKING"), + ("import typing\nTC = typing.TYPE_CHECKING", "TC"), + ) + for guard_import, guard in guards: + with self.subTest(guard=guard): + mod = self._type_checking_module(guard_import, guard) + checked = mod["Checked"].get_object() + self.assertEqual(checked, mod["Alias"].get_object()) + facade = mod["Facade"].get_object() + self.assertEqual(checked, facade["Only"].get_object()) + derived = mod["Derived"].get_object() + self.assertEqual([checked], derived.get_superclasses()) + + def test_other_branch_tests_stay_undecided(self): + guards = ( + ("from typing import TYPE_CHECKING", "not TYPE_CHECKING"), + ("import typing\nTC = typing.TYPE_CHECKING\nTC = False", "TC"), + ("TYPE_CHECKING = False", "TYPE_CHECKING"), + ) + for guard_import, guard in guards: + with self.subTest(guard=guard): + mod = self._type_checking_module(guard_import, guard) + runtime = mod["Runtime"].get_object() + self.assertEqual(runtime, mod["Alias"].get_object()) + + def test_type_checking_of_a_project_typing_module_is_taken(self): + testutils.create_module(self.project, "typing").write("TYPE_CHECKING = False\n") + mod = self._type_checking_module( + "from typing import TYPE_CHECKING", "TYPE_CHECKING" + ) + self.assertEqual(mod["Checked"].get_object(), mod["Alias"].get_object()) + def test_module_creation(self): new_module = testutils.create_module(self.project, "module") self.assertFalse(new_module.is_folder())