-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.go
100 lines (85 loc) · 2.05 KB
/
tracker.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
package tok
import (
"strings"
)
// Tracker is an interface that can be coupled with a Scannar and track the movemend.
type Tracker interface {
Update(m Marker)
}
// Returns a new empty Basket that is coupled as Tracker on the scanner.
func (s *Scanner) NewBasket() *Basket {
b := &Basket{}
s.Tracker = b
return b
}
// Returns a new empty Basket that is coupled as Tracker on the scanner.
// Each Rule that matches picks the Segment to the Basket.
func (s *Scanner) NewBasketFor(g Grammar) *Basket {
b := &Basket{}
b.PickWith(g.Grammar()...)
s.Tracker = b
return b
}
//------------------------------------------------------------------------------
// Basket can be used to Pick readed Segments.
type Basket struct {
segments []Segment
}
// Add adds a Segment to the Basket.
func (b *Basket) Add(seg Segment) {
b.segments = append(b.segments, seg)
}
func (b *Basket) Update(m Marker) {
for i := len(b.segments); i > 0; i-- {
seg := b.segments[i-1]
if seg.to <= m {
b.segments = b.segments[:i]
return
}
}
b.segments = []Segment{}
}
// Picked returns the picked Segments.
func (b *Basket) Picked() []Segment {
return b.segments
}
func (b *Basket) String() string {
segs := []string{}
for _, seg := range b.segments {
segs = append(segs, seg.String())
}
return strings.Join(segs, ";")
}
// PickWith calls Pick on all rules with the Basket as paramter.
func (b *Basket) PickWith(rules ...*Rule) {
for _, r := range rules {
r.Pick(b)
}
}
//------------------------------------------------------------------------------
type pickReader struct {
info string
basket *Basket
sub Reader
}
func (r *pickReader) Read(s *Scanner) error {
t, err := s.TokenizeUse(r.sub)
if err == nil {
r.basket.Add(Segment{
Info: r.info,
Token: t,
})
}
return err
}
func (r *pickReader) What() string {
return r.sub.What()
}
// Pick creates a Reader that appends the Segments that r reads forward to the Basket with info as Info value.
func Pick(r Reader, b *Basket, info string) Reader {
return &pickReader{
info: info,
basket: b,
sub: r,
}
}