More Kleene star fixes

This commit is contained in:
2024-10-23 10:26:50 -04:00
parent 9d3bc2b804
commit 11dd6aeb7c
3 changed files with 36 additions and 10 deletions

View File

@@ -1,5 +1,22 @@
package main
// takeZeroState takes the 0-state (if such a transition exists) for all states in the
// given slice. It returns the resulting states. If any of the resulting states is a 0-state,
// the second parameter is true.
func takeZeroState(states []*State) (rtv []*State, isZero bool) {
for _, state := range states {
if len(state.transitions[EPSILON]) > 0 {
rtv = append(rtv, state.transitions[EPSILON]...)
}
}
for _, state := range rtv {
if len(state.transitions[EPSILON]) > 0 {
return rtv, true
}
}
return rtv, false
}
// match tries to match the regex represented by given start-state, with
// the given string
func match(start *State, str string) (startIdx int, endIdx int, matched bool) {
@@ -18,14 +35,16 @@ func match(start *State, str string) (startIdx int, endIdx int, matched bool) {
// Main loop
for i < len(str) {
// If there are any 0-transitions, take those
// TODO: Maybe I need to keep taking 0-transitions until I don't have anymore. Needs to be tested
for _, state := range currentStates {
if len(state.transitions[EPSILON]) > 0 {
tempStates = append(tempStates, state.transitions[EPSILON]...)
}
zeroStates := make([]*State, 0)
// Keep taking zero-states, until there are no more left to take
zeroStates, isZero := takeZeroState(currentStates)
tempStates = append(tempStates, zeroStates...)
for isZero == true {
zeroStates, isZero = takeZeroState(tempStates)
tempStates = append(tempStates, zeroStates...)
}
copy(currentStates, tempStates)
currentStates = append(currentStates, tempStates...)
tempStates = nil
// Take any transitions corresponding to current character
@@ -40,6 +59,7 @@ func match(start *State, str string) (startIdx int, endIdx int, matched bool) {
}
}
}
currentStates = make([]*State, len(tempStates))
copy(currentStates, tempStates)
tempStates = nil
@@ -52,7 +72,7 @@ func match(start *State, str string) (startIdx int, endIdx int, matched bool) {
tempStates = append(tempStates, state.transitions[EPSILON]...)
}
}
copy(currentStates, tempStates)
currentStates = append(currentStates, tempStates...)
tempStates = nil
for _, state := range currentStates {