-
Notifications
You must be signed in to change notification settings - Fork 0
/
automata.go
120 lines (90 loc) · 2.07 KB
/
automata.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package aautomata
import (
"fmt"
"strings"
)
type debug bool
func (d debug) print(i ...interface{}) {
if d {
fmt.Print(i...)
}
}
func (d debug) println(i ...interface{}) {
if d {
fmt.Println(i...)
}
}
func (d debug) printf(s string, i ...interface{}) {
if d {
fmt.Printf(s, i...)
}
}
type AdaptiveAutomata struct {
scanner *scanner
transitions *transitionCollection
state string
final map[string]bool
}
func NewAdaptiveAutomata() *AdaptiveAutomata {
return &AdaptiveAutomata{
newScanner(),
newTransitionCollection(),
"",
nil,
}
}
func (aa *AdaptiveAutomata) AddTransition(from, input, to string, b func(*AdaptiveAutomata), a func(*AdaptiveAutomata)) {
aa.transitions.Add(newTransition(from, input, to, b, a))
}
func (aa *AdaptiveAutomata) RemoveTransition(from, input string) {
aa.transitions.Remove(from, input)
}
func (aa *AdaptiveAutomata) SetState(s string) {
aa.state = s
}
func (aa *AdaptiveAutomata) SetFinalStates(s ...string) {
aa.final = make(map[string]bool)
for _, state := range s {
aa.final[state] = true
}
}
func (aa *AdaptiveAutomata) Run(input string, d ...bool) (string, bool) {
var debug debug
if len(d) > 0 && d[0] {
debug = true
}
debug.println("testing input ", input)
aa.scanner.Init(strings.NewReader(input))
var trans *transition
for aa.scanner.Scan() {
debug.printf("%v\t%v\t", aa.state, aa.scanner.Text())
state := aa.state
input := aa.scanner.Text()
trans = aa.transitions.Find(state, input)
if trans == nil {
debug.println("transition not found")
debug.println("")
return state, false
}
trans.ExecBefore(aa)
trans = aa.transitions.Find(state, input)
if trans == nil {
debug.println("transition not found")
debug.println("")
return state, false
}
trans.ExecAfter(aa)
aa.state = trans.to
debug.printf("%v\n", trans.to)
}
accept := aa.final[aa.state]
debug.println(aa.state, accept)
debug.println("")
return aa.state, accept
}
func (aa *AdaptiveAutomata) Push(s string) {
aa.scanner.Push(s)
}
func (aa *AdaptiveAutomata) Print() {
aa.transitions.Print()
}