-
Notifications
You must be signed in to change notification settings - Fork 3
/
opmatchcontext.go
90 lines (80 loc) · 2.04 KB
/
opmatchcontext.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
package yarex
import (
"sync"
"unsafe"
)
type ContextKey struct {
Kind rune
Index uint
}
type opStackFrame struct {
Key ContextKey
Pos int
}
var opStackPool = sync.Pool{
New: func() interface{} {
b := make([]opStackFrame, initialStackSize)
return &b
},
}
type MatchContext struct {
Str uintptr // *string // string being matched
getStack uintptr // *func() []opStackFrame // Accessors to stack to record capturing positions.
setStack uintptr // *func([]opStackFrame) // We use uintptr to avoid leaking param.
stackTop int // stack top
}
func makeOpMatchContext(str *string, getter *func() []opStackFrame, setter *func([]opStackFrame)) MatchContext {
return MatchContext{uintptr(unsafe.Pointer(str)), uintptr(unsafe.Pointer(getter)), uintptr(unsafe.Pointer(setter)), 0}
}
func (c MatchContext) Push(k ContextKey, p int) MatchContext {
st := (*(*func() []opStackFrame)(unsafe.Pointer(c.getStack)))() // c.getStack()
sf := opStackFrame{k, p}
if len(st) <= c.stackTop {
st = append(st, sf)
st = st[:cap(st)]
(*(*func([]opStackFrame))(unsafe.Pointer(c.setStack)))(st) // c.setStack(st)
} else {
st[c.stackTop] = sf
}
c.stackTop++
return c
}
func (c MatchContext) GetCaptured(k ContextKey) (string, bool) {
loc := c.GetCapturedIndex(k)
if loc == nil {
return "", false
}
return (*(*string)(unsafe.Pointer(c.Str)))[loc[0]:loc[1]], true
}
func (c MatchContext) GetCapturedIndex(k ContextKey) []int {
var start, end int
st := (*(*func() []opStackFrame)(unsafe.Pointer(c.getStack)))() // c.getStack()
i := c.stackTop - 1
for ; ; i-- {
if i == 0 {
return nil
}
if st[i].Key == k {
end = st[i].Pos
break
}
}
i--
for ; i >= 0; i-- {
if st[i].Key == k {
start = st[i].Pos
return []int{start, end}
}
}
// This should not happen.
panic("Undetermined capture")
}
func (c MatchContext) FindVal(k ContextKey) int {
st := (*(*func() []opStackFrame)(unsafe.Pointer(c.getStack)))() // c.getStack()
for i := c.stackTop - 1; i >= 0; i-- {
if st[i].Key == k {
return st[i].Pos
}
}
return -1
}