forked from M-Labs/artiq
compiler/fold_constants: use eval_constant from tools
This commit is contained in:
parent
0145e52d4b
commit
fe5b3cc67e
|
@ -1,28 +1,6 @@
|
||||||
import ast, operator
|
import ast, operator
|
||||||
|
|
||||||
from artiq.language import units
|
from artiq.compiler.tools import *
|
||||||
from artiq.compiler.tools import value_to_ast, make_stmt_transformer
|
|
||||||
|
|
||||||
class _NotConstant(Exception):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _get_constant(node):
|
|
||||||
if isinstance(node, ast.Num):
|
|
||||||
return node.n
|
|
||||||
elif isinstance(node, ast.Str):
|
|
||||||
return node.s
|
|
||||||
elif isinstance(node, ast.Call) \
|
|
||||||
and isinstance(node.func, ast.Name) \
|
|
||||||
and node.func.id == "Quantity":
|
|
||||||
amount, unit = node.args
|
|
||||||
amount = _get_constant(amount)
|
|
||||||
try:
|
|
||||||
unit = getattr(units, unit.id)
|
|
||||||
except:
|
|
||||||
raise _NotConstant
|
|
||||||
return units.Quantity(amount, unit)
|
|
||||||
else:
|
|
||||||
raise _NotConstant
|
|
||||||
|
|
||||||
_ast_unops = {
|
_ast_unops = {
|
||||||
ast.Invert: operator.inv,
|
ast.Invert: operator.inv,
|
||||||
|
@ -50,8 +28,8 @@ class _ConstantFolder(ast.NodeTransformer):
|
||||||
def visit_UnaryOp(self, node):
|
def visit_UnaryOp(self, node):
|
||||||
self.generic_visit(node)
|
self.generic_visit(node)
|
||||||
try:
|
try:
|
||||||
operand = _get_constant(node.operand)
|
operand = eval_constant(node.operand)
|
||||||
except _NotConstant:
|
except NotConstant:
|
||||||
return node
|
return node
|
||||||
try:
|
try:
|
||||||
op = _ast_unops[type(node.op)]
|
op = _ast_unops[type(node.op)]
|
||||||
|
@ -66,8 +44,8 @@ class _ConstantFolder(ast.NodeTransformer):
|
||||||
def visit_BinOp(self, node):
|
def visit_BinOp(self, node):
|
||||||
self.generic_visit(node)
|
self.generic_visit(node)
|
||||||
try:
|
try:
|
||||||
left, right = _get_constant(node.left), _get_constant(node.right)
|
left, right = eval_constant(node.left), eval_constant(node.right)
|
||||||
except _NotConstant:
|
except NotConstant:
|
||||||
return node
|
return node
|
||||||
try:
|
try:
|
||||||
op = _ast_binops[type(node.op)]
|
op = _ast_binops[type(node.op)]
|
||||||
|
|
Loading…
Reference in New Issue