Debian Codegraph @

msp/raw.go

raw symbols SCIP
1 package msp
2
3 import (
4 "errors"
5 "strings"
6 )
7
8 type NodeType int // Types of node in the binary expression tree.
9
10 const (
11 NodeAnd NodeType = iota
12 NodeOr
13 )
14
15 func (t NodeType) Type() NodeType {
16 return t
17 }
18
19 type Layer struct {
20 Conditions []Condition
21 Operators []NodeType
22 }
23
24 type Raw struct { // Represents one node in the tree.
25 NodeType
26
27 Left Condition
28 Right Condition
29 }
30
31 func StringToRaw(r string) (out Raw, err error) {
32 // Automaton. Modification of Dijkstra's Two-Stack Algorithm for parsing
33 // infix notation. Reads one long unbroken expression (several operators and
34 // operands with no parentheses) at a time and parses it into a binary
35 // expression tree (giving AND operators precedence). Running time linear in
36 // the size of the predicate?
37 //
38 // Steps to the next (un)parenthesis.
39 // ( -> Push new queue onto staging stack
40 // value -> Push onto back of queue at top of staging stack.
41 // ) -> Pop queue off top of staging stack, build BET, and push tree
42 // onto the back of the top queue.
43 //
44 // To build the binary expression tree, for each type of operation we iterate
45 // through the (Condition, operator) lists compacting where that operation
46 // occurs into tree nodes.
47 //
48 // Staging stack is empty on initialization and should have exactly 1 node
49 // (the root node) at the end of the string.
50 r = "(" + r + ")"
51
52 min := func(a, b, c int) int { // Return smallest non-negative argument.
53 if a > b { // Sort {a, b, c}
54 a, b = b, a
55 }
56 if b > c {
57 b, c = c, b
58 }
59 if a > b {
60 a, b = b, a
61 }
62
63 if a != -1 {
64 return a
65 } else if b != -1 {
66 return b
67 } else {
68 return c
69 }
70 }
71
72 getNext := func(r string) (string, string) { // r -> (next, rest)
73 r = strings.TrimSpace(r)
74
75 if r[0] == '(' || r[0] == ')' || r[0] == '&' || r[0] == '|' {
76 return r[0:1], r[1:]
77 }
78
79 nextOper := min(
80 strings.Index(r, "&"),
81 strings.Index(r, "|"),
82 strings.Index(r, ")"),
83 )
84
85 if nextOper == -1 {
86 return r, ""
87 }
88 return strings.TrimSpace(r[0:nextOper]), r[nextOper:]
89 }
90
91 staging := []Layer{} // Stack of (Condition list, operator list)
92 indices := make(map[string]int, 0)
93
94 var nxt string
95 for len(r) > 0 {
96 nxt, r = getNext(r)
97
98 switch nxt {
99 case "(":
100 staging = append([]Layer{Layer{}}, staging...)
101 case ")":
102 if len(staging) < 1 { // Check 1
103 return out, errors.New("Invalid string: Illegal close parenthesis.")
104 }
105
106 top := staging[0] // Legal because of check 1.
107 staging = staging[1:]
108
109 if len(top.Conditions) != (len(top.Operators) + 1) { // Check 2
110 return out, errors.New("Invalid string: There needs to be an operator (& or |) for every pair of operands.")
111 }
112
113 for typ := NodeAnd; typ <= NodeOr; typ++ {
114 i := 0
115 for i < len(top.Operators) {
116 oper := top.Operators[i] // Legal because for loop condition.
117
118 // Copy left and right out of slice and THEN give a pointer for them!
119 left, right := top.Conditions[i], top.Conditions[i+1] // Legal because of check 2.
120 if oper == typ {
121 built := Raw{typ, left, right}
122
123 top.Conditions = append(
124 top.Conditions[:i],
125 append([]Condition{built}, top.Conditions[i+2:]...)...,
126 )
127
128 top.Operators = append(top.Operators[:i], top.Operators[i+1:]...) // Legal because for loop condition.
129 } else {
130 i++
131 }
132 }
133 }
134
135 if len(top.Conditions) != 1 || len(top.Operators) != 0 { // Check 3
136 return out, errors.New("Invalid string: Couldn't evaluate all of the operators.")
137 }
138
139 if len(staging) == 0 { // Check 4
140 if len(r) == 0 {
141 res, ok := top.Conditions[0].(Raw) // Legal because of check 3.
142 if !ok {
143 return out, errors.New("Invalid string: Only one condition was found?")
144 }
145 return res, nil
146 }
147 return out, errors.New("Invalid string: Can't parse anymore, but there's still data. Too many closing parentheses or too few opening parentheses?")
148 }
149 staging[0].Conditions = append(staging[0].Conditions, top.Conditions[0]) // Legal because of checks 3 and 4.
150
151 case "&":
152 // Legal because first operation is to add an empty layer to the stack.
153 // If the stack is ever empty again, the function tries to return or error.
154 staging[0].Operators = append(staging[0].Operators, NodeAnd)
155 case "|":
156 staging[0].Operators = append(staging[0].Operators, NodeOr) // Legal for same reason as case &.
157 default:
158 if _, there := indices[nxt]; !there {
159 indices[nxt] = 0
160 }
161
162 staging[0].Conditions = append(staging[0].Conditions, Name{nxt, indices[nxt]}) // Legal for same reason as case &.
163 indices[nxt]++
164 }
165 }
166
167 return out, errors.New("Invalid string: Not finished parsing, but out of data. Too many opening parentheses or too few closing parentheses?")
168 }
169
170 func (r Raw) String() string {
171 out := ""
172
173 switch left := r.Left.(type) {
174 case Name:
175 out += left.string
176 case Raw:
177 out += "(" + left.String() + ")"
178 }
179
180 if r.Type() == NodeAnd {
181 out += " & "
182 } else {
183 out += " | "
184 }
185
186 switch right := r.Right.(type) {
187 case Name:
188 out += right.string
189 case Raw:
190 out += "(" + right.String() + ")"
191 }
192
193 return out
194 }
195
196 func (r Raw) Formatted() (out Formatted) {
197 // Recursively maps a raw predicate to a formatted predicate by mapping AND
198 // gates to (2, A, B) treshold gates and OR gates to (1, A, B) gates.
199 if r.Type() == NodeAnd {
200 out.Min = 2
201 } else {
202 out.Min = 1
203 }
204
205 switch left := r.Left.(type) {
206 case Name:
207 out.Conds = []Condition{left}
208 case Raw:
209 out.Conds = []Condition{left.Formatted()}
210 }
211
212 switch right := r.Right.(type) {
213 case Name:
214 out.Conds = append(out.Conds, right)
215 case Raw:
216 out.Conds = append(out.Conds, right.Formatted())
217 }
218
219 out.Compress() // Small amount of predicate compression.
220 return
221 }
222
223 func (r Raw) Ok(db UserDatabase) bool {
224 if r.Type() == NodeAnd {
225 return r.Left.Ok(db) && r.Right.Ok(db)
226 } else {
227 return r.Left.Ok(db) || r.Right.Ok(db)
228 }
229 }