-
Notifications
You must be signed in to change notification settings - Fork 2
/
op.go
482 lines (456 loc) · 10.9 KB
/
op.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package shapes
import (
"fmt"
"github.com/pkg/errors"
)
// OpType represents the type of operation that is being performed
type OpType byte
const (
// Unary: a → b
Const OpType = iota // K
Dims
Prod
Sum
ForAll // special use
// Binary: a → a → a
Add
Sub
Mul
Div
// Cmp: a → a → Bool
Eq
Ne
Lt
Gt
Lte
Gte
// Logic: bool → bool → bool
And
Or
// Broadcast
Bc
)
var optypeStr = map[OpType]string{
Const: "K",
Dims: "D",
Prod: "Π",
Sum: "Σ",
ForAll: "∀",
Add: "+",
Sub: "-",
Mul: "×",
Div: "÷",
Eq: "=",
Ne: "≠",
Lt: "<",
Gt: ">",
Lte: "≤",
Gte: "≥",
And: "∧",
Or: "∨",
Bc: "⚟",
}
var optypeRune = map[rune]OpType{
'K': Const,
'D': Dims,
'Π': Prod,
'Σ': Sum,
'∀': ForAll,
'+': Add,
'-': Sub,
'×': Mul,
'÷': Div,
'=': Eq,
'≠': Ne,
'<': Lt,
'>': Gt,
'≤': Lte,
'≥': Gte,
'∧': And,
'∨': Or,
'⚟': Bc,
}
// String returns the string representation
func (o OpType) String() string {
retVal, ok := optypeStr[o]
if !ok {
retVal = fmt.Sprintf("UNFORMATTED OPTYPE %d", o)
}
return retVal
}
func parseOpType(a rune) (OpType, error) {
retVal, ok := optypeRune[a]
if !ok {
return Const, errors.Errorf("Unknown OpType for rune %c", a)
}
return retVal, nil
}
// BinOp represents a binary operation.
// It is only an Expr for the purposes of being a value in a shape.
// On the toplevel, BinOp on is meaningless. This is enforced in the `unify` function.
type BinOp struct {
Op OpType
A Expr
B Expr
}
func (op BinOp) isExpr() {}
func (op BinOp) isSizelike() {}
func (op BinOp) isValid() bool { return op.Op >= Add && op.Op <= Or }
func (op BinOp) resolveSize() (Size, error) {
if err := op.nofreeevars(); err != nil {
return 0, errors.Wrapf(err, "Cannot resolve BinOp %v to Size.", op)
}
A, B, err := op.resolveAB()
if err != nil {
return 0, errors.Wrapf(err, "Cannot resolve BinOp %v to Size.", op)
}
switch op.Op {
case Add:
return A + B, nil
case Sub:
return A - B, nil
case Mul:
return A * B, nil
case Div:
return A / B, nil
default:
return 0, errors.Errorf("Unable to resolve op %v into a Size", op)
}
panic("unreachable")
}
// resolveBool is only ever used by SubjectTo's resolveBool.
func (op BinOp) resolveBool() (bool, error) {
if err := op.nofreeevars(); err != nil {
return false, errors.Wrapf(err, "Cannot resolve BinOp %v to bool.", op)
}
A, B, err := op.resolveAB()
if err != nil {
retVal, err := op.resolveForAllAB()
if err == nil {
return retVal, nil
}
return op.resolveBroadcastAB()
}
return op.do(A, B)
}
func (op BinOp) do(A, B Size) (bool, error) {
switch op.Op {
case Eq:
return A == B, nil
case Ne:
return A != B, nil
case Lt:
return A < B, nil
case Gt:
return A > B, nil
case Lte:
return A <= B, nil
case Gte:
return A >= B, nil
default:
return false, errors.Errorf("Cannot resolve BinOp %v to bool.", op)
}
}
func (op BinOp) nofreeevars() error {
if len(op.A.freevars()) > 0 {
return errors.Errorf("Cannot resolve BinOp %v - free vars found in A", op)
}
if len(op.B.freevars()) > 0 {
return errors.Errorf("Cannot resolve BinOp %v - free vars found in B", op)
}
return nil
}
func (op BinOp) resolveAB() (A, B Size, err error) {
switch a := op.A.(type) {
case Size:
A = a
case sizeOp:
var err error
if A, err = a.resolveSize(); err != nil {
return A, B, errors.Wrapf(err, "BinOp %v - A (%v) does not resolve to a Size", op, op.A)
}
default:
return 0, 0, errors.Errorf("Cannot resolve BinOp %v - A (%v) is not resolved to a Size", op, op.A)
}
switch b := op.B.(type) {
case Size:
B = b
case sizeOp:
var err error
if B, err = b.resolveSize(); err != nil {
return A, B, errors.Wrapf(err, "BinOp %v - B (%v) does not resolve to a Size", op, op.B)
}
default:
return 0, 0, errors.Errorf("Cannot resolve BinOp %v - B is not resolved to a Size", op)
}
return
}
func (op BinOp) resolveForAllAB() (bool, error) {
auo, aok := extractForAll(op.A)
buo, bok := extractForAll(op.B)
var ok bool
switch {
case aok && bok:
var A, B intslike
if A, ok = auo.A.(intslike); !ok {
return false, errors.Errorf("Unable to reolve %v to bool. Operand A's expression of %T is not intslike.", op, auo.A)
}
if B, ok = buo.A.(intslike); !ok {
return false, errors.Errorf("Unable to reolve %v to bool. Operand B's expression of %T is not intslike.", op, buo.A)
}
al, bl := A.AsInts(), B.AsInts()
if len(al) != len(bl) {
return false, nil // will always be false because you cannot compare slices of unequal length. Does this mean it should have an error message? Unsure
}
bl = bl[:len(al)]
for i, a := range al {
b := bl[i]
ok, err := op.do(Size(a), Size(b))
if err != nil {
return false, errors.Wrapf(err, "Cannot resolve %v %v %v (%dth index in %v)", a, op.Op, b, i, op)
}
if !ok {
return false, nil
}
}
case !aok && bok:
A, ok := op.A.(sizeOp)
if !ok {
return false, errors.Errorf("Unable to resolve %v to bool. Operand A's expression of %T is not a sizeOp", op, op.A)
}
B, ok := buo.A.(intslike)
if !ok {
return false, errors.Errorf("Unable to resolve %v to bool. Operand B's expression of %T is not intslike", op, buo.A)
}
a, err := A.resolveSize()
if err != nil {
return false, errors.Wrapf(err, "Unable to resolve %v to bool. Operand A %v was unable to be resolved into a Size", op, op.A)
}
bl := B.AsInts()
for i, b := range bl {
ok, err := op.do(a, Size(b))
if err != nil {
return false, errors.Wrapf(err, "Cannot resolve %v %v %v (%dth index in %v)", a, op.Op, b, i, op)
}
if !ok {
return false, nil
}
}
case aok && !bok:
A, ok := auo.A.(intslike)
if !ok {
return false, errors.Errorf("Unable to resolve %v to bool. Operand A's expression of %T is not intslike", op, auo.A)
}
B, ok := op.B.(sizeOp)
if !ok {
return false, errors.Errorf("Unable to resolve %v to bool. Operand B's expression of %T is not a sizeOp", op, op.B)
}
b, err := B.resolveSize()
if err != nil {
return false, errors.Wrapf(err, "Unable to resolve %v to bool. Operand B %v was unable to be resolved into a Size", op, op.B)
}
al := A.AsInts()
for i, a := range al {
ok, err := op.do(Size(a), b)
if err != nil {
return false, errors.Wrapf(err, "Cannot resolve %v %v %v (%dth index in %v)", a, op.Op, b, i, op)
}
if !ok {
return false, nil
}
}
default:
// not foralls.
return false, errors.Errorf("Unable to resolve %v to a bool", op)
}
return true, nil
}
func (op BinOp) resolveBroadcastAB() (bool, error) {
A, ok := op.A.(UnaryOp)
if !ok {
return false, errors.Errorf("Expected a unary op in A")
}
B, ok := op.B.(UnaryOp)
if !ok {
return false, errors.Errorf("Expected a unary op in B")
}
aShp, aok := A.A.(Shape)
bShp, bok := B.A.(Shape)
if aok && bok {
err := AreBroadcastable(aShp, bShp)
if _, ok := err.(NoOpError); ok || err == nil {
return true, nil
}
return false, err
}
return false, errors.Errorf("Cannot resolve BroadcastAB")
}
// BinOp implements substitutable
func (op BinOp) apply(ss substitutions) substitutable {
return BinOp{
Op: op.Op,
A: op.A.apply(ss).(Expr),
B: op.B.apply(ss).(Expr),
}
}
func (op BinOp) freevars() varset {
retVal := op.A.freevars()
retVal = append(retVal, op.B.freevars()...)
return unique(retVal)
}
func (op BinOp) subExprs() []substitutableExpr {
return []substitutableExpr{op.A.(substitutableExpr), op.B.(substitutableExpr)}
}
// Format formats the BinOp into a nice string.
func (op BinOp) Format(s fmt.State, r rune) {
var format string
switch r {
case 'P':
if op.A.depth() >= 3 || op.B.depth() >= 3 {
format = "(%P %v %P)"
} else {
format = "(%v %v %v)"
}
default:
if op.A.depth() >= 3 || op.B.depth() >= 3 {
format = "%P %v %P"
} else {
format = "%v %v %v"
}
}
fmt.Fprintf(s, format, op.A, op.Op, op.B)
}
// UnaryOp represetns a unary operation on a shape expression.
// Unlike BinaryOp, UnaryOp is an expression.
type UnaryOp struct {
Op OpType
A Expr
}
func (op UnaryOp) depth() int { return op.A.depth() + 1 }
func (op UnaryOp) isSizelike() {}
func (op UnaryOp) isValid() bool { return op.Op < Add }
func (op UnaryOp) resolveSize() (Size, error) {
if !op.isValid() {
return 0, errors.Errorf("Invalid UnaryOp %v", op)
}
if len(op.A.freevars()) > 0 {
return 0, errors.Errorf("Cannot resolve UnaryOp %v - free vars found in A", op)
}
switch A := op.A.(type) {
case Abstract:
switch op.Op {
case Const:
// ????????? TODO
case Dims:
return Size(len(A)), nil
case Prod:
retVal := 1
for _, av := range A {
switch a := av.(type) {
case Size:
retVal *= int(a)
case sizeOp:
v, err := a.resolveSize()
if err != nil {
return 0, errors.Wrapf(err, "Unable to resolve %v.", op)
}
retVal *= int(v)
default:
return 0, errors.Errorf("Unreachable: a sizelike of %T cannot be Prod'd", av)
}
}
return Size(retVal), nil
case Sum:
retVal := 0
for _, av := range A {
switch a := av.(type) {
case Size:
retVal += int(a)
case sizeOp:
v, err := a.resolveSize()
if err != nil {
return 0, errors.Wrapf(err, "Unable to resolve %v.", op)
}
retVal += int(v)
}
}
return Size(retVal), nil
default:
panic("unreachable")
}
case Shape:
switch op.Op {
case Const:
return 0, errors.Errorf(unaryOpResolveErr, op)
case Dims:
return Size(len(A)), nil
case Prod:
retVal := 1
for i := range A {
retVal *= A[i]
}
return Size(retVal), nil
case Sum:
retVal := 0
for i := range A {
retVal += A[i]
}
return Size(retVal), nil
default:
panic("unreachable")
}
case Axes:
// only D is allowed. Error otherwise
if op.Op != Dims {
return 0, errors.Errorf(unaryOpResolveErr, op)
}
return Size(len(A)), nil
case Sizes:
// only D is allowed. Error otherwise
if op.Op != Dims {
return 0, errors.Errorf(unaryOpResolveErr, op)
}
return Size(len(A)), nil
case Size:
switch op.Op {
case Const:
return A, nil
case Dims:
return 0, nil
case Prod:
return A, nil
case Sum:
return A, nil
}
case Axis:
switch op.Op {
case Const:
return 0, errors.Errorf(unaryOpResolveErr, op)
case Dims:
return 0, nil
case Prod:
return Size(A), nil
case Sum:
return Size(A), nil
}
default:
return 0, errors.Errorf(unaryOpResolveErr, op)
}
panic("Unreachable")
}
// UnaryOp implements substitutable
func (op UnaryOp) apply(ss substitutions) substitutable {
return UnaryOp{
Op: op.Op,
A: op.A.apply(ss).(Expr),
}
}
func (op UnaryOp) freevars() varset { return op.A.freevars() }
// UnaryOp is an Expr
func (op UnaryOp) isExpr() {}
// Exprs returns the expression contained within the UnaryOp expression.
func (op UnaryOp) subExprs() []substitutableExpr {
return []substitutableExpr{op.A.(substitutableExpr)}
}
// Format makes UnaryOp implement fmt.Formatter.
func (op UnaryOp) Format(s fmt.State, r rune) { fmt.Fprintf(s, "%v %v", op.Op, op.A) }