swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.27k stars 10.33k forks source link

An `init` declaration inside computed property of function type crashes compiler #67477

Open thecrypticace opened 1 year ago

thecrypticace commented 1 year ago

Description An init declaration inside a computed property crashes the compiler when said property has a function type. I had no idea these declarations were valid Swift but they're emitted by the @ObservationTracked macro but you can reproduce this error without using it and without importing any frameworks.

Steps to reproduce

Shortest repro (using Observation + macros in Xcode 15b3):

import Observation

@Observable
class ThisCrashes1 {
  var content: (() -> Bool)? = nil
}

Minimal repro without Observation or macros:

class ThisCrashes2 {
  var content: (() -> Bool)? {
    // This init declaration is the cause of the crash
    // Only for function types
    // For example `Bool?` does not crash
    // While `(() -> Bool)?` does
    // If you comment it out the crash no longer happens
    init(initialValue) initializes (_content) {
      _content = initialValue
    }

    get {
      return _content
    }

    set {
      _content = newValue
    }
  }

  private var _content: (() -> Bool)? = nil
}

I also have a repro that involves Swift UI. I assume the underlying cause is the same however the stack trace output is different so I figured it might also be useful:

import SwiftUI
import Observation

@Observable
class ThisCrashes1 {
  var content: (() -> any View)? = nil
}

Expected behavior The compiler doesn't crash. Maybe there's a build error (not sure if the above is supposed to be valid or not). But it definitely shouldn't crash.

Environment

Additional context

Here's the stack traces for all three repros above: https://gist.github.com/thecrypticace/756927dde4d6722c1359a53bc468a972

xedin commented 1 year ago

This issue has been fixed by https://github.com/apple/swift/pull/67312 and cherry-picked into 5.9