Skip to content

Commit

Permalink
Now handle correctly a classdef constructor.
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Antukh committed Jan 21, 2014
1 parent c636e2a commit 219ae6d
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 10 deletions.
11 changes: 11 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
Changelog
=========

Version 0.1.2
-------------

- Correct handle of __init__ function on classdef.

Version 0.1.1
-------------

- Multiple assignation.
- Fixed bugs on list comprensions.

Version 0.1
-----------

Expand Down
19 changes: 15 additions & 4 deletions cobra/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,15 +678,26 @@ def _translate_ExceptHandler(self, node, childs):

def _translate_ClassDef(self, node, childs):
functions = list(map(lambda x: x._func_expr,
filter(lambda x: hasattr(x, "_func_expr"), childs)))
filter(lambda x: hasattr(x, "_func_expr"), childs)))
childs = list(filter(lambda x: not hasattr(x, "_func_expr"), childs))

self.scope.new_scope()
# Constructor

constructor_func_expr = None
for fn in functions:
if fn._identifier.value == "__init__":
constructor_func_expr = fn
self.scope.unset("__init__")
break

if constructor_func_expr is None:
constructor_func_expr = ecma_ast.FuncExpr(None, None, None)
else:
functions = list(filter(lambda x: x is not constructor_func_expr, functions))

self.scope.new_scope()
inner_class_idf = self.get_unique_identifier("classref")

# Constructor
constructor_func_expr = ecma_ast.FuncExpr(None, None, None)
assign_expr = ecma_ast.Assign("=", inner_class_idf, constructor_func_expr)
constructor_expr = ecma_ast.ExprStatement(assign_expr)

Expand Down
3 changes: 3 additions & 0 deletions cobra/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ def set(self, key, value, special_form=False):
if not self.validate():
raise RuntimeError("Special form overwriten")

def unset(self, key):
del self.data[key]

def is_empty(self):
return len(self.data) == 0

Expand Down
15 changes: 9 additions & 6 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,19 +765,22 @@ def person(name):
def test_basic_class():
input = """
class MyClass:
def foo(self):
return 2
def __init__(x):
this.x = x
def foo():
return this.x
"""

expected = """
var MyClass, foo;
MyClass = (function() {
var classref_0;
classref_0 = function() {
classref_0 = function(x) {
this.x = x;
};
classref_0.prototype.foo = function(self) {
return 2;
classref_0.prototype.foo = function() {
return this.x;
};
return classref_0;
})();
Expand Down

0 comments on commit 219ae6d

Please sign in to comment.