-
Notifications
You must be signed in to change notification settings - Fork 15
/
pattern.go
400 lines (341 loc) · 8.76 KB
/
pattern.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package rel
import (
"bytes"
"fmt"
"github.com/arr-ai/frozen"
"github.com/go-errors/errors"
)
// Pattern can be inside an Expr, Expr can be a Pattern.
type Pattern interface {
// Require a String() method.
fmt.Stringer
Bind(scope Scope, value Value) (Scope, error)
}
type IdentPattern struct {
ident string
}
func NewIdentPattern(ident string) IdentPattern {
return IdentPattern{ident}
}
func (p IdentPattern) Bind(scope Scope, value Value) (Scope, error) {
scope.MustGet(p.ident)
scope.MatchedWith(p.ident, value)
return EmptyScope.With(p.ident, value), nil
}
func (p IdentPattern) String() string {
return p.ident
}
type ExtraElementPattern struct {
ident string
}
func NewExtraElementPattern(ident string) ExtraElementPattern {
return ExtraElementPattern{ident}
}
func (p ExtraElementPattern) Bind(scope Scope, value Value) (Scope, error) {
if p.ident == "" {
return EmptyScope, nil
}
return EmptyScope.With(p.ident, value), nil
}
func (p ExtraElementPattern) String() string {
return "..." + p.ident
}
type ArrayPattern struct {
items []Pattern
}
func NewArrayPattern(elements ...Pattern) ArrayPattern {
return ArrayPattern{elements}
}
func (p ArrayPattern) Bind(local Scope, value Value) (Scope, error) {
if s, is := value.(GenericSet); is {
if s.set.IsEmpty() {
if len(p.items) == 0 {
return EmptyScope, nil
}
panic(fmt.Sprintf("value [] is empty but pattern %s is not", p))
}
panic(fmt.Sprintf("value %s is not an array", value))
}
array, is := value.(Array)
if !is {
panic(fmt.Sprintf("value %s is not an array", value))
}
extraElements := make(map[int]int)
for i, item := range p.items {
if _, is := item.(ExtraElementPattern); is {
if len(extraElements) == 1 {
panic("multiple ... not supported yet")
}
extraElements[i] = array.Count() - len(p.items)
}
}
if len(p.items) > array.Count()+len(extraElements) {
panic(fmt.Sprintf("length of array %s shorter than array pattern %s", array, p))
}
if len(extraElements) == 0 && len(p.items) < array.Count() {
panic(fmt.Sprintf("length of array %s longer than array pattern %s", array, p))
}
result := EmptyScope
offset := 0
for i, item := range p.items {
if _, is := item.(ExtraElementPattern); is {
offset = extraElements[i]
arr := NewArray()
if offset >= 0 {
arr = NewArray(array.Values()[i : i+offset+1]...)
}
scope, err := item.Bind(local, arr)
if err != nil {
return EmptyScope, err
}
result = result.MatchedUpdate(scope)
continue
}
scope, err := item.Bind(local, array.Values()[i+offset])
if err != nil {
return EmptyScope, err
}
result = result.MatchedUpdate(scope)
}
return result, nil
}
func (p ArrayPattern) String() string {
var b bytes.Buffer
b.WriteByte('[')
for i, item := range p.items {
if i > 0 {
b.WriteString(", ")
}
b.WriteString(item.String())
}
b.WriteByte(']')
return b.String()
}
type TuplePatternAttr struct {
name string
pattern Pattern
}
func NewTuplePatternAttr(name string, pattern Pattern) TuplePatternAttr {
return TuplePatternAttr{
name: name,
pattern: pattern,
}
}
func (a TuplePatternAttr) String() string {
return fmt.Sprintf("%s:%s", a.name, a.pattern)
}
func (a *TuplePatternAttr) IsWildcard() bool {
return a.name == "*"
}
type TuplePattern struct {
attrs []TuplePatternAttr
}
func NewTuplePattern(attrs ...TuplePatternAttr) TuplePattern {
names := make(map[string]bool)
for _, attr := range attrs {
if names[attr.name] {
panic(fmt.Sprintf("name %s is duplicated in tuple", attr.name))
}
}
return TuplePattern{attrs}
}
func (p TuplePattern) Bind(local Scope, value Value) (Scope, error) {
tuple, is := value.(Tuple)
if !is {
panic(fmt.Sprintf("%s is not a tuple", value))
}
extraElements := make(map[int]int)
for i, attr := range p.attrs {
if _, is := attr.pattern.(ExtraElementPattern); is {
if len(extraElements) == 1 {
panic("multiple ... not supported yet")
}
extraElements[i] = tuple.Count() - len(p.attrs)
}
}
if len(p.attrs) > tuple.Count()+len(extraElements) {
panic(fmt.Sprintf("length of tuple %s shorter than tuple pattern %s", tuple, p))
}
if len(extraElements) == 0 && len(p.attrs) < tuple.Count() {
panic(fmt.Sprintf("length of tuple %s longer than tuple pattern %s", tuple, p))
}
result := EmptyScope
names := tuple.Names()
for _, attr := range p.attrs {
if _, is := attr.pattern.(ExtraElementPattern); is {
tupleExpr := tuple.Project(names)
if tupleExpr == nil {
panic(fmt.Sprintf("tuple %s cannot match tuple pattern %s", tuple, p))
}
scope, err := attr.pattern.Bind(local, tupleExpr)
if err != nil {
return EmptyScope, err
}
result = result.MatchedUpdate(scope)
continue
}
tupleExpr := tuple.MustGet(attr.name)
scope, err := attr.pattern.Bind(local, tupleExpr)
if err != nil {
return EmptyScope, err
}
result = result.MatchedUpdate(scope)
names = names.Without(attr.name)
}
return result, nil
}
func (p TuplePattern) String() string {
var b bytes.Buffer
b.WriteByte('(')
for i, attr := range p.attrs {
if i > 0 {
b.WriteString(", ")
}
if attr.IsWildcard() {
if attr.pattern != DotIdent {
b.WriteString(attr.pattern.String())
}
b.WriteString(".*")
} else {
b.WriteString(attr.name)
b.WriteString(": ")
b.WriteString(attr.pattern.String())
}
}
b.WriteByte(')')
return b.String()
}
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 {
panic(fmt.Sprintf("%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 {
panic("multiple ... not supported yet")
}
extraElements[i] = dict.Count() - len(p.entries)
}
}
if len(p.entries) > dict.Count()+len(extraElements) {
panic(fmt.Sprintf("length of dict %s shorter than dict pattern %s", dict, p))
}
if len(extraElements) == 0 && len(p.entries) < dict.Count() {
panic(fmt.Sprintf("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 := m.MustGet(entry.at)
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()
}
type ExprsPattern struct {
exprs []Expr
}
func NewExprsPattern(exprs ...Expr) ExprsPattern {
return ExprsPattern{exprs: exprs}
}
func (ep ExprsPattern) Bind(scope Scope, value Value) (Scope, error) {
if len(ep.exprs) == 0 {
return EmptyScope, errors.Errorf("there is not any rel.Expr in rel.ExprsPattern")
}
if pe, isPattern := ep.exprs[0].(Pattern); len(ep.exprs) == 1 && isPattern {
// Support patterns IDENT and NUM
return pe.Bind(scope, value)
}
incomingVal, err := value.Eval(scope)
if err != nil {
return EmptyScope, err
}
for _, e := range ep.exprs {
val, err := e.Eval(scope)
if err != nil {
return EmptyScope, err
}
if incomingVal.Equal(val) {
return scope, nil
}
}
return EmptyScope, errors.Errorf("didn't find matched value")
}
func (ep ExprsPattern) String() string {
if len(ep.exprs) == 0 {
panic("there is not any rel.Expr in rel.ExprsPattern")
}
if len(ep.exprs) == 1 {
// it processes cases IDENT and NUM as syntax, otherwise `let (:x) = (x: 1); x` will fail.
return ep.exprs[0].String()
}
var b bytes.Buffer
b.WriteByte('[')
for i, e := range ep.exprs {
if i > 0 {
b.WriteString(", ")
}
fmt.Fprintf(&b, "%v", e.String())
}
b.WriteByte(']')
return b.String()
}