Skip to content

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

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Warning

Rate limit exceeded

@arvi18 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 50 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 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)

"""

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
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch clone-bugfix/gh-18901-reachability

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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)

@visz11
Copy link
Collaborator

visz11 commented Jul 2, 2025

/do-refacto

@visz11
Copy link
Collaborator

visz11 commented Jul 16, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 16, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@visz11
Copy link
Collaborator

visz11 commented Jul 16, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 16, 2025

🤖 Refacto.AI: PR Summary & Reviewer Guide

Warning: Requirements context (e.g., linked ticket) was not provided. Analysis is based solely on PR metadata and code diff, which may be incomplete.

🎯 1. The Goal (Why was this PR raised?)

This PR aims to enhance the infer_condition_value function to correctly recognize and evaluate the entire truth table for conditional expressions. The goal is to improve type checking by properly handling various logical operations (AND, OR, NOT) and their combinations.

🗺️ 2. The Changes (What was implemented?)

Goal / Requirement Addressed Implementation Details (File & Key Changes)
Improve truth table recognition mypy/reachability.py (Modified):
- Refactored infer_condition_value to handle logical operations more comprehensively
- Moved negation handling to the beginning of the function
- Replaced conditional logic for AND/OR operations with a more complete evaluation that considers all possible combinations
Add test cases for new functionality test-data/unit/check-unreachable-code.test (Modified):
- Added test case testConditionalValuesBinaryOps to verify handling of all combinations of true/false with AND/OR operators
- Added test case testConditionalValuesNegation to verify handling of NOT operations with various operands
- Added test case testConditionalValuesUnsupportedOps to test behavior with unsupported operations
- Added test case testMypyFalseValuesInBinaryOps_no_empty to verify handling of TYPE_CHECKING and MYPY constants in conditional expressions

🤔 3. Key Areas for Human Review

Area of Concern: Core Logic Change in infer_condition_value

  • File: mypy/reachability.py (Lines 115-168)
  • Why: This function is critical for type checking as it determines the truth value of conditional expressions. The implementation has been significantly restructured, changing how logical operations are evaluated.
  • Testing Instruction: Verify that the new implementation correctly handles all combinations in the truth table (true AND true, true AND false, etc.) by running the new test cases and checking if they pass as expected.

Area of Concern: Handling of Special Cases

  • File: mypy/reachability.py (Lines 136-153)
  • Why: The new implementation introduces more complex logic for handling different combinations of truth values with AND/OR operators, which could introduce edge cases.
  • Testing Instruction: Review the conditions for each logical operator to ensure they correctly implement the truth table. Pay special attention to the handling of MYPY_TRUE and MYPY_FALSE values, which represent values that differ between type checking time and runtime.

Area of Concern: Comprehensive Test Coverage

  • File: test-data/unit/check-unreachable-code.test (Lines 500-582)
  • Why: The PR adds extensive new test cases, but it's important to verify they cover all the logical combinations and edge cases.
  • Testing Instruction: Run the full test suite and verify that all the new test cases pass. Check if there are any logical combinations or edge cases that aren't covered by the tests.

Copy link

refacto-test bot commented Jul 16, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@coderabbit-test coderabbit-test deleted a comment from refacto-test bot Jul 22, 2025
Copy link

refacto-test bot commented Jul 22, 2025

PR already reviewed at the latest commit: 648bd84.
Please try again with new changes.

1 similar comment
Copy link

refacto-test bot commented Jul 22, 2025

PR already reviewed at the latest commit: 648bd84.
Please try again with new changes.

@visz11
Copy link
Collaborator

visz11 commented Jul 22, 2025

/refacto-test

Copy link

refacto-test bot commented Jul 22, 2025

PR already reviewed at the latest commit: 648bd84.
Please try again with new changes.

@visz11
Copy link
Collaborator

visz11 commented Aug 21, 2025

/refacto-test

Copy link

refacto-test bot commented Aug 21, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

Copy link

refacto-test bot commented Aug 21, 2025

Code Review: Boolean Logic Evaluation in Reachability Analysis

👍 Well Done
Comprehensive Truth Table Implementation

Complete truth table handling improves conditional branch evaluation accuracy and efficiency.

Thorough Test Coverage

Extensive test cases verify all logical operation combinations, enhancing reliability.

📌 Files Processed
  • test-data/unit/check-unreachable-code.test
  • mypy/reachability.py
📝 Additional Comments
mypy/reachability.py (1)
Truth Table Constants

Truth table logic uses magic constants directly throughout the code. This approach makes the code harder to understand and maintain, as the meaning of these constants isn't immediately clear without context.

def _evaluate_or_condition(left: int, right: int) -> int:
    results = {left, right}
    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
    return TRUTH_VALUE_UNKNOWN

def _evaluate_and_condition(left: int, right: int) -> int:
    results = {left, right}
    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

# In the main function:
if expr.op == "or":
    return _evaluate_or_condition(left, right)
elif expr.op == "and":
    return _evaluate_and_condition(left, right)

Standards:

  • Clean-Code-Function-Size
  • Refactoring-Extract-Method
  • SOLID-SRP

Comment on lines +131 to +132
if expr.op not in ("or", "and"):
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.

Redundant Operator Check Creating Unreachable Code

Redundant check for operator type after already confirming expr.op is 'and' or 'or' at line 130. This creates unreachable code since the outer if-statement already ensures expr.op is either 'and' or 'or'.

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)
Standards
  • ISO-IEC-25010-Reliability-Maturity
  • DbC-Code-Clarity

Comment on lines 171 to 172
return result

Copy link

Choose a reason for hiding this comment

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

Negation Logic Redundancy

The 'negated' flag is never set in the code but is used in this condition. This creates dead code that will never execute, potentially masking logical errors in negation handling.

Standards
  • Logic-Verification-Dead-Code
  • Algorithm-Correctness-Control-Flow

name = expr.name
elif isinstance(expr, MemberExpr):
name = expr.name
elif isinstance(expr, OpExpr) and expr.op in ("and", "or"):
Copy link

Choose a reason for hiding this comment

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

Unhandled Operator Case

The function handles only 'and' and 'or' operators explicitly, but the redundant check suggests other operators were intended. This could cause unexpected behavior if other operators are passed.

Suggested change
elif isinstance(expr, OpExpr) and expr.op in ("and", "or"):
elif isinstance(expr, OpExpr):
if expr.op in ("and", "or"):
left = infer_condition_value(expr.left, options)
right = infer_condition_value(expr.right, options)
results = {left, right}
if expr.op == "or":
# ... existing or logic ...
else:
return TRUTH_VALUE_UNKNOWN
Standards
  • ISO-IEC-25010-Functional-Correctness-Completeness
  • ISO-IEC-25010-Reliability-Fault-Tolerance

@arvi18
Copy link
Author

arvi18 commented Sep 2, 2025

/refacto-test

Copy link

refacto-test bot commented Sep 2, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Author

arvi18 commented Sep 2, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Sep 2, 2025

✅ Actions performed

Full review triggered.

Copy link

refacto-test bot commented Sep 2, 2025

Code Review: Conditional Logic Evaluation

👍 Well Done
Comprehensive Truth Table

Enhanced logical operator evaluation improves conditional reliability.

Simplified Negation Handling

Dedicated negation handling reduces complexity and improves maintainability.

📌 Files Processed
  • test-data/unit/check-unreachable-code.test
  • mypy/reachability.py
📝 Additional Comments
mypy/reachability.py (2)
Incomplete Set Comparison

The set comparison could be simplified to check if both values are in {ALWAYS_FALSE, MYPY_FALSE} since results only contains two values (left and right). Current approach works but is less direct than checking left and right individually.

Standards:

  • Algorithm-Correctness-Set-Operations
  • Logic-Verification-Simplicity
  • Mathematical-Accuracy-Boolean-Logic
Logic Evaluation Improvement

The refactored code improves conditional evaluation but introduces duplicate logic for 'not' operations. This creates minor maintainability risk if truth mappings change.

Standards:

  • CWE-691
  • OWASP-A04

Comment on lines +131 to +132
if expr.op not in ("or", "and"):
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.

Redundant Condition Check

Redundant check for operators not in ("or", "and") after already confirming expr.op is in ("and", "or"). This dead code branch is unreachable, causing unnecessary complexity.

Standards
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • ISO-IEC-25010-Reliability-Maturity

Comment on lines +137 to +154
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
Copy link

Choose a reason for hiding this comment

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

Complex Conditional Logic

Complex nested conditionals with multiple return paths make the truth table logic difficult to maintain. Consider using a lookup table or mapping approach for better readability and easier future modifications.

Standards
  • Clean-Code-Complexity
  • Design-Pattern-Table-Lookup

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