Browse files

Support multi-statement code fragments

  • Loading branch information...
1 parent fbf46a7 commit d889793b2beb87c864b48ea219153ffc54aef873 @andrewschaaf andrewschaaf committed Feb 4, 2014
Showing with 21 additions and 7 deletions.
  1. +3 −0 .gitmodules
  2. +8 −7 context.py
  3. +9 −0 test-context.py
  4. 0 upstream/__init__.py
  5. +1 −0 upstream/codegen
View
3 .gitmodules
@@ -0,0 +1,3 @@
+[submodule "upstream/codegen"]
+ path = upstream/codegen
+ url = https://github.com/andrewschaaf/codegen.git
View
15 context.py
@@ -1,6 +1,7 @@
import ast, _ast, time
from stdlib import Image, Video
from value_repr import value_repr
+from upstream.codegen.codegen import to_source
class Context:
@@ -16,15 +17,15 @@ def reset(self):
def run_code(self, code):
result = None
- body = ast.parse(code).body
t0 = time.time()
try:
- assert len(body) == 1# TODO: multi-line
- node = ast.parse(code).body[0]
- if isinstance(node, _ast.Expr):
- result = eval(code, self.globals, self.locals)
- else:
- exec(code, self.globals, self.locals)
+ for node in ast.parse(code).body:
+ node_code = to_source(node)
+ if isinstance(node, _ast.Expr):
+ result = eval(node_code, self.globals, self.locals)
+ else:
+ exec(node_code, self.globals, self.locals)
+ result = None
except Exception, e:
result = e
microseconds = int((time.time() - t0) * 1000000)
View
9 test-context.py
@@ -28,6 +28,15 @@ def test_run_code(self):
c = Context()
assert set(c.run_code("1").keys()) == set(['microseconds', 'result'])
+ def test_multiline_ending_with_expression(self):
+ c = Context()
+ import ast
+ assert c.run_code("x = 2\n3")['result']['value'] == 3
+
+ def test_multiline_ending_with_statement(self):
+ c = Context()
+ assert c.run_code("3\nx = 2")['result']['type'] == 'NullValue'
+
def test_Assign_exception(self):
c = Context()
assert c.run_code("x = {}['k']")['result']['type'] == 'ErrorValue'
View
0 upstream/__init__.py
No changes.
1 upstream/codegen
@@ -0,0 +1 @@
+Subproject commit 279103e491f8fc776b01fbfd5b5fb4b5971bc185

0 comments on commit d889793

Please sign in to comment.