swiftlang / swiftlang/swift-experimental-string-processing
Swift Regex Builders will crash if a named capture group is optional
Nobody has claimed this yet.
- Dominant language
- Swift
- Stars
- 308
- Forks
- 52
- Avg merge
- 12h 45m
- Merged PRs (30d)
- 2
Description
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....)."
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied Swift reproducer with RegexBuilder, comparing the optional capture result from firstMatch and the match subscript. Trace the optional capture and Reference lookup path; done means an absent named capture returns nil instead of crashing, while the regex-literal behavior remains unchanged.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100