From c9c498348174b38ce35bfe001353c8ebea262802 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 10 Jul 2021 23:48:57 +0200 Subject: Fix issues when inferring match variables (#1093) * Fix issues when inferring match variables * Fix extract_node for MatchCase * Typing improvements * Fix pylint issues (no-name-in-module) * Use PY310_PLUS instead of sys.version_info --- ChangeLog | 6 ++++ astroid/builder.py | 2 +- astroid/node_classes.py | 39 ++++++++++++++++++++++--- astroid/protocols.py | 61 +++++++++++++++++++++++++++++++++++++++ astroid/rebuilder.py | 12 ++++---- tests/unittest_protocols.py | 70 ++++++++++++++++++++++++++++++++++++++++++++- 6 files changed, 178 insertions(+), 12 deletions(-) diff --git a/ChangeLog b/ChangeLog index fadf89b3..98110ede 100644 --- a/ChangeLog +++ b/ChangeLog @@ -16,6 +16,11 @@ Release date: TBA Closes PyCQA/pylint#4671 +* Fix issues when inferring match variables + + Closes PyCQA/pylint#4685 + + What's New in astroid 2.6.2? ============================ Release date: 2021-06-30 @@ -30,6 +35,7 @@ Release date: 2021-06-30 Closes PyCQA/pylint#4631 Closes #1080 + What's New in astroid 2.6.1? ============================ Release date: 2021-06-29 diff --git a/astroid/builder.py b/astroid/builder.py index a3fc9d4e..2513904b 100644 --- a/astroid/builder.py +++ b/astroid/builder.py @@ -334,7 +334,7 @@ def _find_statement_by_line(node, line): can be found. :rtype: astroid.bases.NodeNG or None """ - if isinstance(node, (nodes.ClassDef, nodes.FunctionDef)): + if isinstance(node, (nodes.ClassDef, nodes.FunctionDef, nodes.MatchCase)): # This is an inaccuracy in the AST: the nodes that can be # decorated do not carry explicit information on which line # the actual definition (class/def), but .fromline seems to diff --git a/astroid/node_classes.py b/astroid/node_classes.py index 7cb5799f..9dca85d9 100644 --- a/astroid/node_classes.py +++ b/astroid/node_classes.py @@ -36,10 +36,11 @@ import abc import itertools import pprint +import sys import typing from functools import lru_cache from functools import singledispatch as _singledispatch -from typing import ClassVar, Optional +from typing import Callable, ClassVar, Generator, Optional from astroid import as_string, bases from astroid import context as contextmod @@ -55,10 +56,10 @@ from astroid.exceptions import ( ) from astroid.manager import AstroidManager -try: +if sys.version_info >= (3, 8): + # pylint: disable=no-name-in-module from typing import Literal -except ImportError: - # typing.Literal was added in Python 3.8 +else: from typing_extensions import Literal @@ -5026,6 +5027,16 @@ class MatchMapping(mixins.AssignTypeMixin, Pattern): self.patterns = patterns self.rest = rest + assigned_stmts: Callable[ + [ + "MatchMapping", + AssignName, + Optional[contextmod.InferenceContext], + Literal[None], + ], + Generator[NodeNG, None, None], + ] + class MatchClass(Pattern): """Class representing a :class:`ast.MatchClass` node. @@ -5098,6 +5109,16 @@ class MatchStar(mixins.AssignTypeMixin, Pattern): def postinit(self, *, name: Optional[AssignName]) -> None: self.name = name + assigned_stmts: Callable[ + [ + "MatchStar", + AssignName, + Optional[contextmod.InferenceContext], + Literal[None], + ], + Generator[NodeNG, None, None], + ] + class MatchAs(mixins.AssignTypeMixin, Pattern): """Class representing a :class:`ast.MatchAs` node. @@ -5144,6 +5165,16 @@ class MatchAs(mixins.AssignTypeMixin, Pattern): self.pattern = pattern self.name = name + assigned_stmts: Callable[ + [ + "MatchAs", + AssignName, + Optional[contextmod.InferenceContext], + Literal[None], + ], + Generator[NodeNG, None, None], + ] + class MatchOr(Pattern): """Class representing a :class:`ast.MatchOr` node. diff --git a/astroid/protocols.py b/astroid/protocols.py index f2ffe6b3..228000ab 100644 --- a/astroid/protocols.py +++ b/astroid/protocols.py @@ -28,6 +28,8 @@ where it makes sense. import collections import itertools import operator as operator_mod +import sys +from typing import Generator, Optional from astroid import arguments, bases from astroid import context as contextmod @@ -41,6 +43,12 @@ from astroid.exceptions import ( NoDefault, ) +if sys.version_info >= (3, 8): + # pylint: disable=no-name-in-module + from typing import Literal +else: + from typing_extensions import Literal + raw_building = util.lazy_import("raw_building") objects = util.lazy_import("objects") @@ -785,3 +793,56 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None): nodes.Starred.assigned_stmts = starred_assigned_stmts + + +@decorators.yes_if_nothing_inferred +def match_mapping_assigned_stmts( + self: nodes.MatchMapping, + node: nodes.AssignName, + context: Optional[contextmod.InferenceContext] = None, + assign_path: Literal[None] = None, +) -> Generator[nodes.NodeNG, None, None]: + """Return empty generator (return -> raises StopIteration) so inferred value + is Uninferable. + """ + return + yield # pylint: disable=unreachable + + +nodes.MatchMapping.assigned_stmts = match_mapping_assigned_stmts + + +@decorators.yes_if_nothing_inferred +def match_star_assigned_stmts( + self: nodes.MatchStar, + node: nodes.AssignName, + context: Optional[contextmod.InferenceContext] = None, + assign_path: Literal[None] = None, +) -> Generator[nodes.NodeNG, None, None]: + """Return empty generator (return -> raises StopIteration) so inferred value + is Uninferable. + """ + return + yield # pylint: disable=unreachable + + +nodes.MatchStar.assigned_stmts = match_star_assigned_stmts + + +@decorators.yes_if_nothing_inferred +def match_as_assigned_stmts( + self: nodes.MatchAs, + node: nodes.AssignName, + context: Optional[contextmod.InferenceContext] = None, + assign_path: Literal[None] = None, +) -> Generator[nodes.NodeNG, None, None]: + """Infer MatchAs as the Match subject if it's the only MatchCase pattern + else raise StopIteration to yield Uninferable. + """ + if isinstance(self.parent, nodes.MatchCase) and isinstance( + self.parent.parent, nodes.Match + ): + yield self.parent.parent.subject + + +nodes.MatchAs.assigned_stmts = match_as_assigned_stmts diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py index 59ceac77..e53b427a 100644 --- a/astroid/rebuilder.py +++ b/astroid/rebuilder.py @@ -45,18 +45,18 @@ from typing import ( overload, ) -try: - from typing import Final -except ImportError: - # typing.Final was added in Python 3.8 - from typing_extensions import Final - from astroid import node_classes, nodes from astroid._ast import ParserModule, get_parser_module, parse_function_type_comment from astroid.const import PY37_PLUS, PY38_PLUS, PY39_PLUS, Context from astroid.manager import AstroidManager from astroid.node_classes import NodeNG +if sys.version_info >= (3, 8): + # pylint: disable=no-name-in-module + from typing import Final +else: + from typing_extensions import Final + if TYPE_CHECKING: import ast diff --git a/tests/unittest_protocols.py b/tests/unittest_protocols.py index 246cf1d9..e130b570 100644 --- a/tests/unittest_protocols.py +++ b/tests/unittest_protocols.py @@ -19,7 +19,7 @@ import pytest import astroid from astroid import extract_node, nodes, util -from astroid.const import PY38_PLUS +from astroid.const import PY38_PLUS, PY310_PLUS from astroid.exceptions import InferenceError from astroid.node_classes import AssignName, Const, Name, Starred @@ -266,5 +266,73 @@ def test_named_expr_inference(): assert node.value == 1 +@pytest.mark.skipif(not PY310_PLUS, reason="Match requires python 3.10") +def test_assigned_stmts_match_mapping(): + """Assigned_stmts for MatchMapping not yet implemented. + + Test the result is 'Uninferable' and no exception is raised. + """ + assign_stmts = extract_node( + """ + var = {1: "Hello", 2: "World"} + match var: + case {**rest}: #@ + pass + """ + ) + match_mapping: nodes.MatchMapping = assign_stmts.pattern # type: ignore + assert match_mapping.rest + assigned = next(match_mapping.rest.assigned_stmts()) + assert assigned == util.Uninferable + + +@pytest.mark.skipif(not PY310_PLUS, reason="Match requires python 3.10") +def test_assigned_stmts_match_star(): + """Assigned_stmts for MatchStar not yet implemented. + + Test the result is 'Uninferable' and no exception is raised. + """ + assign_stmts = extract_node( + """ + var = (0, 1, 2) + match var: + case (0, 1, *rest): #@ + pass + """ + ) + match_sequence: nodes.MatchSequence = assign_stmts.pattern # type: ignore + match_star = match_sequence.patterns[2] + assert isinstance(match_star, nodes.MatchStar) and match_star.name + assigned = next(match_star.name.assigned_stmts()) + assert assigned == util.Uninferable + + +@pytest.mark.skipif(not PY310_PLUS, reason="Match requires python 3.10") +def test_assigned_stmts_match_as(): + """Assigned_stmts for MatchAs only implemented for the most basic case (y).""" + assign_stmts = extract_node( + """ + var = 42 + match var: #@ + case 2 | x: #@ + pass + case y: #@ + pass + """ + ) + subject: nodes.Const = assign_stmts[0].subject # type: ignore + match_or: nodes.MatchOr = assign_stmts[1].pattern # type: ignore + match_as: nodes.MatchAs = assign_stmts[2].pattern # type: ignore + + assert match_as.name + assigned_match_as = next(match_as.name.assigned_stmts()) + assert assigned_match_as == subject + + match_or_1 = match_or.patterns[1] + assert isinstance(match_or_1, nodes.MatchAs) and match_or_1.name + assigned_match_or_1 = next(match_or_1.name.assigned_stmts()) + assert assigned_match_or_1 == util.Uninferable + + if __name__ == "__main__": unittest.main() -- cgit v1.2.1