When I try to re-borrow a bitwise copyable value, I get a compiler diagnostic that doesn't really make sense.. I know it doesn't really make sense to borrow a bitwise copyable value, but should this generally be disallowed / is the diagnostic just not ideal in this instance?
For context, I'm running into this where Element must conform to a protocol that is constrained to a lot of things, BitwiseCopyable being one of them. Trivial fix is to just use get.
extension Span where Element: BitwiseCopyable {
var a: Element {
borrow {
self[0]
// `- error: Invalid return value from a borrow accessor
// `- note: Borrow accessors can return stored properties, computed properties with borrow accessors or global 'let' declarations
}
}
subscript(blah i: Int) -> Element {
borrow {
self[i]
// `- error: Invalid return value from a borrow accessor
// `- note: Borrow accessors can return stored properties, computed properties with borrow accessors or global 'let' declarations
}
}
}
The diagnostic is accurate and enforces memory safety. A borrow accessor must yield a reference to existing storage, which is why the compiler note explicitly restricts it to stored properties, global let declarations, or other borrow accessors.
When you access self[0], the subscript evaluates to an owned, temporary copy of the BitwiseCopyable element. Yielding a borrow to this temporary copy is strictly disallowed because the temporary is destroyed at the end of the accessor's scope, which would create a dangling reference.
Using get is the correct structural approach. It returns the copied value directly instead of attempting to yield a reference to a short-lived temporary.
Got it, thanks! I just realised this also makes utter sense given most BitwiseCopyable will be loadable and you can't reference temporaries, much less values in registers.
Are you sure it isn't? I checked and I'm seeing a borrow accessor there... It would definitely explain why I can't get a Ref to a Span element atm, but this doesn't seem to be the case.
@export(implementation)
public subscript(_ position: Index) -> Element {
@_transparent
borrow {
_checkIndex(position)
return unsafe self[unchecked: position]
}
}
Btw, does anyone know if there's some magic involved in generating swift interfaces of types providing _unsafeAddress accessors (e.g., by turning them into borrow accessors, which would have roughly the same effect on the call site)?