File tree Expand file tree Collapse file tree 2 files changed +35
-13
lines changed
Sources/_StringProcessing Expand file tree Collapse file tree 2 files changed +35
-13
lines changed Original file line number Diff line number Diff line change @@ -17,23 +17,24 @@ func constructExistentialOutputComponent(
17
17
component: ( range: Range < String . Index > , value: Any ? ) ? ,
18
18
optionalCount: Int
19
19
) -> Any {
20
- let someCount : Int
21
- var underlying : Any
22
20
if let component = component {
23
- underlying = component. value ?? input [ component. range]
24
- someCount = optionalCount
21
+ var underlying = component. value ?? input [ component. range]
22
+ for _ in 0 ..< optionalCount {
23
+ func wrap< T> ( _ x: T ) {
24
+ underlying = Optional ( x) as Any
25
+ }
26
+ _openExistential ( underlying, do: wrap)
27
+ }
28
+ return underlying
25
29
} else {
26
- // Ok since we Any-box every step up the ladder
27
- underlying = Optional < Any > ( nil ) as Any
28
- someCount = optionalCount - 1
29
- }
30
- for _ in 0 ..< someCount {
31
- func wrap< T> ( _ x: T ) {
32
- underlying = Optional ( x) as Any
30
+ precondition ( optionalCount > 0 , " Must have optional type " )
31
+ func makeNil< T> ( _ x: T . Type ) -> Any {
32
+ T ? . none as Any
33
33
}
34
- _openExistential ( underlying, do: wrap)
34
+ let underlyingTy = TypeConstruction . optionalType (
35
+ of: Substring . self, depth: optionalCount - 1 )
36
+ return _openExistential ( underlyingTy, do: makeNil)
35
37
}
36
- return underlying
37
38
}
38
39
39
40
@available ( SwiftStdlib 5 . 7 , * )
Original file line number Diff line number Diff line change @@ -461,6 +461,8 @@ class RegexDSLTests: XCTestCase {
461
461
462
462
try _testDSLCaptures (
463
463
( " abcdef2 " , ( " abcdef2 " , " f " ) ) ,
464
+ ( " 2 " , ( " 2 " , nil ) ) ,
465
+ ( " " , ( " " , nil ) ) ,
464
466
matchType: ( Substring, Substring?? ) . self, == )
465
467
{
466
468
Optionally {
@@ -1262,6 +1264,25 @@ class RegexDSLTests: XCTestCase {
1262
1264
1263
1265
XCTAssertEqual ( try replace ( " {bar} " ) , " foo " )
1264
1266
}
1267
+
1268
+ func testOptionalNesting( ) throws {
1269
+ let r = Regex {
1270
+ Optionally {
1271
+ Optionally {
1272
+ Capture {
1273
+ " a "
1274
+ }
1275
+ }
1276
+ }
1277
+ }
1278
+ if let _ = try r. wholeMatch ( in: " " ) !. output. 1 {
1279
+ XCTFail ( " Unexpected capture match " )
1280
+ }
1281
+ if let _ = try r. wholeMatch ( in: " a " ) !. output. 1 { }
1282
+ else {
1283
+ XCTFail ( " Expected to match capture " )
1284
+ }
1285
+ }
1265
1286
}
1266
1287
1267
1288
extension Unicode . Scalar {
You can’t perform that action at this time.
0 commit comments