Skip to content

Accessing computed property sometimes causes unexpected consume of borrowed value #73292

@ORBAT

Description

@ORBAT

Description

I've found two cases of values getting consumed when reading computed properties, and they seem like they're not correct behavior based on my reading of SE-0377 and SE-0390.

  • case 1 is a method with a borrowed some Proto parameter calling a getter on the borrowed value
  • case 2 is a borrowing method in a struct A<T> that has a stored property v: T

Reproduction

Case 1: borrowed parameter with opaque type

struct Example {
  protocol Proto {
    // doesn't work with { borrowing get } either
    var count: Int { get }
  }

  func takeProto(_ p: borrowing some Proto) -> Int {
    p.count
  }
}

Result is

error: 'p' is borrowed and cannot be consumed
  func takeProto(_ p: borrowing some Proto) -> Int {
                   ^

note: consumed here
    p.count
      ^

Interestingly using p: borrowing any Proto leads to a different error. Should I make another issue for this as the error suggests?

error: usage of no-implicit-copy value that the compiler can't verify. 
This is a compiler bug. Please file a bug with a small example of the bug

Case 2: borrowing method in a generic struct with stored property of generic type

struct Broken<Base> {
  let base: Base
  var compd: Int { 666 }
  borrowing func doSomething() -> Int { compd }
}
error: 'self' is borrowed and cannot be consumed
  borrowing func doSomething() -> Int { compd }
                 ^
note: consumed here
  borrowing func doSomething() -> Int { compd }
                                        ^

Expected behavior

Case 1

Expected no error

Case 2

Expected no error, like in the following cases that compile fine:

class Class<Base> {
  let base: Base
  var computed: Int { 666 } 

  borrowing func doSomething() -> Int { computed }

  init(base: Base) {
    self.base = base
  }
}

struct NoProp<Base> {
  var computed: Int { 666 }
  borrowing func doSomething() -> Int { computed }
}

struct NotGeneric {
  var computed: Int { 666 }
  borrowing func doSomething() -> Int { computed }
}

Environment

swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

Additional information

Forum post

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.ownershipFeature: Ownership modifiers and semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions