Cotton code
141 lines · 6.5 KB · SwiftRaw
// An Objective-C completion that answers off the main queue is never handed a// main-actor closure.//// **This is a crash, not a warning.** `SystemSpeechRecogniser` is `@MainActor`,// and it asked for speech permission like this:////     await withCheckedContinuation { continuation in//         SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0) }//     }//// The completion closure inherited the type's isolation, so Swift 6 compiled a// main-queue assertion into its entry — and `requestAuthorization` answers on an// arbitrary queue. libdispatch logged "BUG IN CLIENT OF LIBDISPATCH: Assertion// failed: Block was expected to execute on queue [com.apple.main-thread]" and// the process took SIGTRAP. No error screen, no Bugsink event: the app simply// vanished to the home screen, every single time somebody who had declined// dictation touched the microphone.//// 4l's walk found it on `/take`. The fix is one keyword (`nonisolated`), which// is exactly the kind of fix that gets undone by a later tidy-up — so this// sweeps for the shape rather than trusting the comment beside it.//// The list is the completion APIs this app calls that Apple documents as// answering on an unspecified queue. A new one is added here in the same change// that introduces it; a call to one of these from inside a main-actor type must// either be `nonisolated` or hop with `MainActor.assumeIsolated`, and this test// is what says so out loud.import Foundationimport XCTestfinal class SpeechPermissionIsolationTests: XCTestCase {    /// Objective-C completion APIs that call back on an arbitrary queue.    private static let offMainQueue = [        "SFSpeechRecognizer.requestAuthorization",        "AVCaptureDevice.requestAccess",    ]    func testEveryOffQueueCompletionSitsInNonisolatedOrAssumedCode() throws {        var offenders: [String] = []        for source in try AppSources.all() {            for api in Self.offMainQueue {                for line in Self.lineNumbers(of: api, in: source.text) {                    let declaration = Self.enclosingDeclaration(of: line, in: source.text)                    let safe =                        // Written out of the closure's isolation …                        declaration.contains("nonisolated")                        // … or hopped deliberately, either back to the main                        // actor or onto the object's own serial queue.                        || declaration.contains("MainActor.assumeIsolated")                        || declaration.contains(".async {")                        // … or the enclosing type is not main-actor isolated at                        // all, so there is no assertion to fail.                        // `PairingMedia`'s coordinator is the case: `@unchecked                        // Sendable` on its own queue, and it says why.                        || !Self.enclosingTypeIsMainActor(of: line, in: source.text)                    if !safe {                        offenders.append("\(source.name):\(line + 1) calls \(api)")                    }                }            }        }        XCTAssertEqual(            offenders, [],            """            This completion answers on an arbitrary queue. Handing it a \            main-actor closure compiles a main-queue assertion into the \            closure's entry, and the process takes SIGTRAP the first time \            Apple answers off the main thread — an app that vanishes, with no \            error and no crash report the person can see. Put the call in a \            `nonisolated` function, or hop deliberately.            """        )    }    /// Whether the type this line sits in is `@MainActor`.    ///    /// A type that is not main-actor isolated compiles no queue assertion into    /// its closures, so an off-queue completion is simply ordinary code there.    /// Walked backwards to the nearest type declaration, then up over its    /// attributes — which is where `@MainActor` is written.    private static func enclosingTypeIsMainActor(of line: Int, in text: String) -> Bool {        let lines = text.split(separator: "\n", omittingEmptySubsequences: false)        var index = line        while index > 0 {            let candidate = lines[index].trimmingCharacters(in: .whitespaces)            let isType =                ["class ", "struct ", "actor ", "enum ", "extension "]                .contains { candidate.contains($0) && candidate.hasSuffix("{") }            if isType {                if candidate.contains("@MainActor") { return true }                var above = index - 1                while above >= 0 {                    let attribute = lines[above].trimmingCharacters(in: .whitespaces)                    if attribute.hasPrefix("@") {                         if attribute.contains("MainActor") { return true }                        above -= 1                        continue                    }                    if attribute.isEmpty || attribute.hasPrefix("//") {                        above -= 1                        continue                    }                    break                }                return false            }            index -= 1        }        return false    }    /// The zero-based lines mentioning `api`, comments excluded — a rule written    /// down beside the rule it keeps must not fail it.    private static func lineNumbers(of api: String, in text: String) -> [Int] {        text.split(separator: "\n", omittingEmptySubsequences: false).enumerated()            .filter { _, line in                let trimmed = line.trimmingCharacters(in: .whitespaces)                return !trimmed.hasPrefix("//") && !trimmed.hasPrefix("///")                    && line.contains(api)            }            .map(\.offset)    }    /// The `func`/`var`/`init` the line sits in, plus the lines above it back to    /// that declaration — which is where `nonisolated` would be written.    private static func enclosingDeclaration(of line: Int, in text: String) -> String {        let lines = text.split(separator: "\n", omittingEmptySubsequences: false)        var start = line        while start > 0 {            let candidate = lines[start].trimmingCharacters(in: .whitespaces)            if candidate.contains("func ") || candidate.hasPrefix("init(")                || candidate.contains(" var ")            {                break            }            start -= 1        }        return lines[start...line].joined(separator: "\n")    }}