-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnfa.go
More file actions
214 lines (176 loc) · 6.02 KB
/
Copy pathnfa.go
File metadata and controls
214 lines (176 loc) · 6.02 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package ahocorasick
// OptimizedNFA represents an optimized Aho-Corasick automaton.
// Key optimizations:
// 1. Dense transitions: []StateID instead of map[byte]StateID
// 2. Precomputed root transitions: no failure link following for root
// 3. ByteClasses: reduced alphabet size
type OptimizedNFA struct {
// states stores all state data.
states []optState
// byteClasses maps bytes to equivalence classes.
byteClasses *ByteClasses
// alphabetLen is the number of equivalence classes.
alphabetLen int
// startState is the ID of the start state (always 0).
startState StateID
// matchKind specifies match semantics.
matchKind MatchKind
// patternCount is the number of patterns.
patternCount int
}
// optState represents an optimized state.
// Uses dense transitions for fast lookup.
type optState struct {
// trans is a dense transition table indexed by byte class.
// trans[class] = next state ID, or 0 if no transition (follow fail).
// For root state, all transitions are precomputed (no fail following needed).
trans []StateID
// fail is the failure link state ID.
fail StateID
// matches lists pattern IDs that match at this state.
matches []PatternID
// depth is the depth from root.
depth int
}
// buildOptimizedNFA constructs an optimized NFA from patterns.
func buildOptimizedNFA(patterns [][]byte, bc *ByteClasses, matchKind MatchKind) *OptimizedNFA {
alphabetLen := bc.NumClasses()
nfa := &OptimizedNFA{
byteClasses: bc,
alphabetLen: alphabetLen,
startState: 0,
matchKind: matchKind,
patternCount: len(patterns),
}
// Phase 1: Build trie from patterns
nfa.buildTrie(patterns)
// Phase 2: Compute failure links using BFS
nfa.buildFailureLinks()
// Phase 3: Propagate matches along failure links
if matchKind == LeftmostFirst || matchKind == LeftmostLongest {
nfa.propagateMatches()
}
// Phase 4: Precompute root transitions (key optimization!)
nfa.precomputeRootTransitions()
return nfa
}
// buildTrie constructs the initial trie from patterns.
func (nfa *OptimizedNFA) buildTrie(patterns [][]byte) {
// Create root state with dense transitions
nfa.states = append(nfa.states, optState{
trans: make([]StateID, nfa.alphabetLen),
fail: 0,
depth: 0,
})
// Add each pattern to the trie
for patternID, pattern := range patterns {
nfa.addPattern(pattern, PatternID(patternID))
}
}
// addPattern adds a single pattern to the trie.
func (nfa *OptimizedNFA) addPattern(pattern []byte, patternID PatternID) {
state := nfa.startState
for _, b := range pattern {
class := nfa.byteClasses.Get(b)
// Check if transition exists
if next := nfa.states[state].trans[class]; next != 0 {
state = next
} else {
// Create new state with dense transitions
newState := StateID(len(nfa.states)) //nolint:gosec // G115: state count bounded by patterns
nfa.states = append(nfa.states, optState{
trans: make([]StateID, nfa.alphabetLen),
fail: 0,
depth: nfa.states[state].depth + 1,
})
nfa.states[state].trans[class] = newState
state = newState
}
}
// Mark this state as accepting for this pattern
nfa.states[state].matches = append(nfa.states[state].matches, patternID)
}
// buildFailureLinks computes failure links using BFS.
func (nfa *OptimizedNFA) buildFailureLinks() {
queue := make([]StateID, 0, len(nfa.states))
// Initialize: children of root have failure link to root
root := &nfa.states[nfa.startState]
for class := 0; class < nfa.alphabetLen; class++ {
if child := root.trans[class]; child != 0 {
nfa.states[child].fail = nfa.startState
queue = append(queue, child)
}
}
// Process remaining states in BFS order
for len(queue) > 0 {
state := queue[0]
queue = queue[1:]
// For each outgoing transition
for class := 0; class < nfa.alphabetLen; class++ {
child := nfa.states[state].trans[class]
if child == 0 {
continue
}
queue = append(queue, child)
// Compute failure link for child
fail := nfa.states[state].fail
for {
if next := nfa.states[fail].trans[class]; next != 0 {
nfa.states[child].fail = next
break
}
if fail == nfa.startState {
nfa.states[child].fail = nfa.startState
break
}
fail = nfa.states[fail].fail
}
}
}
}
// propagateMatches propagates match lists along failure links.
func (nfa *OptimizedNFA) propagateMatches() {
queue := make([]StateID, 0, len(nfa.states))
// Start with children of root
root := &nfa.states[nfa.startState]
for class := 0; class < nfa.alphabetLen; class++ {
if child := root.trans[class]; child != 0 {
queue = append(queue, child)
}
}
// Process states in BFS order
for len(queue) > 0 {
stateID := queue[0]
queue = queue[1:]
state := &nfa.states[stateID]
// Add children to queue
for class := 0; class < nfa.alphabetLen; class++ {
if child := state.trans[class]; child != 0 {
queue = append(queue, child)
}
}
// Propagate matches from failure state
if state.fail != nfa.startState {
failMatches := nfa.states[state.fail].matches
if len(failMatches) > 0 {
state.matches = append(state.matches, failMatches...)
}
}
}
}
// precomputeRootTransitions fills in all root transitions.
// This is the KEY optimization: after this, root never needs failure link following.
func (nfa *OptimizedNFA) precomputeRootTransitions() {
// Root state already has direct transitions set.
// For any class without a transition, it loops back to root.
// This is already the case (trans[class] == 0 means stay at root).
// But we need to explicitly set it so nextState doesn't need to check.
// Actually, for the root state, we keep trans[class] == 0 as meaning "stay at root".
// The nextState function handles this specially.
// For non-root states, we could also precompute failure transitions,
// but that would use much more memory (DFA-style).
// For now, we keep the NFA approach but with dense transitions.
}
// Note: nextState, isMatch, getMatches, stateCount methods removed.
// Search is now performed via the compiled DFA (see dfa.go, automaton.go).
// The NFA serves only as an intermediate representation for DFA construction.