Tweaking the AST.

This commit is contained in:
Paul R. Tagliamonte 2013-03-05 21:42:54 -05:00
parent 7a925b5ee4
commit 37a11247c7
4 changed files with 33 additions and 6 deletions

View File

@ -4,7 +4,10 @@ from hy.compiler import hy_compile
from hy.lex import tokenize from hy.lex import tokenize
import codegen import codegen
import sys import sys
import ast
tokens = tokenize(open(sys.argv[1], 'r').read())
ast = hy_compile(tokenize(open(sys.argv[1], 'r').read())) print tokens
print codegen.to_source(ast) _ast = hy_compile(tokens)
print ast.dump(_ast)
print codegen.to_source(_ast)

View File

@ -63,8 +63,9 @@ class HyASTCompiler(object):
tree.reverse() tree.reverse()
if self.returnable and len(tree) > 0: if self.returnable and len(tree) > 0:
el = tree.pop() el = tree[0]
if not isinstance(el, ast.stmt): if not isinstance(el, ast.stmt):
el = tree.pop()
ret.append(ast.Return(value=el, ret.append(ast.Return(value=el,
lineno=el.lineno, lineno=el.lineno,
col_offset=el.col_offset)) col_offset=el.col_offset))
@ -80,6 +81,30 @@ class HyASTCompiler(object):
def compile_raw_list(self, entries): def compile_raw_list(self, entries):
return [self.compile(x) for x in entries] return [self.compile(x) for x in entries]
@builds("assert")
def compile_assert_expression(self, expr):
expr.pop(0) # assert
e = expr.pop(0)
return ast.Assert(test=self.compile(e),
msg=None,
lineno=e.start_line,
col_offset=e.start_column)
@builds("=")
def compile_compare_op_expression(self, expression):
ops = {"=": ast.Eq}
inv = expression.pop(0)
op = ops[inv]
ops = [op() for x in range(1, len(expression))]
e = expression.pop(0)
return ast.Compare(left=self.compile(e),
ops=ops,
comparators=[self.compile(x) for x in expression],
lineno=e.start_line,
col_offset=e.start_column)
@builds("+") @builds("+")
@builds("-") @builds("-")
@builds("/") @builds("/")

View File

@ -18,7 +18,6 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE. # DEALINGS IN THE SOFTWARE.
from hy.models import HyObject
from hy.models.list import HyList from hy.models.list import HyList

View File

@ -2,4 +2,4 @@
(def test_basic_math (fn [] (def test_basic_math (fn []
(assert (+ 2 2) 4))) (assert (= (+ 2 2) 4))))