Throwing error in `init` is "conditional initialization" of noncopyable types?

Maybe related: SE-0429: Partial Consumption

The code below doesn't compile, and as I understand, it's because the failure code path (guard clause) doesn't initialize the struct's properties, while the success path does.

// ERROR: Conditional initialization or destruction of noncopyable types is not supported; this variable must be consistently in an initialized or uninitialized state through every code path
public struct Device: ~Copyable {
    public var device: USBDevice
    public var serialNumber: String?

    public init(...) throws {
        let devices = try? Self.usb.getDevices { ... }
        
        guard var devices, let device = devices.popLast() else {
            throw DeviceError.deviceNotFound
        }
        
        self.device = consume device
        self.serialNumber = self.device?.serialNumber
        
        try self.device.open()
    }
}

I can work around it by doing this:

public var device: USBDevice! // Changed to implicitly unwrapped Optional
// ... ///
guard var devices, let device = devices.popLast() else {
    self.device = nil
    self.serialNumber = nil
    throw DeviceError.deviceNotFound
}

but is this a necessary restriction?

I don't know what happens under the hood when ~Copyable types are initialized and discarded, but exiting via throwing an error means the partially-initialized struct is promptly discarded anyways. Does it really need to make sure that everything has the exact same shape?

It doesn't give me an error if I do actually initialize every property before any possible exit. This code isn't a correct behavior, but at least this does compile.

public struct Device: ~Copyable {
    public var device: USBDevice
    public var serialNumber: String?

    public init(...) throws {
        var devices = try? Self.usb.getDevices { ... }
        
        self.device = devices!.popLast()
        self.serialNumber = device?.serialNumber
        
        guard false else {
            throw DeviceError.deviceNotFound
        }
        
        try self.device.open()
    }
}

Maybe this is something that the language design needs to address?

If you break the initialization into two steps, one of which only delegates to another init, and another which always initializes all properties, you can work around this issue:

public struct Device: ~Copyable {
    public var device: USBDevice
    public var serialNumber: String?

    public init() throws {
        let devices = try? Self.usbGetDevices()
        
        guard var devices, let device = devices.popLast() else {
            throw DeviceError.deviceNotFound
        }

        try self.init(device: device)
    }

    private init(device: consuming USBDevice) throws {
        self.device = consume device
        self.serialNumber = self.device.serialNumber
        
        try self.device.open()
    }

    static func usbGetDevices() throws -> [USBDevice] {
        [USBDevice()]
    }
}

public struct USBDevice {
    var serialNumber: String? { "123" }
    func open() throws {}
}

enum DeviceError: Error {
    case deviceNotFound
}
2 Likes

Learner question: But, why does this work?

I suspect it’s because delegating to self.init(...) initializes self all in one step. There are really two kinds of initializers: ones that initialize all stored properties one at a time, and ones that delegate to another initializer. You can’t mix them:

init() { // this is invalid
  if condition {
    self.x = 3
  } else {
    self.init(x: 4)
  }
}
3 Likes

If I had to guess, it's because non-copyable structs can have deinits, and they want to make sure the deinit can be called if the init throws after initializing member variables.

1 Like

Now this looks much better than my workaround. I wasn't sure about readability on mine, since the reader wouldn't know that is a weird workaround, but yours looks natural. Thanks!

1 Like

Okay, I tested some random things, and this is weirder than I thought.

Because this compiles:

enum InitError: Error {
    case incorrectValue
}

struct Test: ~Copyable {
    var someNumber: Int
    var someString: String
    
    init(inputNumber: Int, inputString: String) throws {
        someNumber = inputNumber
        
        guard inputString == "random string" else {
            throw InitError.incorrectValue
        }
        
        someString = inputString
    }

    deinit { print("deinit") }
}

but this doesn't:

enum InitError: Error {
    case incorrectValue
}

struct Test: ~Copyable {
    var someNumber: Int
    var someString: String
    
    init(inputNumber: Int, inputString: String) throws {
        guard inputNumber == 1234 else {
            throw InitError.incorrectValue
        }
        
        someNumber = inputNumber
        
        guard inputString == "random string" else {
            throw InitError.incorrectValue
        }
        
        someString = inputString
    }

    deinit { print("deinit") }
}

In both cases, the failure path makes this struct partially initialized. But as long as every failure path has the same members initialized, and others uninitialized, it compiles. So it's okay to randomly put more throwing function calls in between someNumber and someString assignments.

I tested this too, and like you said it does call deinit even inside an initializer when all of the members are initialized, and it doesn't call deinit when only some of the members are initialized. So it knows how to deal with partially initialized early exits, but only works when every early exit has the same initialized members, and the same uninitialized members.

I don't know what to think of this, but at the very least I think the error message needs to be a bit more clear.

3 Likes