How is __shared keyword supposed to work in Swift 5.0?

I'm a normal Swift user trying to understand the semantics of this code--does the code compile, and what value is printed? What happens on the caller or callee side at run time is neither part of the language semantics nor relevant to me.

func f(sh: shared Int, io: inout Int) {
  io += 1
  print(sh)
}

var x = 5
f(sh: x, io: &x)

The possiblities are:

  1. The shared argument is an immutable borrow and the code is illegal.

  2. The shared argument has pass-by-reference semantics.

  3. shared does not affect program semantics for any code that I can write today.

First I read Swift's documentation. That leads me to the first possiblity. __shared -> "shared values" -> "immutable borrow". But the code does compile. What could this mean?

The only reasonable assumption now is that __shared provides pass-by-reference semantics, what else could it possibly mean? After all, language designers just told me that:

  • __shared does affect semantics by suppressing copies!
  • "__shared acts like a borrow"!
  • "passed by value is [just] an optimization"!

How could this be more misleading?

What language designers should do about this:

Surface __shared as unowned. Document that it is the inverse of owned which allows user control over caller vs. callee ownership of references, that it has no effect on program semantics, that it does not enforce exclusivity (which would be clearly implied by "shared"), and that value types are passed by value either way.

I did try to nip this in the bud last year:

Back to the OP:

But even at run time this prints 5, not 6 as I'd expect if __shared prevents it from creating a copy. Does it mean that I misunderstand the intended use of __shared?

Swift language semantics require that the argument be copied. You were being mislead.

Or another possibility I'm thinking, is __shared keyword currently only "decorative" to annotate the code for ABI stability purposes and there's no real borrow checker available for Swift 5.0?

@Max_Desiatov You are absolutely correct. Congratulations for seeing throught the nonsense even though you had to reverse engineer the true behavior of the language.

3 Likes