-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule.go
119 lines (98 loc) · 2.36 KB
/
rule.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
package day19
import (
"fmt"
"strconv"
"strings"
)
type CacheKey struct {
// It is poor that we keep regenerating this with String() calls. It might
// be nicer for each rule to become a struct, which stores its original
// string representation alongside the rule.
RuleDef string
Message string
}
type RuleID int
type Rule interface {
Match(rules map[RuleID]Rule, cache map[CacheKey]bool, message string) bool
fmt.Stringer
}
type AdjacentRule []Rule
func (r AdjacentRule) Match(rules map[RuleID]Rule, cache map[CacheKey]bool, message string) (ret bool) {
key := CacheKey{
RuleDef: r.String(),
Message: message,
}
if ret, ok := cache[key]; ok {
return ret
}
defer func() {
cache[key] = ret
}()
if len(r) == 1 {
return r[0].Match(rules, cache, message)
}
for i := 1; i < len(message); i++ {
if r[0].Match(rules, cache, message[:i]) && r[1:].Match(rules, cache, message[i:]) {
return true
}
}
return false
}
func (r AdjacentRule) String() string {
subrules := make([]string, len(r))
for i, subrule := range r {
subrules[i] = subrule.String()
}
return strings.Join(subrules, " ")
}
type OrRule []Rule
func (r OrRule) Match(rules map[RuleID]Rule, cache map[CacheKey]bool, message string) (ret bool) {
key := CacheKey{
RuleDef: r.String(),
Message: message,
}
if ret, ok := cache[key]; ok {
return ret
}
defer func() {
cache[key] = ret
}()
for _, subrule := range r {
if subrule.Match(rules, cache, message) {
return true
}
}
return false
}
func (r OrRule) String() string {
subrules := make([]string, len(r))
for i, subrule := range r {
subrules[i] = subrule.String()
}
return strings.Join(subrules, " | ")
}
type TerminalRule byte
func (r TerminalRule) Match(_ map[RuleID]Rule, _ map[CacheKey]bool, message string) bool {
// Don't bother with a cache lookup here: it probably isn't worth the String() call
return len(message) == 1 && message[0] == byte(r)
}
func (r TerminalRule) String() string {
return fmt.Sprintf(`"%c"`, r)
}
type RefRule RuleID
func (r RefRule) Match(rules map[RuleID]Rule, cache map[CacheKey]bool, message string) (ret bool) {
key := CacheKey{
RuleDef: r.String(),
Message: message,
}
if ret, ok := cache[key]; ok {
return ret
}
defer func() {
cache[key] = ret
}()
return rules[RuleID(r)].Match(rules, cache, message)
}
func (r RefRule) String() string {
return strconv.Itoa(int(r))
}