| 1 |
""" |
| 2 |
Helpers for morphing modules |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import contextlib |
| 12 |
|
| 13 |
from gavo.adql import nodes |
| 14 |
|
| 15 |
|
| 16 |
class State(object): |
| 17 |
"""is a scratchpad for morphers to communicate state among |
| 18 |
themselves. |
| 19 |
|
| 20 |
Append to warnings a necessary. Also, traverse keeps an attribute |
| 21 |
nodeStack in here letting elements look up its parent chain. |
| 22 |
""" |
| 23 |
def __init__(self): |
| 24 |
self.warnings = [] |
| 25 |
self.nodeStack = [] |
| 26 |
|
| 27 |
@contextlib.contextmanager |
| 28 |
def onNodeStack(self, node): |
| 29 |
self.nodeStack.append(node) |
| 30 |
try: |
| 31 |
yield |
| 32 |
finally: |
| 33 |
popped = self.nodeStack.pop() |
| 34 |
assert popped==node, "ADQL morphing node stack corruption" |
| 35 |
|
| 36 |
|
| 37 |
_BOOLEANIZER_TABLE = { |
| 38 |
('=', '0'): "NOT", |
| 39 |
('!=', '1'): "NOT", |
| 40 |
('=', '1'): "", |
| 41 |
('!=', '0'): "",} |
| 42 |
|
| 43 |
def addNotToBooleanized(expr, operator, operand): |
| 44 |
"""prepends a NOT to expr if operator and operand suggest there should |
| 45 |
be one for ADQL integerized boolean expressions. |
| 46 |
|
| 47 |
The function will return None for unknown combinations of operator and |
| 48 |
operand, and it will simply hand through Nones for expr, so calling |
| 49 |
functions can just return addNotToBooleanized(...). |
| 50 |
""" |
| 51 |
if expr is None: |
| 52 |
return expr |
| 53 |
|
| 54 |
prefix = _BOOLEANIZER_TABLE.get((operator, operand), None) |
| 55 |
if prefix is None: |
| 56 |
# weird non-boolean-looking condition |
| 57 |
return None |
| 58 |
|
| 59 |
elif prefix: |
| 60 |
return nodes.TransparentNode(children=[prefix, '(', expr, ')']) |
| 61 |
|
| 62 |
else: |
| 63 |
return expr |
| 64 |
|
| 65 |
|
| 66 |
def analyzeFuncComp(node, acceptableOperators=["=", "!="]): |
| 67 |
"""returns the (function, other operator) for a comparisonPredicate |
| 68 |
|
| 69 |
This is regardless of the order of the comparison. |
| 70 |
|
| 71 |
This will return None, None if |
| 72 |
|
| 73 |
* node isn't a comparisonPredicate |
| 74 |
* the operator is not symmetric |
| 75 |
* none of the operators is a FunctionNode |
| 76 |
""" |
| 77 |
if (node.type!="comparisonPredicate" |
| 78 |
or node.opr not in acceptableOperators): |
| 79 |
return None, None |
| 80 |
|
| 81 |
if isinstance(node.op1, nodes.FunctionNode): |
| 82 |
return node.op1, node.op2 |
| 83 |
elif isinstance(node.op2, nodes.FunctionNode): |
| 84 |
return node.op2, node.op1 |
| 85 |
else: |
| 86 |
# no function call, leave things alone |
| 87 |
return None, None |
| 88 |
|
| 89 |
|
| 90 |
# Handler functions for booleanizeComparisons |
| 91 |
_BOOLEANOID_FUNCTIONS = {} |
| 92 |
|
| 93 |
def registerBooleanizer(funcName, handler): |
| 94 |
"""registers handler as a booleanizer for ADQL functions called |
| 95 |
funcName. |
| 96 |
|
| 97 |
funcName must be all-uppercase for this to work. handler(node, |
| 98 |
operand, operator) is a function that receives a function node |
| 99 |
and the operand and operator of the comparison and either returns |
| 100 |
None to say it can't handle it, or something else; that something |
| 101 |
else is what the entire comparison node is morphed into. |
| 102 |
|
| 103 |
You can call multiple booleanizers for the same function; they will |
| 104 |
be tried in sequence. Hence, make sure you get your import sequences |
| 105 |
right if you do this. |
| 106 |
""" |
| 107 |
_BOOLEANOID_FUNCTIONS.setdefault(funcName, []).append(handler) |
| 108 |
|
| 109 |
|
| 110 |
def booleanizeComparisons(node, state): |
| 111 |
"""turns a comparison expression that's really a boolean |
| 112 |
expression into a boolean expression. |
| 113 |
|
| 114 |
Actual morphers shouldn't use that but rather get their parent |
| 115 |
from the stack and use its OVERRIDE_RESULT attribute. See the |
| 116 |
DISTANCE morpher for an example. |
| 117 |
|
| 118 |
For several reasons, ufuncs like ivo_hasword can't really do this. |
| 119 |
Instead, they call registerBooleanizer with the function name |
| 120 |
and callable that receives the function node, the operator, and |
| 121 |
the operand. If that function returns non-None, that result is |
| 122 |
used instead of the current node. |
| 123 |
""" |
| 124 |
fCall, opd = analyzeFuncComp(node) |
| 125 |
if fCall is None: |
| 126 |
# node is not a comparison with a function; this is probably not |
| 127 |
# a good sign, as we shouldn't end up here in that case, but |
| 128 |
# let's hope for the best and fall through to SQL. |
| 129 |
return node |
| 130 |
|
| 131 |
opd = nodes.flatten(opd) |
| 132 |
|
| 133 |
for morpher in _BOOLEANOID_FUNCTIONS.get(fCall.funName, []): |
| 134 |
res = morpher(fCall, node.opr, opd) |
| 135 |
if res is not None: |
| 136 |
node = res |
| 137 |
break |
| 138 |
return node |
| 139 |
|
| 140 |
|
| 141 |
class Morpher(object): |
| 142 |
"""A class managing the process of morphing an ADQL expression. |
| 143 |
|
| 144 |
It is constructed with a a dictionary of morphers; the keys are node |
| 145 |
types, the values morphing functions. |
| 146 |
|
| 147 |
Morphing functions have the signature m(node, state) -> node. They |
| 148 |
should return the node if they do not with to change it. |
| 149 |
state is a State instance. |
| 150 |
|
| 151 |
The main entry point is morph(origTree) -> state, tree. origTree is not |
| 152 |
modified, the return value can be flattened but can otherwise be severely |
| 153 |
damaged. |
| 154 |
|
| 155 |
For special effects, there's also earlyMorphers. These will be called |
| 156 |
when traversal reaches the node for the first time. If these return |
| 157 |
None, traversal continues as usual, if not, their result will be |
| 158 |
added to the tree and *not* further traversed. TODO: We don't currently |
| 159 |
have anything requiring earlyMorphers. Do we want to drop the feature? |
| 160 |
""" |
| 161 |
def __init__(self, morphers, earlyMorphers={}): |
| 162 |
self.morphers = morphers |
| 163 |
self.earlyMorphers = earlyMorphers |
| 164 |
|
| 165 |
def _getChangedForSeq(self, value, state): |
| 166 |
newVal, changed = [], False |
| 167 |
for child in value: |
| 168 |
if isinstance(child, nodes.ADQLNode): |
| 169 |
newVal.append(self._traverse(child, state)) |
| 170 |
else: |
| 171 |
newVal.append(child) |
| 172 |
if newVal[-1]!=child: |
| 173 |
changed = True |
| 174 |
if changed: |
| 175 |
return tuple(newVal) |
| 176 |
|
| 177 |
def _getChangedForNode(self, value, state): |
| 178 |
newVal = self._traverse(value, state) |
| 179 |
if not newVal is value: |
| 180 |
return newVal |
| 181 |
|
| 182 |
def _getChanges(self, name, value, state): |
| 183 |
"""iterates over key/value pairs changed by morphing value under |
| 184 |
the key name. |
| 185 |
""" |
| 186 |
if isinstance(value, (list, tuple)): |
| 187 |
meth = self._getChangedForSeq |
| 188 |
elif isinstance(value, nodes.ADQLNode): |
| 189 |
meth = self._getChangedForNode |
| 190 |
else: |
| 191 |
return |
| 192 |
newVal = meth(value, state) |
| 193 |
if newVal is not None: |
| 194 |
yield name, newVal |
| 195 |
|
| 196 |
def _traverse(self, node, state): |
| 197 |
if node.type in self.earlyMorphers: |
| 198 |
res = self.earlyMorphers[node.type](node, state) |
| 199 |
if res is not None: |
| 200 |
return res |
| 201 |
|
| 202 |
with state.onNodeStack(node): |
| 203 |
changes = [] |
| 204 |
for name, value in node.iterAttributes(): |
| 205 |
changes.extend(self._getChanges(name, value, state)) |
| 206 |
|
| 207 |
# let handlers down the tree determine the total result (this |
| 208 |
# is mainly for when comparisons become boolean function calls, |
| 209 |
# but who knows?) |
| 210 |
if getattr(node, "OVERRIDE_RESULT", None) is not None: |
| 211 |
newNode = node.OVERRIDE_RESULT |
| 212 |
|
| 213 |
elif changes: |
| 214 |
newNode = node.change(**dict(changes)) |
| 215 |
newNode.original = node |
| 216 |
|
| 217 |
else: |
| 218 |
newNode = node |
| 219 |
|
| 220 |
curType = getattr(newNode, "type", None) |
| 221 |
if curType in self.morphers: |
| 222 |
handlerResult = self.morphers[curType](newNode, state) |
| 223 |
assert handlerResult is not None,\ |
| 224 |
"ADQL morph handler for %s returned None"%curType |
| 225 |
return handlerResult |
| 226 |
return newNode |
| 227 |
|
| 228 |
def morph(self, tree): |
| 229 |
state = State() |
| 230 |
res = self._traverse(tree, state) |
| 231 |
return state, res |