Merge pull request #719 from unmerged/nonlocal-keyword

Added `nonlocal`. `global` takes multiple args.
This commit is contained in:
Paul‮etnomailgaT‭ 2015-06-22 09:55:51 -04:00
commit 950c1bd41b
2 changed files with 48 additions and 6 deletions

View File

@ -1061,13 +1061,42 @@ class HyASTCompiler(object):
return ret return ret
@builds("global") @builds("global")
@checkargs(1) @checkargs(min=1)
def compile_global_expression(self, expr): def compile_global_expression(self, expr):
expr.pop(0) # global expr.pop(0) # global
e = expr.pop(0) names = []
return ast.Global(names=[ast_str(e)], while len(expr) > 0:
lineno=e.start_line, identifier = expr.pop(0)
col_offset=e.start_column) name = ast_str(identifier)
names.append(name)
if not isinstance(identifier, HySymbol):
raise HyTypeError(identifier, "(global) arguments must "
" be Symbols")
return ast.Global(names=names,
lineno=expr.start_line,
col_offset=expr.start_column)
@builds("nonlocal")
@checkargs(min=1)
def compile_nonlocal_expression(self, expr):
if not PY3:
raise HyCompileError(
"nonlocal only supported in python 3!")
expr.pop(0) # nonlocal
names = []
while len(expr) > 0:
identifier = expr.pop(0)
name = ast_str(identifier)
names.append(name)
if not isinstance(identifier, HySymbol):
raise HyTypeError(identifier, "(nonlocal) arguments must "
"be Symbols.")
return ast.Nonlocal(names=names,
lineno=expr.start_line,
col_offset=expr.start_column)
@builds("yield") @builds("yield")
@checkargs(max=1) @checkargs(max=1)

View File

@ -218,12 +218,25 @@ def test_ast_bad_assert():
def test_ast_good_global(): def test_ast_good_global():
"Make sure AST can compile valid global" "Make sure AST can compile valid global"
can_compile("(global a)") can_compile("(global a)")
can_compile("(global foo bar)")
def test_ast_bad_global(): def test_ast_bad_global():
"Make sure AST can't compile invalid global" "Make sure AST can't compile invalid global"
cant_compile("(global)") cant_compile("(global)")
cant_compile("(global foo bar)") cant_compile("(global (foo))")
if PY3:
def test_ast_good_nonlocal():
"Make sure AST can compile valid nonlocal"
can_compile("(nonlocal a)")
can_compile("(nonlocal foo bar)")
def test_ast_bad_nonlocal():
"Make sure AST can't compile invalid nonlocal"
cant_compile("(nonlocal)")
cant_compile("(nonlocal (foo))")
def test_ast_good_defclass(): def test_ast_good_defclass():