-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcompound.go
86 lines (70 loc) · 1.92 KB
/
compound.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
package shapes
import (
"fmt"
"github.com/pkg/errors"
)
// compound.go describes compound terms
// SubjectTo describes a constraint
type SubjectTo struct {
OpType
A, B Operation
}
func (s SubjectTo) Format(st fmt.State, r rune) {
fmt.Fprintf(st, "(%v %v %v)", s.A, s.OpType, s.B)
}
// SubjectTo implements substitutable
func (s SubjectTo) apply(ss substitutions) substitutable {
return SubjectTo{
OpType: s.OpType,
A: s.A.apply(ss).(Operation),
B: s.B.apply(ss).(Operation),
}
}
func (s SubjectTo) freevars() varset { return append(s.A.freevars(), s.B.freevars()...) }
func (s SubjectTo) subExprs() []substitutableExpr { return []substitutableExpr{s.A, s.B} }
// subjectTo is also an Operation
func (s SubjectTo) isValid() bool { return s.OpType >= Eq && s.A.isValid() && s.B.isValid() }
func (s SubjectTo) resolveSize() (Size, error) {
return 0, errors.Errorf("SubjectTo does not resolve to Size.")
}
func (s SubjectTo) resolveBool() (bool, error) {
switch s.OpType {
case And, Or:
A, err := s.A.(boolOp).resolveBool()
if err != nil {
return false, errors.Wrapf(err, "Failed to resolve operand A of SubjectTo %v into a bool", s)
}
B, err := s.B.(boolOp).resolveBool()
if err != nil {
return false, errors.Wrapf(err, "Failed to resolve operand A of SubjectTo %v into a bool", s)
}
switch s.OpType {
case And:
return A && B, nil
case Or:
return A || B, nil
}
panic("Unreachable")
default:
op := BinOp{s.OpType, s.A.(Expr), s.B.(Expr)}
return op.resolveBool()
}
}
type Compound struct {
Expr
SubjectTo
}
func (c Compound) Format(s fmt.State, r rune) {
fmt.Fprintf(s, "{ %v | %v }", c.Expr, c.SubjectTo)
}
func (c Compound) apply(ss substitutions) substitutable {
return Compound{
Expr: c.Expr.apply(ss).(Expr),
SubjectTo: c.SubjectTo,
}
}
func (c Compound) freevars() varset {
retVal := c.Expr.freevars()
retVal = append(retVal, c.SubjectTo.freevars()...)
return retVal
}