Skip to content

Commit

Permalink
Fix regex literal parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Dec 3, 2022
1 parent ce82120 commit 852b9af
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Snapshots/Issues/1269.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// switformat:options --swiftversion 5.7
// swiftformat:options --swiftversion 5.7

struct Foo<Value> {
func bar<V, R>(
Expand Down
4 changes: 4 additions & 0 deletions Snapshots/Issues/1319.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// swiftformat:options --swiftversion 5.7
// swiftformat:disable --redundantLet

let _ = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
6 changes: 1 addition & 5 deletions Sources/Tokenizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -812,12 +812,8 @@ private extension UnicodeScalarView {
var start = self
if var tail = readCharacter(where: isHead) {
switch tail {
case "?", "!", "\\":
case "/" where !["*", "/"].contains(first), "?", "!", "\\":
return .operator(String(tail), .none)
case "/":
if first == "\\" {
return .operator("/", .none)
}
default:
start = self
}
Expand Down
46 changes: 46 additions & 0 deletions Tests/TokenizerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,22 @@ class TokenizerTests: XCTestCase {
XCTAssertEqual(tokenize(input), output)
}

func testAnchoredSingleLineRegexLiteral() {
let input = "let _ = /^foo$/"
let output: [Token] = [
.keyword("let"),
.space(" "),
.identifier("_"),
.space(" "),
.operator("=", .infix),
.space(" "),
.startOfScope("/"),
.stringBody("^foo$"),
.endOfScope("/"),
]
XCTAssertEqual(tokenize(input), output)
}

func testSingleLineRegexLiteralStartingWithEscapeSequence() {
let input = "let regex = /\\w+/"
let output: [Token] = [
Expand Down Expand Up @@ -943,6 +959,36 @@ class TokenizerTests: XCTestCase {
XCTAssertEqual(tokenize(input), output)
}

func testPrefixSlashCaretOperator() {
let input = "let _ = /^foo"
let output: [Token] = [
.keyword("let"),
.space(" "),
.identifier("_"),
.space(" "),
.operator("=", .infix),
.space(" "),
.operator("/^", .prefix),
.identifier("foo"),
]
XCTAssertEqual(tokenize(input), output)
}

func testPrefixSlashQueryOperator() {
let input = "let _ = /?foo"
let output: [Token] = [
.keyword("let"),
.space(" "),
.identifier("_"),
.space(" "),
.operator("=", .infix),
.space(" "),
.operator("/?", .prefix),
.identifier("foo"),
]
XCTAssertEqual(tokenize(input), output)
}

// MARK: Single-line comments

func testSingleLineComment() {
Expand Down

0 comments on commit 852b9af

Please sign in to comment.