Skip to content
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
9 changes: 7 additions & 2 deletions Sources/_StringProcessing/Regex/AnyRegexOutput.swift
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,12 @@ extension AnyRegexOutput.ElementRepresentation {
}

var type: Any.Type {
content?.value.map { Swift.type(of: $0) }
?? TypeConstruction.optionalType(of: Substring.self, depth: optionalDepth)
func wrapIfNecessary<U>(_: U.Type) -> Any.Type {
TypeConstruction.optionalType(of: U.self, depth: optionalDepth)
}

return content?.value.map {
_openExistential(Swift.type(of: $0), do: wrapIfNecessary)
} ?? TypeConstruction.optionalType(of: Substring.self, depth: optionalDepth)
}
}
53 changes: 53 additions & 0 deletions Tests/RegexBuilderTests/RegexDSLTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1962,6 +1962,59 @@ extension RegexDSLTests {
XCTAssertNotNil(clip.contains(pattern))
XCTAssertNotNil(clip2.contains(pattern))
}

func testIssue83022() throws {
// Original report from https://github.com/swiftlang/swift/issues/83022
// rdar://155710126
let mixedNumberRegex = Regex {
// whole number
Optionally {
Capture {
OneOrMore(.digit)
} transform: { Int($0)! }
OneOrMore { " " }
}
// numerator
Capture {
OneOrMore(.digit)
} transform: { Int($0)! }
"/"
// denominator (modified to test for double optional)
Capture {
OneOrMore(.digit)
} transform: { Optional.some(Int($0)) }
}

do {
let match = try XCTUnwrap(mixedNumberRegex.wholeMatch(in: "1 3/4"))
XCTAssertEqual(match.1, 1)
XCTAssertEqual(match.2, 3)
XCTAssertEqual(match.3, 4)

let erasedMatch = Regex<AnyRegexOutput>.Match(match)
XCTAssert(erasedMatch.output[0].type == Substring.self)
XCTAssert(erasedMatch.output[1].type == Int?.self)
XCTAssert(erasedMatch.output[2].type == Int.self)
XCTAssert(erasedMatch.output[3].type == Int??.self)
}

do {
let match = try XCTUnwrap(mixedNumberRegex.wholeMatch(in: "3/4"))
XCTAssertNil(match.1)
XCTAssertEqual(match.2, 3)
XCTAssertEqual(match.3, 4)

let erasedMatch = Regex<AnyRegexOutput>.Match(match)
XCTAssert(erasedMatch.output[0].type == Substring.self)
XCTAssert(erasedMatch.output[2].type == Int.self)
XCTAssert(erasedMatch.output[3].type == Int??.self)

XCTExpectFailure {
// `nil` value is interpreted as `Substring?` instead of `Int?`
XCTAssert(erasedMatch.output[1].type == Int?.self)
}
}
}
}

extension Unicode.Scalar {
Expand Down