Repository navigation
Description
Description
A quantified group that can match the empty string can loop forever (or just grow until memory allocation fails) when the forward-progress analysis wrongly concludes that the body always advances.
let regex = try Regex(#"(?:.c|)*x"#)
print("b".matches(of: regex).count) // never returnsMore inputs that hang: (?:\sA|)*?x on "b", (?:[ab]c|)*x on "b". Some variants end with Fatal error: failed to allocate 3758096400 bytes of memory instead of hanging.
The same patterns finish at once in Swift on macOS (the OS's own _StringProcessing, which predates the flattened DSLList). I reproduced the hang with the Swift 6.4.0 SDK for WebAssembly, and with _StringProcessing built from the swift-6.4.0-RELEASE tag. It is still present on main.
Cause
In Sources/_StringProcessing/ByteCodeGen+DSLList.swift, _guaranteesForwardProgressImpl walks the flattened node list with an inout position cursor. For children it uses short-circuiting collection methods:
case .orderedChoice(let count):
return (0..<count).allSatisfy { _ in _guaranteesForwardProgressImpl(list, position: &position) }
case .concatenation(let count):
return (0..<count).contains { _ in _guaranteesForwardProgressImpl(list, position: &position) }When contains stops at the first child that guarantees progress, the remaining children are never visited, so position is left in the middle of the concatenation. The caller then reads the wrong node as the next sibling. In (?:.c|) the first alternative is .c: contains stops after ., the cursor is left on c, and that c is then read as the second (empty) alternative. That makes allSatisfy true, so the progress check is never emitted and the empty alternative loops. allSatisfy stopping at the first false causes the same problem.
Suggested fix
Visit every child, and move the cursor past each child's whole subtree, however much of it was needed to decide:
func _guaranteesForwardProgressOfChild(_ list: ArraySlice<DSLTree.Node>, position: inout Int) -> Bool {
var probe = position
let result = _guaranteesForwardProgressImpl(list, position: &probe)
list.skipNode(&position)
position += 1
return result
}
case .orderedChoice(let count):
var all = true
for _ in 0..<count where !_guaranteesForwardProgressOfChild(list, position: &position) { all = false }
return all
case .concatenation(let count):
var any = false
for _ in 0..<count where _guaranteesForwardProgressOfChild(list, position: &position) { any = true }
return anyWith this change, all the cases above give the same results as Swift on macOS (checked on several thousand random patterns). This is related to, but separate from, #872 (progress checks for bounded repetition).
Activity
Fix forward progress analysis losing its place in the node list (swif…