compiler/fold_constants: use eval_constant from tools

This commit is contained in:
Sebastien Bourdeauducq 2014-08-13 17:54:58 +08:00
parent 0145e52d4b
commit fe5b3cc67e
1 changed files with 5 additions and 27 deletions

View File

@ -1,28 +1,6 @@
import ast, operator
from artiq.language import units
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
from artiq.compiler.tools import *
_ast_unops = {
ast.Invert: operator.inv,
@ -50,8 +28,8 @@ class _ConstantFolder(ast.NodeTransformer):
def visit_UnaryOp(self, node):
self.generic_visit(node)
try:
operand = _get_constant(node.operand)
except _NotConstant:
operand = eval_constant(node.operand)
except NotConstant:
return node
try:
op = _ast_unops[type(node.op)]
@ -66,8 +44,8 @@ class _ConstantFolder(ast.NodeTransformer):
def visit_BinOp(self, node):
self.generic_visit(node)
try:
left, right = _get_constant(node.left), _get_constant(node.right)
except _NotConstant:
left, right = eval_constant(node.left), eval_constant(node.right)
except NotConstant:
return node
try:
op = _ast_binops[type(node.op)]