Skip to content
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

Prevent Swift objects' deinit from trying to free a nil pointer when subclassed for mocking #2001

Merged
merged 1 commit into from
Feb 29, 2024

Conversation

stefanceriu
Copy link
Contributor

@stefanceriu stefanceriu commented Feb 29, 2024

It seems that #1918 and implicitly #1975 missed one important aspect when opening up classes for mocking:

  • the current deinit implementation shouldn't be called for mocked/subclassed objects because the internal pointer is nil in those cases and doing so will result in a Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
  • deinit is also not overridable in Swift so this is not something that can be worked around downstream

This PR attempts to fix the problem by introducing a guard to check that pointer is not nil before trying to free it.

@stefanceriu stefanceriu requested a review from a team as a code owner February 29, 2024 15:30
@stefanceriu stefanceriu requested review from skhamis and removed request for a team February 29, 2024 15:30
@mhammond
Copy link
Member

Conceptually this seems correct, but the swift compiler doesn't seem to like it :)

@stefanceriu
Copy link
Contributor Author

Oh interesting, let me try something..

…n subclassed for mocking

- doing so will result in a `Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value`
- deinit is not overridable in Swift and this cannot be handled in the subclass
@stefanceriu stefanceriu force-pushed the stefan/fixMockDeallocationCrashes branch from aab4541 to 85e1965 Compare February 29, 2024 15:53
@stefanceriu
Copy link
Contributor Author

Okay, it's happy now. While guard let pointer else is completely valid it's a rather new syntactic sugar addition to Swift, with the original being guard let pointer = pointer else. I assume that the tests are using an older Swift version but the original syntax is still completely acceptable so I don't think we need any other changes.

Copy link
Member

@mhammond mhammond left a comment

Choose a reason for hiding this comment

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

Looks great, thanks!

@mhammond mhammond merged commit 77d3292 into mozilla:main Feb 29, 2024
5 checks passed
@stefanceriu stefanceriu deleted the stefan/fixMockDeallocationCrashes branch February 29, 2024 17:10
@stefanceriu
Copy link
Contributor Author

Yey, thank you too!

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.

2 participants