Skip to content
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

Swift Regex Builders will crash if a named capture group is optional #623

Open
schwa opened this issue Dec 22, 2022 · 1 comment
Open

Swift Regex Builders will crash if a named capture group is optional #623

schwa opened this issue Dec 22, 2022 · 1 comment
Labels
bug Something isn't working

Comments

@schwa
Copy link

schwa commented Dec 22, 2022

macOS X 13.1 (22C65)
Xcode Version 14.1 (14B47b)

The following code that uses a Regex Builder will crash at runtime when the user tries to get the result of an optional capture group via the regex match subscript. The same regex using a regex literal successfully returns an optional (but nil) value. You can generate the result builder from the literal if needed.

import Foundation
import RegexBuilder

// Case 1 - using regex literals. Works

let regex1 = #/\s*(?<label>\w+:)?/#

guard let match1 = "NOP".firstMatch(of: regex1) else {
    fatalError()
}
print(match1.output.label) // Should be nil. Is nil!

// #######################

// Case 2 - using regex builder. Crashes.

let label = Reference(Substring.self)
let regex2 = Regex {
    ZeroOrMore(.whitespace)
    Optionally {
        Capture(as: label) {
            Regex {
                OneOrMore(.word)
                ":"
            }
        }
    }
}

guard let match2 = "NOP".firstMatch(of: regex2) else {
    fatalError()
}
print(match2[label])  // Should be nil. Crashes with "Could not cast value of type 'Swift.Optional<Swift.Substring>' (0x....) to 'Swift.Substring' (0x....)."
@schwa schwa added the bug Something isn't working label Dec 22, 2022
@hamishknight hamishknight transferred this issue from swiftlang/swift Dec 22, 2022
@hamishknight
Copy link
Contributor

cc @milseman

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants