Skip to content

Mention language level pattern matching #354

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Documentation/Evolution/StringProcessingAlgorithms.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,31 @@ We also propose the following regex-powered algorithms as well as their generic
|`prefixMatch(of:)`| Matches the specified `RegexComponent` against the collection at the beginning |
|`matches(of:)`| Returns a collection containing all matches of the specified `RegexComponent` |

We also propose an overload of `~=` allowing regexes to be used in `case` expressions:

```swift
switch "abcde" {
case /a.*f/: // never taken
case /abc/: // never taken
case /ab.*e/: return "success"
default: // never taken
}

switch "2022-04-22" {
case decimalParser: // never taken

case OneOrMore {
CharacterClass.whitespace
}: // never taken

case #/\d{2}/\d{2}/\d{4}/# // never taken

case dateParser: return "success"

default: // never taken
}
```


## Detailed design

Expand Down Expand Up @@ -1025,6 +1050,19 @@ extension RangeReplaceableCollection where Element: Equatable {
}
```

### Language-level pattern matching via `~=`

We propose allowing any regex component be used in case statements by overloading the `~=` operator for matching against the entire input:

```swift
extension RegexComponent {
public static func ~=(regex: Self, input: String) -> Bool

public static func ~=(regex: Self, input: Substring) -> Bool
}
```


[SE-0346]: https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md
[stdlib-pitch]: https://forums.swift.org/t/pitch-primary-associated-types-in-the-standard-library/56426

Expand Down
3 changes: 3 additions & 0 deletions Tests/RegexBuilderTests/AlgorithmsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ class RegexConsumerTests: XCTestCase {
}:
XCTFail()

case OneOrMore { CharacterClass.whitespace }:
XCTFail()

case "abc":
XCTFail()

Expand Down