SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

Swift 5.7 regex literal with braces incorrectly triggers opening_brace rule.

Open chriseplettsonos opened this issue 3 years ago • 2 comments

New Issue Checklist

Describe the bug

We are using the opening_brace rule, and getting a false positive within a Swift 5.7 regex literal containing braces.

Complete output when running SwiftLint, including the stack trace and command used
$ swiftlint lint
[...]
redacted.swift:14:31: warning: Opening Brace Spacing Violation: Opening braces should be preceded by a single space and on the same line as the declaration. (opening_brace)
[...]

Environment

  • SwiftLint v0.50.1
  • Installation via Homebrew
  • Paste your configuration file:
disabled_rules:
  - trailing_comma
  - todo
type_name:
  excluded: ID
excluded:
  - .build/
  • No nested configurations
  • Xcode 14.1, build 14B47b
  • This triggers the rule incorrectly:
// This triggers a violation:
let pattern = #/(\{(?<key>\w+)\})/#

chriseplettsonos avatar Nov 30 '22 20:11 chriseplettsonos

I've also seen it trigger other rules like comma and colon when those characters are inside a pattern like [:,]+.

wmswms avatar Dec 08 '22 14:12 wmswms

Ran into this myself now.

echo "let regex = /((?:E(?<first_group>-*[0-9]{1,3})))*/" | swiftlint lint --no-cache --use-stdin --enable-all-rules --autocorrect

Produces

let regex = /((?:E(?<first_group >-*[0-9] {1,3})))*/

Done correcting 1 file!

Note the whitespace added between [0-9] and {1,3}. The original expression can be tested here https://regex101.com/r/1PP55T/1, and the linted expression here https://regex101.com/r/eCkbB3/1. The former produces a match under first_group, whereas the latter does not, which means we cannot invoke autocorrect on our project as it'll break our regex literals

sruncimanraileasy avatar Feb 01 '23 16:02 sruncimanraileasy

Ran into this myself now.

echo "let regex = /((?:E(?<first_group>-*[0-9]{1,3})))*/" | swiftlint lint --no-cache --use-stdin --enable-all-rules --autocorrect

Produces

let regex = /((?:E(?<first_group >-*[0-9] {1,3})))*/

Done correcting 1 file!

Note the whitespace added between [0-9] and {1,3}. The original expression can be tested here https://regex101.com/r/1PP55T/1, and the linted expression here https://regex101.com/r/eCkbB3/1. The former produces a match under first_group, whereas the latter does not, which means we cannot invoke autocorrect on our project as it'll break our regex literals

Use // swiftlint:disable:next opening_brace to bypass the false positive

d42ohpaz avatar Jul 03 '23 00:07 d42ohpaz