Skip to content

Commit a3b5a71

Browse files
committed
Better diagnose unsupported group conditions
1 parent 5abd9b5 commit a3b5a71

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

Sources/_MatchingEngine/Regex/Parse/Diagnostics.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ enum ParseError: Error, Hashable {
2929
case misc(String)
3030

3131
case tooManyBranchesInConditional(Int)
32+
case unsupportedCondition(String)
3233

3334
case expectedASCII(Character)
3435

@@ -81,6 +82,8 @@ extension ParseError: CustomStringConvertible {
8182
return "cannot refer to whole pattern here"
8283
case let .tooManyBranchesInConditional(i):
8384
return "expected 2 branches in conditional, have \(i)"
85+
case let .unsupportedCondition(str):
86+
return "\(str) cannot be used as condition"
8487
case let .unknownGroupKind(str):
8588
return "unknown group kind '(\(str)'"
8689
case let .invalidMatchingOption(c):

Sources/_MatchingEngine/Regex/Parse/LexicalAnalysis.swift

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -872,10 +872,16 @@ extension Source {
872872
///
873873
mutating func lexGroupConditionalStart() throws -> Located<AST.Group.Kind>? {
874874
try tryEating { src in
875-
guard src.tryEat(sequence: "(?"),
876-
let group = try src.lexGroupStart(),
877-
!group.value.hasImplicitScope
875+
guard src.tryEat(sequence: "(?"), let group = try src.lexGroupStart()
878876
else { return nil }
877+
878+
// Implicitly scoped groups are not supported here.
879+
guard !group.value.hasImplicitScope else {
880+
throw LocatedError(
881+
ParseError.unsupportedCondition("implicitly scoped group"),
882+
group.location
883+
)
884+
}
879885
return group
880886
}
881887
}

Tests/RegexTests/ParseTests.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1276,5 +1276,6 @@ extension RegexTests {
12761276

12771277
diagnosticTest(#"(?(1)a|b|c)"#, .tooManyBranchesInConditional(3))
12781278
diagnosticTest(#"(?(1)||)"#, .tooManyBranchesInConditional(3))
1279+
diagnosticTest(#"(?(?i))"#, .unsupportedCondition("implicitly scoped group"))
12791280
}
12801281
}

0 commit comments

Comments
 (0)