Skip to content

Commit 69c375f

Browse files
rxweihamishknight
authored andcommitted
Make unary builder return Regex type consistently.
Currently, unary regex component builder simply forwards the component's base type. However, this is inconsistent with non-unary builder results. The current behavior may lead to surprising results when the user marks a property with `@RegexComponentBuilder`. This patch makes `RegexComponentBuilder.buildPartialBlock<R>(first: R)` return a `Regex<R.RegexOutput>` rather than `R` itself. --- Before: ```swift // error: cannot convert value of type 'OneOrMore<Substring>' to specified type 'Regex<Substring>' @RegexComponentBuilder var r: Regex<Substring> { OneOrMore("a") // Adding other components below will make the error go away. } struct MyCustomRegex: RegexComponent { // error: cannot convert value of type 'OneOrMore<Substring>' to specified type 'Regex<Substring>' var regex: Regex<Substring> { OneOrMore("a") } } ``` After: No errors.
1 parent 857b6f3 commit 69c375f

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

Sources/RegexBuilder/Builder.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ public enum RegexComponentBuilder {
1818
_RegexFactory().empty()
1919
}
2020

21-
public static func buildPartialBlock<R: RegexComponent>(first: R ) -> R {
22-
first
21+
public static func buildPartialBlock<R: RegexComponent>(
22+
first component: R
23+
) -> Regex<R.RegexOutput> {
24+
component.regex
2325
}
2426

2527
public static func buildExpression<R: RegexComponent>(_ regex: R) -> R {

Tests/RegexBuilderTests/RegexDSLTests.swift

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1052,7 +1052,7 @@ class RegexDSLTests: XCTestCase {
10521052
XCTAssertEqual(str.wholeMatch(of: parser)?.1, version)
10531053
}
10541054
}
1055-
1055+
10561056
func testZeroWidthConsumer() throws {
10571057
struct Trace: CustomConsumingRegexComponent {
10581058
typealias RegexOutput = Void
@@ -1088,6 +1088,26 @@ class RegexDSLTests: XCTestCase {
10881088
10891089
""")
10901090
}
1091+
1092+
func testRegexComponentBuilderResultType() {
1093+
// Test that the user can declare a closure or computed property marked with
1094+
// `@RegexComponentBuilder` with `Regex` as the result type.
1095+
@RegexComponentBuilder
1096+
var unaryWithSingleNonRegex: Regex<Substring> {
1097+
OneOrMore("a")
1098+
}
1099+
@RegexComponentBuilder
1100+
var multiComponent: Regex<Substring> {
1101+
OneOrMore("a")
1102+
"b"
1103+
}
1104+
struct MyCustomRegex: RegexComponent {
1105+
@RegexComponentBuilder
1106+
var regex: Regex<Substring> {
1107+
OneOrMore("a")
1108+
}
1109+
}
1110+
}
10911111
}
10921112

10931113
extension Unicode.Scalar {

0 commit comments

Comments
 (0)