Skip to content

Fix ==#1224

Merged
rrousselGit merged 2 commits intomasterfrom
supercall
Apr 5, 2025
Merged

Fix ==#1224
rrousselGit merged 2 commits intomasterfrom
supercall

Conversation

@rrousselGit
Copy link
Copy Markdown
Owner

@rrousselGit rrousselGit commented Apr 5, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced equality and hash code behavior in class hierarchies by including superclass comparisons, ensuring more accurate object comparisons.
  • Documentation
    • Updated release notes reflecting improvements to equality and hash code handling.
  • Tests
    • Introduced new unit and integration tests to confirm the enhanced behaviors across different inheritance scenarios.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 5, 2025

Walkthrough

This pull request introduces updates to improve the handling of equality and hash code operations in the Freezed library. The changes affect how generated == and hashCode methods behave in subclasses by incorporating superclass comparisons when required. Updates include modifications in AST processing, template rendering, and model definitions, as well as new tests and integration examples to validate the updated logic.

Changes

File(s) Change Summary
packages/freezed/CHANGELOG.md Updated changelog with a new "Unreleased fix" section, documenting changes to the equality (==) and hash code (hashCode) behavior involving superclass comparisons.
packages/freezed/lib/src/ast.dart Added an import for analyzer elements; in extension ClassX, replaced hasCustomEquals with a direct check using hasEqual, updated hasSuperEqual, added hasSuperHashCode; introduced extension on InterfaceElement with hasEqual and hasHashCode.
packages/freezed/lib/src/models.dart Added getter properties (hasSuperEqual and hasSuperHashCode) in the Class class to expose corresponding values from the underlying node.
packages/freezed/lib/src/templates/concrete_template.dart Updated the operatorEqualMethod and hashCodeMethod to include conditional checks for data.hasSuperEqual and data.hasSuperHashCode, incorporating super == other and super.hashCode where applicable.
packages/freezed/test/extend_test.dart
packages/freezed/test/integration/extend.dart
Added new test files with multiple class declarations to verify and showcase the updated equality and hash code behavior across different inheritance patterns.

Sequence Diagram(s)

sequenceDiagram
    participant Inst as Instance
    participant CT as Concrete Template
    Inst->>CT: Invoke operator==(other)
    alt data.hasSuperEqual is true
        CT->>Inst: Calls super == other for equality
    else
        CT->>Inst: Compares instance fields directly
    end
Loading
sequenceDiagram
    participant Inst as Instance
    participant CT as Concrete Template
    Inst->>CT: Request hashCode computation
    alt data.hasSuperHashCode is true
        CT->>Inst: Includes super.hashCode in calculation
    else
        CT->>Inst: Computes hashCode from local properties
    end
Loading

Possibly related PRs

  • External factory #1158: Addresses similar improvements in handling equality and hash code within class inheritance, focusing on constructor handling and the overall class behavior.

Poem

Oh, how I hopped in delight so free,
Fixing equality with a super decree.
Hash codes now dance with a graceful spin,
In inheritance realms, new logic begins.
With tests that twinkle like stars above,
I nibble on carrots and code with love!
Hoppy changes in every line, a true bunny-approved sign!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 06af3b4 and cf3aea4.

📒 Files selected for processing (6)
  • packages/freezed/CHANGELOG.md (1 hunks)
  • packages/freezed/lib/src/ast.dart (2 hunks)
  • packages/freezed/lib/src/models.dart (1 hunks)
  • packages/freezed/lib/src/templates/concrete_template.dart (2 hunks)
  • packages/freezed/test/extend_test.dart (1 hunks)
  • packages/freezed/test/integration/extend.dart (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: freezed (packages/freezed, master, get)
🔇 Additional comments (13)
packages/freezed/test/extend_test.dart (1)

1-15: Good test coverage for the fix.

The test properly verifies equality and hashCode behavior for subclasses. You're testing both equality conditions (same parameters are equal, different parameters are not) and hash code consistency for the Subclass2 implementation.

packages/freezed/CHANGELOG.md (1)

1-4: Clear and concise changelog entry.

The changelog entry correctly describes the fix without going into unnecessary implementation details. It clearly informs users that equal/hashCode now correctly handle inheritance by calling super when needed.

packages/freezed/lib/src/models.dart (1)

1032-1033: Good implementation of property accessors.

These new getters correctly expose the hasSuperEqual and hasSuperHashCode properties from the _node object, allowing generated code to properly call super implementations where needed.

packages/freezed/lib/src/templates/concrete_template.dart (2)

431-431: Proper fix for equality in class hierarchies.

Adding super == other to the equality check when a superclass has an equality operator ensures the object equality respects the full inheritance chain, which is crucial for correct behavior in polymorphic contexts.


473-473: Consistent hashCode implementation in class hierarchies.

Including super.hashCode in the hash computation ensures that objects that are equal will produce the same hash code, even when inheritance is involved. This is essential for proper behavior when objects are stored in hash-based collections like HashMap or HashSet.

packages/freezed/test/integration/extend.dart (4)

16-29: Well-implemented equality and hash code pattern in BaseWithEqual class

This class follows best practices for implementing equality and hash code in Dart:

  • Using identical check for reference equality
  • Proper type checking
  • Comparing relevant properties
  • Consistent hashCode implementation matching the equality comparison

31-37: Good pattern for extending a class with custom equality in Freezed

This is a good test case for how Freezed should handle a class that extends another class with custom equality. The Subclass2 class properly passes the required parameter to the superclass constructor.


39-47: Test classes with intentionally inconsistent equality/hashCode implementations

These two classes deliberately implement only one half of the equality contract (either == or hashCode) which is properly documented with ignore comments. While this would be an anti-pattern in production code, it's appropriate for testing how Freezed handles incomplete equality contracts in parent classes.

Also applies to: 49-53


55-61: Good test cases for Freezed with incomplete equality contracts

These classes provide important test cases for ensuring Freezed correctly handles inheritance from parent classes with incomplete equality contracts (missing either == or hashCode). The structure is clean and properly tests both scenarios.

Also applies to: 63-69

packages/freezed/lib/src/ast.dart (4)

3-3: Appropriate import addition

Adding the element-level import is needed for the new interface element extensions.


41-44: Improved separation of equality detection

Good refactoring to split equality checks into two distinct methods:

  1. hasSuperEqual - checks if any supertype has a custom equality operator
  2. hasCustomEquals - checks if the class itself has an equality operator

This separation allows Freezed to correctly handle inheritance in equality implementations.

Also applies to: 46-46


48-51: Added parallel hashCode check for superclasses

This addition complements the equality checks by adding a parallel check for hashCode in supertypes, which is essential for maintaining the equality contract when inheritance is involved.


54-58: Clean extension implementation for checking equality and hashCode

This extension provides a concise way to check if an interface element has custom equality or hashCode implementations. The code is well-structured and follows Dart's extension patterns effectively.

Some observations:

  • hasEqual correctly checks for operator methods named "=="
  • hasHashCode correctly filters for getters named "hashCode"

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@rrousselGit rrousselGit merged commit 8994f93 into master Apr 5, 2025
4 checks passed
@rrousselGit rrousselGit deleted the supercall branch April 5, 2025 09:54
@coderabbitai coderabbitai bot mentioned this pull request Jul 2, 2025
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.

1 participant