From 8b6eb87b12c3d9f9a4ae731d3c2732978568fc37 Mon Sep 17 00:00:00 2001 From: Michael Ilseman Date: Tue, 26 Apr 2022 07:34:39 -0600 Subject: [PATCH] Mention language level pattern matching --- .../Evolution/StringProcessingAlgorithms.md | 38 +++++++++++++++++++ Tests/RegexBuilderTests/AlgorithmsTests.swift | 3 ++ 2 files changed, 41 insertions(+) diff --git a/Documentation/Evolution/StringProcessingAlgorithms.md b/Documentation/Evolution/StringProcessingAlgorithms.md index 001ce1fec..8106281ca 100644 --- a/Documentation/Evolution/StringProcessingAlgorithms.md +++ b/Documentation/Evolution/StringProcessingAlgorithms.md @@ -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 @@ -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 diff --git a/Tests/RegexBuilderTests/AlgorithmsTests.swift b/Tests/RegexBuilderTests/AlgorithmsTests.swift index 220535e31..173d41598 100644 --- a/Tests/RegexBuilderTests/AlgorithmsTests.swift +++ b/Tests/RegexBuilderTests/AlgorithmsTests.swift @@ -116,6 +116,9 @@ class RegexConsumerTests: XCTestCase { }: XCTFail() + case OneOrMore { CharacterClass.whitespace }: + XCTFail() + case "abc": XCTFail()