-
Notifications
You must be signed in to change notification settings - Fork 15
/
pattern_dict.go
111 lines (95 loc) · 2.47 KB
/
pattern_dict.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
package rel
import (
"bytes"
"fmt"
"github.com/arr-ai/frozen"
)
type DictPatternEntry struct {
at Expr
value Pattern
}
func NewDictPatternEntry(at Expr, value Pattern) DictPatternEntry {
return DictPatternEntry{
at: at,
value: value,
}
}
func (p DictPatternEntry) String() string {
return fmt.Sprintf("%s:%s", p.at, p.value)
}
type DictPattern struct {
entries []DictPatternEntry
}
func NewDictPattern(entries ...DictPatternEntry) DictPattern {
names := make(map[string]bool)
for _, entry := range entries {
if names[entry.at.String()] {
panic(fmt.Sprintf("name %s is duplicated in dict", entry.at))
}
}
return DictPattern{entries}
}
func (p DictPattern) Bind(local Scope, value Value) (Scope, error) {
dict, is := value.(Dict)
if !is {
return EmptyScope, fmt.Errorf("%s is not a dict", value)
}
extraElements := make(map[int]int)
for i, entry := range p.entries {
if _, is := entry.value.(ExtraElementPattern); is {
if len(extraElements) == 1 {
return EmptyScope, fmt.Errorf("non-deterministic pattern is not supported yet")
}
extraElements[i] = dict.Count() - len(p.entries)
}
}
if len(p.entries) > dict.Count()+len(extraElements) {
return EmptyScope, fmt.Errorf("length of dict %s shorter than dict pattern %s", dict, p)
}
if len(extraElements) == 0 && len(p.entries) < dict.Count() {
return EmptyScope, fmt.Errorf("length of dict %s longer than dict pattern %s", dict, p)
}
result := EmptyScope
m := dict.m
for _, entry := range p.entries {
if _, is := entry.value.(ExtraElementPattern); is {
if m.IsEmpty() {
scope, err := entry.value.Bind(local, None)
if err != nil {
return EmptyScope, err
}
result = result.MatchedUpdate(scope)
} else {
scope, err := entry.value.Bind(local, Dict{m: m})
if err != nil {
return EmptyScope, err
}
result = result.MatchedUpdate(scope)
}
continue
}
dictValue, found := m.Get(entry.at)
if !found {
return EmptyScope, fmt.Errorf("couldn't find %s in dict %s", entry.at, m)
}
scope, err := entry.value.Bind(local, dictValue.(Value))
if err != nil {
return EmptyScope, err
}
result = result.MatchedUpdate(scope)
m = m.Without(frozen.NewSet(entry.at))
}
return result, nil
}
func (p DictPattern) String() string {
var b bytes.Buffer
b.WriteByte('{')
for i, expr := range p.entries {
if i > 0 {
b.WriteString(", ")
}
fmt.Fprintf(&b, "%v: %v", expr.at.String(), expr.value.String())
}
b.WriteByte('}')
return b.String()
}