Skip to content

Make infer_condition_value recognize the whole truth table #1

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 23, 2025

Fixes python#18901.

Side question: why don't we support boolean literals there (as in if True or sys.platform == "linux")? Is it an escape hatch to make mypy check some {platform,version}-dependent code on all {platform,version}s?

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of logical negation and binary logical expressions in condition evaluation, resulting in more accurate detection of unreachable code.
  • Tests

    • Added test cases for conditional expressions involving platform checks, logical operators, and negations to verify correct unreachable code detection and type inference.

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

Diff from mypy_primer, showing the effect of this PR on open source code:

vision (https://github.com/pytorch/vision)
+ torchvision/utils.py:271: error: Unused "type: ignore" comment  [unused-ignore]

aiohttp (https://github.com/aio-libs/aiohttp)
+ aiohttp/client.py:400:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:400:9: note: See https://mypy.rtfd.io/en/stable/_refs.html#code-empty-body for more info
+ aiohttp/client.py:1092:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1098:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1104:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1110:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1116:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1122:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1128:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1383:5: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:353:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:357:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:363:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:369:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:375:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:381:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:387:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:393:9: error: Missing return statement  [empty-body]

1 similar comment
@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

Diff from mypy_primer, showing the effect of this PR on open source code:

vision (https://github.com/pytorch/vision)
+ torchvision/utils.py:271: error: Unused "type: ignore" comment  [unused-ignore]

aiohttp (https://github.com/aio-libs/aiohttp)
+ aiohttp/client.py:400:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:400:9: note: See https://mypy.rtfd.io/en/stable/_refs.html#code-empty-body for more info
+ aiohttp/client.py:1092:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1098:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1104:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1110:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1116:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1122:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1128:9: error: Missing return statement  [empty-body]
+ aiohttp/client.py:1383:5: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:353:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:357:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:363:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:369:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:375:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:381:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:387:9: error: Missing return statement  [empty-body]
+ aiohttp/test_utils.py:393:9: error: Missing return statement  [empty-body]

@arvi18
Copy link
Author

arvi18 commented Apr 23, 2025

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Copy link

coderabbitai bot commented Apr 23, 2025

"""

Walkthrough

The changes update the logic in the infer_condition_value function within mypy/reachability.py to improve how logical negations and binary logical operators (and, or) are handled when inferring the truth value of expressions. The function now processes negations recursively and evaluates both operands for binary logical operators, applying more comprehensive rules to determine the resulting truth value. Additionally, new test cases are added to test-data/unit/check-unreachable-code.test to verify the improved handling of conditional expressions, particularly those involving platform checks and logical operations, under different platform settings.

Changes

File(s) Change Summary
mypy/reachability.py Refactored infer_condition_value to handle negation recursively and evaluate both operands for and/or logic.
test-data/unit/check-unreachable-code.test Added new test cases for platform-based conditions, logical operations, and unreachable code detection.

Poem

In the warren of logic, the rabbit hops,
Through "and" and "or," it never stops.
Negations now handled with elegant care,
Both sides of logic get their fair share.
Tests abound for platforms and more,
Ensuring unreachable code’s out the door!
🐇✨
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@visz11
Copy link
Collaborator

visz11 commented Apr 23, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 23, 2025

✅ Actions performed

Full review triggered.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
mypy/reachability.py (1)

131-133: Redundant guard – dead code

The if expr.op not in ("or", "and"): check can never be true, because the surrounding elif already guarantees expr.op in ("and", "or").
Removing it will simplify the flow and silence future linters.

-        if expr.op not in ("or", "and"):
-            return TRUTH_VALUE_UNKNOWN
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 380cb8d and 648bd84.

📒 Files selected for processing (2)
  • mypy/reachability.py (1 hunks)
  • test-data/unit/check-unreachable-code.test (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
mypy/reachability.py (1)
mypy/nodes.py (17)
  • expr (2290-2296)
  • UnaryExpr (2052-2071)
  • name (234-235)
  • name (353-354)
  • name (532-533)
  • name (571-577)
  • name (809-810)
  • name (907-908)
  • name (1068-1069)
  • name (2287-2288)
  • name (2572-2573)
  • name (3205-3207)
  • name (3752-3753)
  • name (3864-3865)
  • NameExpr (1875-1895)
  • MemberExpr (1898-1914)
  • OpExpr (2090-2133)
🔇 Additional comments (5)
mypy/reachability.py (1)

118-121: Negation branch looks solid

Recursively delegating to infer_condition_value() and then using the inverted_truth_mapping is much simpler than the old flag‑based approach – nice clean‑up!

test-data/unit/check-unreachable-code.test (4)

503-523: Great coverage of binary and/or cases

The new tests exercise the full matrix of (true/false)×(true/false) platform checks and catch regressions nicely. 👍


525-541: Negation tests are spot‑on

Good to see both direct and grouped negations covered – this verifies the new not branch you added in reachability.py.


547-551: Edge‑case arithmetic on booleans is intentionally covered

These cases look weird at first glance, but they highlight fallback behaviour when we leave the supported boolean‑operator set. Nice inclusion.


554-577: Useful MYPY / TYPE_CHECKING combinations

These scenarios ensure the new truth‑table still interacts correctly with compile‑time‑only constants. Test expectations match the intended semantics.

Comment on lines +137 to +155
if expr.op == "or":
if ALWAYS_TRUE in results:
return ALWAYS_TRUE
elif MYPY_TRUE in results:
return MYPY_TRUE
elif left == right == MYPY_FALSE:
return MYPY_FALSE
elif results <= {ALWAYS_FALSE, MYPY_FALSE}:
return ALWAYS_FALSE
elif expr.op == "and":
if ALWAYS_FALSE in results:
return ALWAYS_FALSE
elif MYPY_FALSE in results:
return MYPY_FALSE
elif left == right == ALWAYS_TRUE:
return ALWAYS_TRUE
elif results <= {ALWAYS_TRUE, MYPY_TRUE}:
return MYPY_TRUE
return TRUTH_VALUE_UNKNOWN
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Incorrect truth‑table for or when mixing ALWAYS_FALSE and MYPY_FALSE

Example:
cond = ALWAYS_FALSE or MYPY_FALSE

• mypy sees False or False -> False
• runtime sees False or True -> True
→ The result should be MYPY_FALSE, but the current logic returns ALWAYS_FALSE via the
results <= {ALWAYS_FALSE, MYPY_FALSE} branch.

A minimal fix is to short‑circuit on MYPY_FALSE before the subset test:

@@
         if expr.op == "or":
             if ALWAYS_TRUE in results:
                 return ALWAYS_TRUE
             elif MYPY_TRUE in results:
                 return MYPY_TRUE
+            # If at least one side is MYPY_FALSE the overall value is
+            # false for mypy but true at runtime.
+            elif MYPY_FALSE in results:
+                return MYPY_FALSE
-            elif left == right == MYPY_FALSE:
-                return MYPY_FALSE
-            elif results <= {ALWAYS_FALSE, MYPY_FALSE}:
-                return ALWAYS_FALSE
+            elif results == {ALWAYS_FALSE}:
+                return ALWAYS_FALSE

This preserves the existing left == right == MYPY_FALSE optimisation and fixes the mixed case.

(Optional) : consider extracting a small helper (e.g. combine_truth_values(op, left, right)) so the full 5‑state truth table is unit‑tested and easier to reason about.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if expr.op == "or":
if ALWAYS_TRUE in results:
return ALWAYS_TRUE
elif MYPY_TRUE in results:
return MYPY_TRUE
elif left == right == MYPY_FALSE:
return MYPY_FALSE
elif results <= {ALWAYS_FALSE, MYPY_FALSE}:
return ALWAYS_FALSE
elif expr.op == "and":
if ALWAYS_FALSE in results:
return ALWAYS_FALSE
elif MYPY_FALSE in results:
return MYPY_FALSE
elif left == right == ALWAYS_TRUE:
return ALWAYS_TRUE
elif results <= {ALWAYS_TRUE, MYPY_TRUE}:
return MYPY_TRUE
return TRUTH_VALUE_UNKNOWN
if expr.op == "or":
if ALWAYS_TRUE in results:
return ALWAYS_TRUE
elif MYPY_TRUE in results:
return MYPY_TRUE
# If at least one side is MYPY_FALSE the overall value is
# false for mypy but may be true at runtime.
elif MYPY_FALSE in results:
return MYPY_FALSE
elif results == {ALWAYS_FALSE}:
return ALWAYS_FALSE
elif expr.op == "and":
if ALWAYS_FALSE in results:
return ALWAYS_FALSE
elif MYPY_FALSE in results:
return MYPY_FALSE
elif left == right == ALWAYS_TRUE:
return ALWAYS_TRUE
elif results <= {ALWAYS_TRUE, MYPY_TRUE}:
return MYPY_TRUE
return TRUTH_VALUE_UNKNOWN

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
mypy/reachability.py (1)

134-155: 🛠️ Refactor suggestion

Better handling of binary logical operators

The new implementation provides more comprehensive logic for handling both operands in binary operations, correctly evaluating all combinations of truth values. This addresses the previous issue noted in code reviews where mixed ALWAYS_FALSE and MYPY_FALSE values were incorrectly processed.

However, there's still a potential issue with the truth table for or operator. When MYPY_FALSE is in results but not equal on both sides, it should still return MYPY_FALSE as per the previous comment.

    if expr.op == "or":
        if ALWAYS_TRUE in results:
            return ALWAYS_TRUE
        elif MYPY_TRUE in results:
            return MYPY_TRUE
+       elif MYPY_FALSE in results:
+           return MYPY_FALSE
        elif left == right == MYPY_FALSE:
            return MYPY_FALSE
        elif results <= {ALWAYS_FALSE, MYPY_FALSE}:
            return ALWAYS_FALSE
🧹 Nitpick comments (1)
mypy/reachability.py (1)

131-132: Redundant conditional check

This conditional check is unreachable because we're already inside a block that checks for expr.op in ("and", "or") on line 130.

-    if expr.op not in ("or", "and"):
-        return TRUTH_VALUE_UNKNOWN
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 380cb8d and 648bd84.

📒 Files selected for processing (2)
  • mypy/reachability.py (1 hunks)
  • test-data/unit/check-unreachable-code.test (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
mypy/reachability.py (1)
mypy/nodes.py (17)
  • expr (2290-2296)
  • UnaryExpr (2052-2071)
  • name (234-235)
  • name (353-354)
  • name (532-533)
  • name (571-577)
  • name (809-810)
  • name (907-908)
  • name (1068-1069)
  • name (2287-2288)
  • name (2572-2573)
  • name (3205-3207)
  • name (3752-3753)
  • name (3864-3865)
  • NameExpr (1875-1895)
  • MemberExpr (1898-1914)
  • OpExpr (2090-2133)
🔇 Additional comments (5)
mypy/reachability.py (1)

118-120: Good improvement to handle negation directly

This change simplifies the logic by recursively evaluating the negated expression and looking up its opposite truth value, which is more readable and maintainable than using a flag.

test-data/unit/check-unreachable-code.test (4)

503-523: Good test cases for binary logical operations

These test cases comprehensively cover the various combinations of truth values in binary operations, which is essential for verifying the improved behavior of the infer_condition_value function.


525-541: Good test coverage for negation handling

These tests effectively verify the negation handling logic, ensuring that expressions like not sys.platform == 'linux' are properly evaluated under different conditions.


543-551: Good tests for unsupported operations

These test cases verify the behavior when unsupported operations are applied to boolean expressions, ensuring proper type inference.


553-577: Comprehensive tests for MYPY and TYPE_CHECKING in binary operations

These test cases verify the behavior when mypy-specific values (TYPE_CHECKING, MYPY) are used in binary operations with platform checks. The tests ensure that functions in unreachable blocks are properly detected.

@visz11
Copy link
Collaborator

visz11 commented Apr 24, 2025

/gemini review

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The pull request aims to improve the accuracy of condition evaluation in mypy, particularly for logical negation and binary logical expressions. The changes involve modifications to the infer_condition_value function in mypy/reachability.py and the addition of new test cases in test-data/unit/check-unreachable-code.test. Overall, the changes seem well-structured and address the identified issue. However, there are a few areas that could benefit from further refinement.

Summary of Findings

  • Truth table completeness: The updated code in infer_condition_value now recognizes the whole truth table for and and or operations, leading to more accurate detection of unreachable code.
  • Test coverage: The added test cases cover various scenarios, including platform checks, logical operators, and negations, ensuring the correct behavior of the modified code.
  • Redundant check: The check if expr.op not in ("or", "and") on line 131 in mypy/reachability.py seems redundant, as the function already handles only 'and' and 'or' operations in the preceding elif condition.

Merge Readiness

The pull request is almost ready for merging. The added functionality and tests are valuable additions. However, the redundant check identified in mypy/reachability.py should be addressed before merging. Additionally, consider the question raised in the pull request description regarding boolean literals. I am unable to approve this pull request, and recommend that others review and approve this code before merging.

Comment on lines +131 to +132
if expr.op not in ("or", "and"):
return TRUTH_VALUE_UNKNOWN

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This check seems redundant, as the elif condition on line 130 already ensures that expr.op is either "and" or "or". Can this be removed to simplify the code?

Suggested change
if expr.op not in ("or", "and"):
return TRUTH_VALUE_UNKNOWN
left = infer_condition_value(expr.left, options)
right = infer_condition_value(expr.right, options)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Unreachability depends on statement ordering
3 participants