expr: fix reverse for << and >>

This commit is contained in:
Shiz 2021-06-25 01:54:33 +02:00
parent 727e89e051
commit 43344943ea
1 changed files with 11 additions and 5 deletions

View File

@ -89,8 +89,8 @@ reverse = {
operator.pow: lambda x, y: math.log(x) / math.log(y),
operator.inv: operator.inv,
operator.lshift: operator.rshift,
operator.rshift: operator.lshift,
operator.lshift: (operator.rshift, lambda x, y: int(math.log(x / y) / math.log(2))),
operator.rshift: (operator.lshift, lambda x, y: int(math.log(y / x) / math.log(2))),
}
T = TypeVar('T')
@ -121,9 +121,10 @@ class Expr(G[T]):
locals()['__' + x.strip('_') + '__'] = functools.partialmethod(lambda self, x: UnaryExpr(getattr(operator, x), self), x)
for x in (
'add', 'and_', 'floordiv', 'lshift', 'mod', 'mul', 'matmul', 'or_', 'pow', 'rshift', 'sub', 'truediv', 'xor',
'concat', 'contains', 'delitem', 'getitem', 'delitem', 'getitem', 'setitem',
'concat', 'contains',
):
locals()['__' + x.strip('_') + '__'] = functools.partialmethod(lambda self, x, other: BinExpr(getattr(operator, x), self, other), x)
locals()[ '__' + x.strip('_') + '__'] = functools.partialmethod(lambda self, x, other: BinExpr(getattr(operator, x), self, other), x)
locals()['__r' + x.strip('_') + '__'] = functools.partialmethod(lambda self, x, other: BinExpr(getattr(operator, x), other, self), x)
del x
class AttrExpr(G[T], Expr[T]):
@ -263,14 +264,19 @@ class BinExpr(G[T], Expr[T]):
if not isinstance(self.__left, Expr):
operand = self.__left
target = self.__right
i = 0
elif not isinstance(self.__right, Expr):
operand = self.__right
target = self.__left
i = 1
else:
raise NotImplementedError(f'{self.__class__.__name__} has two expression operands and is not invertible')
if self.__op not in reverse:
raise NotImplementedError(f'{self.__class__.__name__} {symbols[self.__op]!r} is not invertible')
put(target, reverse[self.__op](value, operand))
rev = reverse[self.__op]
if isinstance(rev, tuple):
rev = rev[i]
put(target, rev(value, operand))
def __str__(self) -> str:
return f'({self.__left} {symbols[self.__op]} {self.__right})'