Skip to content

fix: prevent delegation to inexact user mappings#2372

Open
AmirTahan80 wants to merge 1 commit into
riok:mainfrom
AmirTahan80:fix/1793-user-mapping-warning
Open

fix: prevent delegation to inexact user mappings#2372
AmirTahan80 wants to merge 1 commit into
riok:mainfrom
AmirTahan80:fix/1793-user-mapping-warning

Conversation

@AmirTahan80

Copy link
Copy Markdown

Fixes #1793.

Summary

Mapperly could reuse a user-defined mapping through BuildDelegatedMapping even when the requested source and target types did not match the user mapping exactly. For example, a mapping returning Target[] could be selected when Mapperly needed IEnumerable<Target>.

Root cause

MappingBuilderContext.BuildDelegatedMapping accepted any existing mapping found for compatible types. This also included IUserMapping implementations, although user-defined mappings should only participate when their source and target types match exactly.

Changes

Impact

Mapperly now generates the appropriate collection and element mappings instead of selecting an inexact user-defined mapping. User mappings continue to work when their source and target types match exactly.

This changes the behavior of inexact user mappings and is therefore appropriate for the next major release, as discussed in the issue.

Validation

  • dotnet build Riok.Mapperly.slnx /p:TreatWarningsAsErrors=true
  • dotnet test Riok.Mapperly.slnx --no-build --no-restore
  • 1,726 tests passed, 2 skipped, 0 failed
  • CSharpier, style, and analyzer checks passed

Ignore user-defined mappings when resolving generalized delegated mappings,
ensuring they are only used for exact source and target type matches.

Add a regression test for riok#1793.
@AmirTahan80

Copy link
Copy Markdown
Author

Additional implementation context: this follows the approach proposed in #1793 by excluding IUserMapping instances from generalized delegation in MappingBuilderContext.BuildDelegatedMapping. Mapperly-generated mappings remain eligible for delegation.

The regression test uses the reported ICollection<Source?> to IEnumerable<Target> scenario and verifies that Mapperly generates and calls MapToTargetArray instead of selecting the inexact user-defined CustomMapToTargetArray method.

Validation completed locally:

  • Build succeeded with warnings treated as errors
  • 1,726 tests passed, 2 skipped, 0 failed
  • CSharpier, style, and analyzer checks passed

@AmirTahan80
AmirTahan80 marked this pull request as ready for review July 18, 2026 10:30
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.

Incorrect warning RMG020 for nested types when custom method return types do not match target type exactly

1 participant