nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.62k stars 623 forks source link

os_log string interpolation self removal breaks compilation #1715

Closed alistra closed 3 weeks ago

alistra commented 1 month ago

I tried to format this file

  import os.log
  import Foundation

  class BugThree {

      let request: URLRequest

      init(request: URLRequest) {
          self.request = request
      }

      func bugMethod() {
          os_log("🛑🛑🛑 ATTENTION REQUIRED 🛑🛑🛑\nURL: \(self.request.url?.absoluteString ?? "<nil>") requested during tests\nPlease fix this to not use net working in tests")

      }
  }

with this version

❯ swiftformat --version
0.53.10

and it resulted in this file (self removed)

  import Foundation
  import os.log

  class BugThree {
      let request: URLRequest

      init(request: URLRequest) {
          self.request = request
      }

      func bugMethod() {
          os_log("🛑🛑🛑 ATTENTION REQUIRED 🛑🛑🛑\nURL: \(request.url?.absoluteString ?? "<nil>") requested during tests\nPlease fix this to not use net working in tests")
      }
  }

and now it doesn't compile with error:

❯ swiftc bug3.swift
bug3.swift:12:70: error: reference to property 'request' in closure requires explicit use of 'self' to make capture semantics explicit
        os_log("🛑🛑🛑 ATTENTION REQUIRED 🛑🛑🛑\nURL: \(request.url?.absoluteString ?? "<nil>") requested during tests\nPlease fix this to not use net working in tests")
bug3.swift:12:70: note: reference 'self.' explicitly
        os_log("🛑🛑🛑 ATTENTION REQUIRED 🛑🛑🛑\nURL: \(request.url?.absoluteString ?? "<nil>") requested during tests\nPlease fix this to not use net working in tests")
error: fatalError

TBH I have no idea why it behaves like this - I thought it was maybe because of @autoclosure but it is not it. For other methods it works properly, it must be something about os_log that forces the self to be required.

nicklockwood commented 4 weeks ago

@alistra I suspect that os_log's string interpolation does make use of @autoclosure somehow, but in any case the solution should be to add --selfrequired os_log to your SwiftFormat config. I'll add os_log to the default exclusion list in the next version.

nicklockwood commented 3 weeks ago

@alistra fixed in 0.54.0