Fixed kleene star behavior, which used to behave like a '+'

This commit is contained in:
2024-10-23 08:51:40 -04:00
parent 2cd43bf2a1
commit 9d3bc2b804
3 changed files with 34 additions and 12 deletions

19
main.go
View File

@@ -9,7 +9,6 @@ import (
)
const CONCAT rune = '~'
const UNION int = 0
func isOperator(c rune) bool {
if c == '*' || c == '|' || c == CONCAT {
@@ -126,15 +125,19 @@ func thompson(re string) *State {
}
s1.output = s2.output
nfa = append(nfa, s1)
case '*':
case '*': // Create a 0-state, concat the popped state after it, concat the 0-state after the popped state
s1 := pop(&nfa)
stateToAdd := &State{}
stateToAdd.transitions = make(map[int][]*State)
stateToAdd.content = EPSILON
stateToAdd.isEmpty = true
stateToAdd.isKleene = true
stateToAdd.output = append(stateToAdd.output, stateToAdd)
for i := range s1.output {
s1.output[i].transitions[s1.content] = append(s1.output[i].transitions[s1.content], s1)
s1.output[i].transitions[stateToAdd.content] = append(s1.output[i].transitions[stateToAdd.content], stateToAdd)
}
// Reset output to s1 (in case s1 was a union operator state, which has multiple outputs)
s1.output = nil
s1.output = append(s1.output, s1)
nfa = append(nfa, s1)
stateToAdd.transitions[s1.content] = append(stateToAdd.transitions[s1.content], s1)
nfa = append(nfa, stateToAdd)
case '|':
s1 := pop(&nfa)
s2 := pop(&nfa)
@@ -143,7 +146,7 @@ func thompson(re string) *State {
s3.output = append(s3.output, s1, s2)
s3.transitions[s1.content] = append(s3.transitions[s1.content], s1)
s3.transitions[s2.content] = append(s3.transitions[s2.content], s2)
s3.content = UNION
s3.content = EPSILON
s3.isEmpty = true
nfa = append(nfa, &s3)