tweaking the ast.
This commit is contained in:
parent
9e16fb4ca0
commit
20805fc7b2
@ -18,4 +18,5 @@
|
||||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
# DEALINGS IN THE SOFTWARE.
|
||||
|
||||
from hy.compilers.pyast import hy_compile
|
||||
|
||||
from hy.compilers.pyast import hy_compile # NOQA
|
||||
|
@ -24,9 +24,6 @@ from abc import ABCMeta, abstractmethod
|
||||
class HyCompiler(object):
|
||||
__metaclass__ = ABCMeta
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def compile(self, tree):
|
||||
pass
|
||||
|
@ -46,12 +46,34 @@ def builds(_type):
|
||||
|
||||
|
||||
class HyASTCompiler(HyCompiler):
|
||||
|
||||
def __init__(self):
|
||||
self.returnable = False
|
||||
|
||||
def compile(self, tree):
|
||||
for _type in _compile_table:
|
||||
for _type in _compile_table:
|
||||
if type(tree) == _type:
|
||||
return _compile_table[_type](self, tree)
|
||||
|
||||
raise HyCompileError("Unknown type - `%s'" % (str(type(tree))))
|
||||
raise HyCompileError("Unknown type - `%s'" % (str(type(tree))))
|
||||
|
||||
def _mangle_branch(self, tree):
|
||||
ret = []
|
||||
tree.reverse()
|
||||
|
||||
if self.returnable:
|
||||
el = tree.pop()
|
||||
if not isinstance(el, ast.stmt):
|
||||
ret.append(ast.Return(value=el,
|
||||
lineno=el.lineno,
|
||||
col_offset=el.col_offset))
|
||||
ret += [ast.Expr(value=el,
|
||||
lineno=el.lineno,
|
||||
col_offset=el.col_offset
|
||||
) if not isinstance(el, ast.stmt) else el for el in tree]
|
||||
|
||||
ret.reverse()
|
||||
return ret
|
||||
|
||||
@builds(list)
|
||||
def compile_raw_list(self, entries):
|
||||
@ -75,13 +97,12 @@ class HyASTCompiler(HyCompiler):
|
||||
|
||||
@builds(HyString)
|
||||
def compile_string(self, string):
|
||||
return ast.Str(s=string)
|
||||
|
||||
|
||||
compiler = HyASTCompiler()
|
||||
return ast.Str(s=str(string), lineno=string.start_line,
|
||||
col_offset=string.start_column)
|
||||
|
||||
|
||||
def hy_compile(tree):
|
||||
" Compile a HyObject tree into a Python AST tree. "
|
||||
ret = ast.Module(body=compiler.compile(tree))
|
||||
compiler = HyASTCompiler()
|
||||
ret = ast.Module(body=compiler._mangle_branch(compiler.compile(tree)))
|
||||
return ret
|
||||
|
@ -44,7 +44,7 @@ def test_ast_bad_type():
|
||||
def test_ast_expression_basics():
|
||||
""" Ensure basic AST expression conversion works. """
|
||||
code = hy_compile(tokenize("(foo bar)")).body[0]
|
||||
tree = ast.Call(
|
||||
tree = ast.Expr(value=ast.Call(
|
||||
func=ast.Name(
|
||||
id="foo",
|
||||
ctx=ast.Load(),
|
||||
@ -55,6 +55,6 @@ def test_ast_expression_basics():
|
||||
keywords=[],
|
||||
starargs=None,
|
||||
kwargs=None,
|
||||
)
|
||||
_ast_spotcheck("func.id", code, tree)
|
||||
_ast_spotcheck("id", code.args[0], tree.args[0])
|
||||
))
|
||||
|
||||
_ast_spotcheck("value.func.id", code, tree)
|
||||
|
Loading…
Reference in New Issue
Block a user