Skip to content

Commit

Permalink
Make capturing unique values in closures easier
Browse files Browse the repository at this point in the history
Closures defined using `fn move` that capture `uni T` values now expose
them as `mut T` instead of `uni mut T`. This makes working with these
values easier.

Changelog: added
  • Loading branch information
yorickpeterse committed May 30, 2024
1 parent 0fd8ad9 commit e12d2b3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions compiler/src/type_check/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4542,6 +4542,21 @@ impl<'a> CheckMethodBody<'a> {
// closures the capture type is always a reference.
if captured {
capture_as = expose_as;
} else if moving && capture_as.is_uni(self.db()) {
// When an `fn move` captures a `uni T`, we capture it
// as-is but expose it as `mut T`, making it easier to
// work with the value. This is safe because:
//
// 1. The closure itself doesn't care about the
// uniqueness constraint
// 2. We can't move the value out of the closure and
// back into a `uni T` value
//
// We don't change the capture type such that `fn move`
// closures capturing `uni T` values can still be
// inferred as `uni fn move` closures.
expose_as =
capture_as.as_owned(self.db()).as_mut(self.db());
} else {
if !moving {
capture_as = capture_as.as_mut(self.db());
Expand Down
14 changes: 14 additions & 0 deletions std/fixtures/diagnostics/fn_move_captures_uni.inko
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class A {}

fn example1 {
let a = recover [A()]
let b = recover fn { a.push(A()) }
}

fn example2 {
let a = recover [A()]
let b = recover fn move { a.push(A()) }
}

# fn_move_captures_uni.inko:5:24 error(invalid-symbol): the variable 'a' exists, but its type ('uni Array[A]') prevents it from being captured
# fn_move_captures_uni.inko:5:31 error(invalid-type): the receiver of this call requires sendable arguments, but 'A' isn't sendable

0 comments on commit e12d2b3

Please sign in to comment.