Skip to content

Compiler fails to prevent accessing protocol extension members on consumed values #83277

@rayx

Description

@rayx

Description

After a value is consumed, it's still possible to access protocol extension members on it. This happens for both protocol required members and non-required members, as long as they are not shadowed by struct's own implemenations.

Reproduction

My original example:

func test() {
    let values = [1, 2, 3]
    var newValues = consume values
    newValues.append(4)
    
    //print(values.count) // this doesn't compile (as expected)
    //print(values[0]) // this doesn't compile (as expected)
    print(values.first!) // output: 1
    print(values.last!) // output: 3
}

User CrystDragon in Swift forums identified the general pattern to reproduce it:

protocol P {
    func bar() 
}
extension P {
    func bar() {}
    func baz() {}
}

struct A: P {
    let x: String = ""

    func foo() {}
}

func test() {
    let a = A()
    _ = consume a

    a.foo() // error, as expected
    a.bar() // no error, not as expected
    a.baz() // no error, not as expected
}

Expected behavior

Compile should produce error

Environment

$ swift --version
Swift version 6.2-dev (LLVM 5fbc818cf26c90b, Swift 2e18973)
Target: x86_64-unknown-linux-gnu
Build config: +assertions

Additional information

Just in case some people might think P.bar() works because P has no data requirement, compiler fails to generate diagnostic for the following code too.

protocol P {
    var x: String { get }
    func bar()
}

extension P {
    func bar() { print(x) }
}

struct A: P {
    let x: String = ""
}

func test() {
    let a = A()
    _ = consume a

    a.bar() // no error, not as expected
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.regressionswift 6.2triage neededThis issue needs more specific labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions