Skip to content

External factory#1158

Merged
rrousselGit merged 2 commits intomasterfrom
external-factory
Feb 23, 2025
Merged

External factory#1158
rrousselGit merged 2 commits intomasterfrom
external-factory

Conversation

@rrousselGit
Copy link
Copy Markdown
Owner

@rrousselGit rrousselGit commented Feb 23, 2025

Support having factory constructors redirect to a non-generated class.

Summary by CodeRabbit

  • New Features

    • Introduced mixed mode, allowing both traditional and streamlined class definitions with enhanced constructor support (e.g., initializers and super calls) and flexible default values.
    • Enabled custom handling of union cases and enforced updated class declaration modifiers for improved type consistency.
  • Tests

    • Expanded test coverage validates mixed mode functionality and ensures robust behavior for union case handling and inheritance scenarios.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 23, 2025

Walkthrough

This changeset updates the Freezed library for version 3.0.0 with several breaking changes and new features. The changelog details removal of outdated methods and stricter requirements for class definitions, while new features introduce mixed mode support and enhanced constructor behaviors. Internal generator logic is refactored by replacing manual declaration parsing with a unified method, and copyWith generation now accounts for parent classes. Additionally, constructor and model parsing improvements are applied, and new tests are added to validate mixed union types and sealed class hierarchies.

Changes

File(s) Change Summary
packages/freezed/CHANGELOG.md Changelog for Freezed v3.0.0: breaking removal of map/when variants, requirement for Freezed classes to be abstract/sealed/manually implement _$MyClass, introduction of mixed mode supporting traditional and new syntax, enhanced constructor handling, and union case ejection.
packages/freezed/lib/src/freezed_generator.dart Removed _parseDeclaration method, replaced with a call to Class.parseAll to consolidate declaration parsing, and updated CopyWith instantiation by adding parents: data.parents (and parents: [] for constructor-specific cases).
packages/freezed/lib/src/models.dart Added required isSynthetic parameter to ConstructorDetails, updated method signatures for parseAll and _from to include filtering of generated units, and renamed isSynthetic to isSyntheticParam, ensuring proper parent-child relationships among classes.
packages/freezed/lib/src/templates/concrete_template.dart Modified the toString method in Concrete to perform a conditional check on the constructor’s synthetic status and return an empty string for non-synthetic constructors.
packages/freezed/lib/src/templates/copy_with.dart Introduced a new required parents field in the CopyWith class and modified the _deepCopyInterface method to correctly construct an implements string that includes interfaces from multiple parent classes.
packages/freezed/test/mixed_test.dart Added a new test file defining sealed classes (Mixed, DiamondA, DiamondB, etc.) with various factory constructors and inheritance strategies, validating object types and string representations to ensure proper functionality of the new mixed mode and union case ejection.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FreezedGenerator
    participant ClassParser
    participant CopyWith
    participant Concrete

    User->>FreezedGenerator: Invoke factory constructor (e.g., Mixed.a)
    FreezedGenerator->>ClassParser: Parse class declarations with Class.parseAll
    ClassParser-->>FreezedGenerator: Return parsed Class instances
    FreezedGenerator->>CopyWith: Generate copyWith (include parent classes)
    CopyWith-->>FreezedGenerator: Return copyWith instance
    FreezedGenerator->>Concrete: Generate class representation
    Concrete-->>User: Instance created with correct string representation
Loading

Poem

I hop through lines of freshly forged code,
Carrots of logic in every new node.
Breaking old chains with a playful tweak,
Mixed modes bloom with a syntax so sleek.
With fields and parents joining the spree,
I'm a rabbit in code—wild and free!
Celebrating change with a joyful, swift leap!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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.

Copy link
Copy Markdown

@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 (2)
packages/freezed/lib/src/models.dart (1)

186-186: Consider documenting the new parameter.
Adding isSynthetic to the constructor is fine, but consider adding a doc comment explaining how it’s determined and used. This helps maintain clarity for future contributors.

packages/freezed/CHANGELOG.md (1)

3-163: Minor documentation improvements needed.

Please consider the following refinements to the changelog:

  1. Remove trailing punctuation from headings:
    -### Breaking changes:
    +### Breaking changes
    -### New: Inheritance and non-constant default values.
    +### New: Inheritance and non-constant default values
  2. Fix grammar issues:
    -Freezed will them pass it values
    +Freezed will then pass it values
    -control over every parts of your models
    +control over every part of your models
    -it is kind of required to "extend"
    +it is required to "extend"
🧰 Tools
🪛 LanguageTool

[grammar] ~79-~79: Did you mean to use a possessive pronoun here?
Context: ... can accept any parameter. Freezed will them pass it values from other factory con...

(MD_OBJ_PRONOUN)


[typographical] ~79-~79: Except for inverted sentences, ‘will them’ requires a question mark at the end of the sentence.
Context: ...er factory constructors, based on name. In short, this enables extending any c...

(MD_PRP_QUESTION_MARK)


[grammar] ~158-~158: The noun should probably be in the singular form.
Context: ... offers fine-grained control over every parts of your models. Note: Unfortunatel...

(EVERY_EACH_SINGULAR)


[style] ~161-~161: Consider removing “kind of” to make your writing sound more confident.
Context: ...models. Note: Unfortunately, it is kind of required to "extend" the parent class (so here `...

(KIND_OF_SORT_OF_CONFIDENCE)

🪛 markdownlint-cli2 (0.17.2)

3-3: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


50-50: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b51e44f and 1b330d8.

📒 Files selected for processing (6)
  • packages/freezed/CHANGELOG.md (2 hunks)
  • packages/freezed/lib/src/freezed_generator.dart (3 hunks)
  • packages/freezed/lib/src/models.dart (9 hunks)
  • packages/freezed/lib/src/templates/concrete_template.dart (1 hunks)
  • packages/freezed/lib/src/templates/copy_with.dart (3 hunks)
  • packages/freezed/test/mixed_test.dart (1 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
packages/freezed/CHANGELOG.md

3-3: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


50-50: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)

🪛 LanguageTool
packages/freezed/CHANGELOG.md

[grammar] ~79-~79: Did you mean to use a possessive pronoun here?
Context: ... can accept any parameter. Freezed will them pass it values from other factory con...

(MD_OBJ_PRONOUN)


[typographical] ~79-~79: Except for inverted sentences, ‘will them’ requires a question mark at the end of the sentence.
Context: ...er factory constructors, based on name. In short, this enables extending any c...

(MD_PRP_QUESTION_MARK)


[grammar] ~158-~158: The noun should probably be in the singular form.
Context: ... offers fine-grained control over every parts of your models. Note: Unfortunatel...

(EVERY_EACH_SINGULAR)


[style] ~161-~161: Consider removing “kind of” to make your writing sound more confident.
Context: ...models. Note: Unfortunately, it is kind of required to "extend" the parent class (so here `...

(KIND_OF_SORT_OF_CONFIDENCE)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: freezed (packages/freezed, master, get)
🔇 Additional comments (17)
packages/freezed/lib/src/models.dart (3)

12-12: Dependency import looks good.
This new import is presumably used in this file. The usage appears consistent with references to parse_generator.dart.


258-259: Parameter addition confirmed.
The new unitsExcludingGeneratedFiles parameter is used consistently to check for valid class declarations. Looks suitable for filtering out generated files.


393-398: Handle missing property case safely.
Calling .first on where((element) => element.name == param) may throw if no property matches. If it’s guaranteed to exist, consider adding an assertion. Otherwise, use a safe fallback.

Possible example:

 bool isSyntheticParam({required String param}) {
-  return properties
-      .where((element) => element.name == param)
-      .first
-      .isSynthetic;
+  final match = properties.firstWhereOrNull((element) => element.name == param);
+  if (match == null) {
+    throw ArgumentError.value(param, 'param', 'No property found with that name');
+  }
+  return match.isSynthetic;
 }
packages/freezed/test/mixed_test.dart (9)

1-2: Relevant imports confirmed.
References to freezed_annotation and test are needed for the annotation and tests. Good job.


4-4: Part statement is standard for Freezed.
Required for generated code. Looks correct.


6-13: Sealed class ‘Mixed’ review.
Defining multiple factory constructors that redirect to different subtypes demonstrates the “mixed mode” usage. This is a good test scenario for verifying external classes/constructors.


15-26: ‘FreezedImplements’ correctness.
Implements Mixed with fields overshadowed. The overrides look consistent.


27-35: ‘ManualClass’ extension.
A manually defined class extending Mixed ensures coverage of user-defined inheritance paths. Implementation is straightforward.


37-47: ‘FreezedExtends’ extension.
Combines Freezed with inheritance from Mixed. This is well-structured to validate new “mixed” behavior.


49-59: ‘DiamondA’ & ‘DiamondB’ classes.
Demonstrates diamond inheritance by sharing DiamondLeaf. Good for testing intersection of sealed classes.


60-62: ‘DiamondLeaf’ implements both A & B.
Showcases the “diamond” scenario, verifying resolved inheritance across multiple parents.


64-96: Test cases appear sound.
All four factory constructors of Mixed and the diamond classes are tested. For Mixed.c, note that toString() excludes c. If that’s intended, the test is correct; otherwise, the manual toString logic might need updating.

packages/freezed/lib/src/freezed_generator.dart (3)

62-67: Switch to Class.parseAll.
This refactoring consolidates parsing logic. The code is consistent with the new approach in models.dart.


85-85: Adding parents: data.parents for common copyWith.
This helps in referencing parent classes for the generated copyWith. Great improvement for multi-level class designs.


115-115: Empty parents for constructor-specific copyWith.
Skipping parent references on a specific constructor copy is consistent, ensuring independent copy logic.

packages/freezed/lib/src/templates/copy_with.dart (1)

15-15: LGTM! Well-structured implementation of multi-parent support.

The addition of the parents field and its integration into the constructor enhances the copyWith functionality to support multiple parent classes, which is essential for the new mixed mode feature. The implementation maintains backward compatibility while adding new capabilities.

Also applies to: 39-39

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

43-44: LGTM! Correct handling of non-synthetic constructors.

The early return for non-synthetic constructors ensures that Freezed doesn't generate code for manually implemented constructors, which is essential for supporting external factory constructors.

Comment on lines +303 to +308
isSynthetic: unitsExcludingGeneratedFiles.any(
(e) => !e.declarations
.whereType<ClassDeclaration>()
.map((e) => e.name.lexeme)
.contains(redirectedName),
),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Re-check logic for isSynthetic.
Using any((e) => !e.declarations.contains(...)) marks this constructor as synthetic if any compilation unit omits the redirectedName. If the intention is to denote synthetic only when no unit defines redirectedName, consider .every(...) instead.

Here is a possible fix:

-isSynthetic: unitsExcludingGeneratedFiles.any(
-  (e) => !e.declarations
-      .whereType<ClassDeclaration>()
-      .map((e) => e.name.lexeme)
-      .contains(redirectedName),
-),
+isSynthetic: unitsExcludingGeneratedFiles.every(
+  (unit) => !unit.declarations
+      .whereType<ClassDeclaration>()
+      .map((c) => c.name.lexeme)
+      .contains(redirectedName),
+),
📝 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
isSynthetic: unitsExcludingGeneratedFiles.any(
(e) => !e.declarations
.whereType<ClassDeclaration>()
.map((e) => e.name.lexeme)
.contains(redirectedName),
),
isSynthetic: unitsExcludingGeneratedFiles.every(
(unit) => !unit.declarations
.whereType<ClassDeclaration>()
.map((c) => c.name.lexeme)
.contains(redirectedName),
),

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