nicklockwood / SwiftFormat

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

Swiftformat parser fails on array subscripts in guard. #1113

Closed lhunath closed 2 years ago

lhunath commented 2 years ago

Input file:

enum X {
    case a, b
}

enum Y {
    case a, b
}

func y(x: X) -> Y? {
    guard let y: Y = [
        .a: .a,
        .b: .b,
    ][x]
    else { return nil }

    return y
}

print(y(x: .a) as Any)

Testing:

$ swift Sources/.test.swift
Optional(main.Y.a)

$ swiftformat -v Sources/.test.swift
Running SwiftFormat...
Reading config file at /Users/hubstaff/workspace/hubstaff/ios/.swiftformat
Formatting /Users/hubstaff/workspace/hubstaff/ios/Sources/.test.swift
-- error: Expected { on line 13
error: 1 file could not be formatted.

$ swift --version
swift-driver version: 1.26.21 Apple Swift version 5.5.2 (swiftlang-1300.0.47.5 clang-1300.0.29.30)
Target: x86_64-apple-macosx12.0

$ swiftformat --version
0.49.1
lhunath commented 2 years ago

Wrapping the subscript operation avoids the issue:

    guard let y: Y = ([
        .a: .a,
        .b: .b,
    ][x] ?? nil)
    else { return nil }
nicklockwood commented 2 years ago

Looks like a duplicate of https://github.com/nicklockwood/SwiftFormat/issues/1095

nicklockwood commented 2 years ago

@lhunath fixed in 0.49.2

lhunath commented 2 years ago
hubstaff@Ganymede ios $ swiftformat  --version
0.49.2
hubstaff@Ganymede ios $ swiftformat -v Sources/test.swift
Running SwiftFormat...
Reading config file at /Users/hubstaff/workspace/hubstaff/ios/.swiftformat
Formatting /Users/hubstaff/workspace/hubstaff/ios/Sources/test.swift
-- error: Expected { on line 13
error: 1 file could not be formatted.

SwiftFormat configuration: http://ix.io/3MGA test.swift is the input file as specified in the issue description.