andOr returns the query q AND r or q OR r, possibly reusing q's and r's storage. It works hard to avoid creating unnecessarily complicated structures.
(r *Query, op QueryOp)
| 50 | // andOr returns the query q AND r or q OR r, possibly reusing q's and r's storage. |
| 51 | // It works hard to avoid creating unnecessarily complicated structures. |
| 52 | func (q *Query) andOr(r *Query, op QueryOp) (out *Query) { |
| 53 | opstr := "&" |
| 54 | if op == QOr { |
| 55 | opstr = "|" |
| 56 | } |
| 57 | //println("andOr", q.String(), opstr, r.String()) |
| 58 | //defer func() { println(" ->", out.String()) }() |
| 59 | _ = opstr |
| 60 | |
| 61 | if len(q.Trigram) == 0 && len(q.Sub) == 1 { |
| 62 | q = q.Sub[0] |
| 63 | } |
| 64 | if len(r.Trigram) == 0 && len(r.Sub) == 1 { |
| 65 | r = r.Sub[0] |
| 66 | } |
| 67 | |
| 68 | // Boolean simplification. |
| 69 | // If q ⇒ r, q AND r ≡ q. |
| 70 | // If q ⇒ r, q OR r ≡ r. |
| 71 | if q.implies(r) { |
| 72 | //println(q.String(), "implies", r.String()) |
| 73 | if op == QAnd { |
| 74 | return q |
| 75 | } |
| 76 | return r |
| 77 | } |
| 78 | if r.implies(q) { |
| 79 | //println(r.String(), "implies", q.String()) |
| 80 | if op == QAnd { |
| 81 | return r |
| 82 | } |
| 83 | return q |
| 84 | } |
| 85 | |
| 86 | // Both q and r are QAnd or QOr. |
| 87 | // If they match or can be made to match, merge. |
| 88 | qAtom := len(q.Trigram) == 1 && len(q.Sub) == 0 |
| 89 | rAtom := len(r.Trigram) == 1 && len(r.Sub) == 0 |
| 90 | if q.Op == op && (r.Op == op || rAtom) { |
| 91 | q.Trigram = stringSet.union(q.Trigram, r.Trigram, false) |
| 92 | q.Sub = append(q.Sub, r.Sub...) |
| 93 | return q |
| 94 | } |
| 95 | if r.Op == op && qAtom { |
| 96 | r.Trigram = stringSet.union(r.Trigram, q.Trigram, false) |
| 97 | return r |
| 98 | } |
| 99 | if qAtom && rAtom { |
| 100 | q.Op = op |
| 101 | q.Trigram = append(q.Trigram, r.Trigram...) |
| 102 | return q |
| 103 | } |
| 104 | |
| 105 | // If one matches the op, add the other to it. |
| 106 | if q.Op == op { |
| 107 | q.Sub = append(q.Sub, r) |
| 108 | return q |
| 109 | } |