This repository has been archived by the owner on Nov 22, 2018. It is now read-only.
/
vm.go
108 lines (93 loc) · 2.06 KB
/
vm.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
// Copyright (c) 2014 The lexer Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lexer
type stateSet struct {
count uint
dense []dense
sparse []uint
}
type dense struct {
id uint
priority int
}
func newStateSet(n int) stateSet {
return stateSet{0, make([]dense, n), make([]uint, n)}
}
func (s *stateSet) clear() {
s.count = 0
}
func (s *stateSet) has(state *NfaState, priority *int) bool {
id := state.Index
i := s.sparse[id]
d := s.dense[i]
if i < s.count && d.id == id {
*priority = d.priority
return true
}
return false
}
func (s *stateSet) include(state *NfaState, priority int) bool {
id := state.Index
i := s.sparse[id]
d := &s.dense[i]
if i < s.count && d.id == id { // has
if d.priority > priority {
d.priority = priority
return false
}
return true
}
s.sparse[id], s.dense[s.count] = s.count, dense{id, priority}
s.count++
return false
}
func (s *stateSet) closure(src *ScannerSource, state *NfaState, priority int) {
if !s.include(state, priority) {
for _, edge := range state.NonConsuming {
if edge.Accepts(src) {
p := edge.Priority()
if p == 0 { // inherit
p = priority
}
s.closure(src, edge.Target(), p)
}
}
}
}
type vm struct {
nfa Nfa
x, y stateSet
}
func newVM(nfa Nfa) vm {
n := len(nfa)
return vm{nfa, newStateSet(n), newStateSet(n)}
}
func (vm *vm) start(src *ScannerSource, start, accept *NfaState) (arune rune, moves int, ok bool) {
nfa, x, y := vm.nfa, &vm.x, &vm.y
x.clear()
for x.closure(src, start, 0); ; x, y = y, x {
arune = src.Current()
y.clear()
for i := uint(0); i < x.count; i++ {
d := x.dense[i]
for _, edge := range nfa[d.id].Consuming {
if edge.Accepts(src) {
priority := edge.Priority()
if priority == 0 { // inherit
priority = d.priority
}
y.closure(src, edge.Target(), priority)
}
}
}
if y.count == 0 { // FSM halted
i := int(arune)
ok = x.has(accept, &i)
arune = rune(i)
return
}
src.Move()
moves++
}
}