-
-
Notifications
You must be signed in to change notification settings - Fork 293
Support "is None" constraints from if statements during inference #1189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Pierre-Sassoulas
merged 27 commits into
pylint-dev:main
from
david-yz-liu:constraint-checking
Jan 6, 2023
Merged
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
159af87
Support "is None" constraints from if statements during inference
david-yz-liu 1c5b4b3
Merge branch 'main' into constraint-checking
Pierre-Sassoulas 4dffa4d
Merge branch 'main' of https://github.com/PyCQA/astroid into constrai…
DanielNoord 4828797
Changes
DanielNoord c39baff
Some typing
DanielNoord b54d841
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] de4c318
Some changes to typing and removal of dead code
DanielNoord 3da1c83
Fix on python 3.7
DanielNoord 7fe82e6
Fix import
DanielNoord fc4156e
Add abstractness
DanielNoord 55bb33f
Update ChangeLog
Pierre-Sassoulas 8a3b443
Simplify expression NoneConstraint.match
david-yz-liu 5b86d5a
Merge remote-tracking branch 'upstream/main' into constraint-checking
david-yz-liu e032c0b
move constraint.py into submodule, and small fixes
david-yz-liu c1268a2
Fix imports and __all__
david-yz-liu 7d0b6b2
Fix Union usage in type definition
david-yz-liu f963723
Add __future__ import to unittest_constraint.py
david-yz-liu 21e4cf9
Merge remote-tracking branch 'upstream/main' into constraint-checking
david-yz-liu 65c3c55
Updates based on review
david-yz-liu f6e001b
Use Self
DanielNoord 5da24fe
Use InferenceResult
DanielNoord b46f001
Don't check None is
DanielNoord 409543b
Use frozenset
DanielNoord 316ba46
Also accept Proxy
DanielNoord dabf0e9
Use an Iterator
DanielNoord f70fbad
Merge branch 'main' into constraint-checking
Pierre-Sassoulas 46c056f
Merge remote-tracking branch 'origin/main' into constraint-checking
Pierre-Sassoulas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html | ||
cdce8p marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE | ||
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt | ||
|
||
"""Classes representing different types of constraints on inference values.""" | ||
from __future__ import annotations | ||
|
||
import sys | ||
from abc import ABC, abstractmethod | ||
from collections.abc import Iterator | ||
from typing import Union | ||
|
||
from astroid import bases, nodes, util | ||
from astroid.typing import InferenceResult | ||
|
||
if sys.version_info >= (3, 11): | ||
from typing import Self | ||
else: | ||
from typing_extensions import Self | ||
|
||
_NameNodes = Union[nodes.AssignAttr, nodes.Attribute, nodes.AssignName, nodes.Name] | ||
|
||
|
||
class Constraint(ABC): | ||
"""Represents a single constraint on a variable.""" | ||
|
||
def __init__(self, node: nodes.NodeNG, negate: bool) -> None: | ||
self.node = node | ||
"""The node that this constraint applies to.""" | ||
self.negate = negate | ||
"""True if this constraint is negated. E.g., "is not" instead of "is".""" | ||
|
||
@classmethod | ||
@abstractmethod | ||
def match( | ||
cls: type[Self], node: _NameNodes, expr: nodes.NodeNG, negate: bool = False | ||
) -> Self | None: | ||
"""Return a new constraint for node matched from expr, if expr matches | ||
the constraint pattern. | ||
|
||
If negate is True, negate the constraint. | ||
""" | ||
|
||
@abstractmethod | ||
def satisfied_by(self, inferred: InferenceResult) -> bool: | ||
"""Return True if this constraint is satisfied by the given inferred value.""" | ||
|
||
|
||
class NoneConstraint(Constraint): | ||
"""Represents an "is None" or "is not None" constraint.""" | ||
|
||
CONST_NONE: nodes.Const = nodes.Const(None) | ||
|
||
@classmethod | ||
def match( | ||
cls: type[Self], node: _NameNodes, expr: nodes.NodeNG, negate: bool = False | ||
) -> Self | None: | ||
"""Return a new constraint for node matched from expr, if expr matches | ||
the constraint pattern. | ||
|
||
Negate the constraint based on the value of negate. | ||
""" | ||
if isinstance(expr, nodes.Compare) and len(expr.ops) == 1: | ||
left = expr.left | ||
op, right = expr.ops[0] | ||
if op in {"is", "is not"} and ( | ||
_matches(left, node) and _matches(right, cls.CONST_NONE) | ||
): | ||
negate = (op == "is" and negate) or (op == "is not" and not negate) | ||
return cls(node=node, negate=negate) | ||
|
||
return None | ||
|
||
def satisfied_by(self, inferred: InferenceResult) -> bool: | ||
"""Return True if this constraint is satisfied by the given inferred value.""" | ||
# Assume true if uninferable | ||
if inferred is util.Uninferable: | ||
return True | ||
|
||
# Return the XOR of self.negate and matches(inferred, self.CONST_NONE) | ||
return self.negate ^ _matches(inferred, self.CONST_NONE) | ||
|
||
|
||
def get_constraints( | ||
expr: _NameNodes, frame: nodes.LocalsDictNodeNG | ||
) -> dict[nodes.If, set[Constraint]]: | ||
"""Returns the constraints for the given expression. | ||
|
||
The returned dictionary maps the node where the constraint was generated to the | ||
corresponding constraint(s). | ||
|
||
Constraints are computed statically by analysing the code surrounding expr. | ||
Currently this only supports constraints generated from if conditions. | ||
""" | ||
current_node: nodes.NodeNG | None = expr | ||
constraints_mapping: dict[nodes.If, set[Constraint]] = {} | ||
while current_node is not None and current_node is not frame: | ||
parent = current_node.parent | ||
if isinstance(parent, nodes.If): | ||
branch, _ = parent.locate_child(current_node) | ||
constraints: set[Constraint] | None = None | ||
if branch == "body": | ||
constraints = set(_match_constraint(expr, parent.test)) | ||
elif branch == "orelse": | ||
constraints = set(_match_constraint(expr, parent.test, invert=True)) | ||
|
||
if constraints: | ||
constraints_mapping[parent] = constraints | ||
current_node = parent | ||
|
||
return constraints_mapping | ||
|
||
|
||
ALL_CONSTRAINT_CLASSES = frozenset((NoneConstraint,)) | ||
"""All supported constraint types.""" | ||
|
||
|
||
def _matches(node1: nodes.NodeNG | bases.Proxy, node2: nodes.NodeNG) -> bool: | ||
"""Returns True if the two nodes match.""" | ||
if isinstance(node1, nodes.Name) and isinstance(node2, nodes.Name): | ||
return node1.name == node2.name | ||
if isinstance(node1, nodes.Attribute) and isinstance(node2, nodes.Attribute): | ||
return node1.attrname == node2.attrname and _matches(node1.expr, node2.expr) | ||
if isinstance(node1, nodes.Const) and isinstance(node2, nodes.Const): | ||
return node1.value == node2.value | ||
|
||
return False | ||
|
||
|
||
def _match_constraint( | ||
node: _NameNodes, expr: nodes.NodeNG, invert: bool = False | ||
) -> Iterator[Constraint]: | ||
"""Yields all constraint patterns for node that match.""" | ||
for constraint_cls in ALL_CONSTRAINT_CLASSES: | ||
constraint = constraint_cls.match(node, expr, invert) | ||
if constraint: | ||
yield constraint |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.