diff --git a/README.md b/README.md
index 69992eb..db3e43f 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,24 @@
Introduction
------------
-PythonJS is a transpiler written in Python that converts Python into fast
-JavaScript. It can be run with regular Python, or fully self-hosted within
-NodeJS using Empythoned. PythonJS has been designed with speed and easy
-integration with existing JavaScript code in mind.
+PythonJS is a transpiler written in Python that converts a python like language into fast
+JavaScript. It also includes experimental backends that translate to: Dart, Lua, CoffeeScript, and Go.
-To convert your python scripts into javascript, you have two options:
+[Syntax Documentation](https://github.com/PythonJS/PythonJS/blob/master/doc/syntax.md)
+
+
+Go backend
+----------
+The Go backend uses a fully typed subset of Python, mixed with extra syntax inspired by Golang to output Go programs that can be compiled to native executeables, or translated to JavaScript using GopherJS.
+
+[Syntax Documentation](https://github.com/PythonJS/PythonJS/blob/master/doc/go_syntax.md)
+
+
+Getting Started
+===============
+PythonJS can be run with regular Python, or fully self-hosted within
+NodeJS using Empythoned.
+
+To get started, you have two options:
1. install NodeJS, python-js package, and write a build script.
2. or install Python2 and use translator.py from this repo directly.
@@ -48,47 +61,27 @@ If you want to run the latest version of the translator, you will need to instal
Python2.7 and git clone this repo. (the NodeJS package above is not required)
Then, to translate your python script, directly run the `translator.py` script in the "pythonjs" directory. You can give it a list of python files to translate at once.
It will output the translation to stdout. The default output type is JavaScript.
+An html file can also be used as input, python code inside a script tag: `')
+ if script is True:
+ self._html_tail.extend( o )
+ else:
+ for y in o:
+ writer.write(y)
+
+ else:
+ writer.write(line)
+
+ elif line.strip() == '':
+ if type(script) is list and len(script):
+ source = '\n'.join(script)
+ script = True
+ self._html_tail.append( '')
+ else:
+ writer.write( line )
+
+ elif isinstance( script, list ):
+ script.append( line )
+
+ elif script is True:
+ self._html_tail.append( line )
+
+ else:
+ writer.write( line )
source = typedpython.transform_source( source )
self.setup_inliner( writer )
+ self._in_catch_exception = False
+
self._line = None
self._line_number = 0
self._stack = [] ## current path to the root
self._direct_operators = set() ## optimize "+" and "*" operator
self._with_ll = False ## lowlevel
- self._with_js = False
+ self._with_js = True
self._in_lambda = False
self._in_while_test = False
self._use_threading = False
@@ -175,8 +224,11 @@ def __init__(self, source=None, module=None, module_path=None, dart=False, coffe
self._class_attributes = dict()
self._catch_attributes = None
self._typedef_vars = dict()
+
#self._names = set() ## not used?
+ ## inferred class instances, TODO regtests to confirm that this never breaks ##
self._instances = dict() ## instance name : class name
+
self._decorator_properties = dict()
self._decorator_class_props = dict()
self._function_return_types = dict()
@@ -247,8 +299,14 @@ def __init__(self, source=None, module=None, module_path=None, dart=False, coffe
self._source = source.splitlines()
+ if '--debug--' in sys.argv:
+ try:
+ tree = ast.parse( source )
+ except SyntaxError:
+ raise SyntaxError(source)
+ else:
+ tree = ast.parse( source )
- tree = parse( source ) ## ast.parse
self._generator_function_nodes = collect_generator_functions( tree )
for node in tree.body:
@@ -258,6 +316,10 @@ def __init__(self, source=None, module=None, module_path=None, dart=False, coffe
else:
self.visit(node)
+ if self._html_tail:
+ for line in self._html_tail:
+ writer.write(line)
+
def visit(self, node):
"""Visit a node."""
## modified code of visit() method from Python 2.7 stdlib
@@ -362,7 +424,9 @@ def visit_Import(self, node):
tornado = ['tornado', 'tornado.web', 'tornado.ioloop']
for alias in node.names:
- if alias.name in tornado:
+ if self._with_go:
+ writer.write('import %s' %alias.name)
+ elif alias.name in tornado:
pass ## pythonjs/fakelibs/tornado.py
elif alias.name == 'tempfile':
pass ## pythonjs/fakelibs/tempfile.py
@@ -460,7 +524,7 @@ def visit_Dict(self, node):
if isinstance(v, ast.Lambda):
v.keep_as_lambda = True
v = self.visit( v )
- if self._with_dart or self._with_ll:
+ if self._with_dart or self._with_ll or self._with_go:
a.append( '%s:%s'%(k,v) )
#if isinstance(node.keys[i], ast.Str):
# a.append( '%s:%s'%(k,v) )
@@ -471,7 +535,7 @@ def visit_Dict(self, node):
else:
a.append( 'JSObject(key=%s, value=%s)'%(k,v) ) ## this allows non-string keys
- if self._with_dart or self._with_ll:
+ if self._with_dart or self._with_ll or self._with_go:
b = ','.join( a )
return '{%s}' %b
elif self._with_js:
@@ -542,7 +606,11 @@ def visit_ListComp(self, node):
a = ['get%s'%i for i in range(length)]
writer.write('var( %s )' %','.join(a) )
- writer.write('%s = JSArray()'%cname)
+ if self._with_go:
+ assert node.go_listcomp_type
+ writer.write('%s = __go__array__(%s)' %(cname, node.go_listcomp_type))
+ else:
+ writer.write('%s = JSArray()'%cname)
generators = list( node.generators )
generators.reverse()
@@ -599,6 +667,8 @@ def _gen_comp(self, generators, node):
writer.write('%s.add( %s )' %(cname,self.visit(node.elt)) )
elif self._with_lua:
writer.write('table.insert(%s, %s )' %(cname,self.visit(node.elt)) )
+ elif self._with_go:
+ writer.write('%s = append(%s, %s )' %(cname, cname,self.visit(node.elt)) )
else:
writer.write('%s.push( %s )' %(cname,self.visit(node.elt)) )
writer.pull()
@@ -608,6 +678,8 @@ def _gen_comp(self, generators, node):
writer.write('%s.add( %s )' %(cname,self.visit(node.elt)) )
elif self._with_lua:
writer.write('table.insert(%s, %s )' %(cname,self.visit(node.elt)) )
+ elif self._with_go:
+ writer.write('%s = append(%s, %s )' %(cname, cname,self.visit(node.elt)) )
else:
writer.write('%s.push( %s )' %(cname,self.visit(node.elt)) )
if self._with_lua:
@@ -628,6 +700,11 @@ def visit_NotIn(self, node):
#return ' not in '
raise RuntimeError('"not in" is only allowed in if-test: see method - visit_Compare')
+ ## TODO check if the default visit_Compare always works ##
+ #def visit_Compare(self, node):
+ # raise NotImplementedError( node )
+
+
def visit_AugAssign(self, node):
self._in_assign_target = True
target = self.visit( node.target )
@@ -784,6 +861,8 @@ def _visit_dart_classdef(self, node):
methods = {}
method_list = [] ## getter/setters can have the same name
props = set()
+ struct_types = dict()
+
for item in node.body:
if isinstance(item, FunctionDef):
methods[ item.name ] = item
@@ -801,7 +880,18 @@ def _visit_dart_classdef(self, node):
if n.id == 'self':
n.id = 'this'
- if props:
+ elif isinstance(item, ast.Expr) and isinstance(item.value, ast.Dict):
+ sdef = []
+ for i in range( len(item.value.keys) ):
+ k = self.visit( item.value.keys[ i ] )
+ v = self.visit( item.value.values[i] )
+ sdef.append( '%s=%s'%(k,v) )
+
+ writer.write('@__struct__(%s)' %','.join(sdef))
+
+ if self._with_go:
+ pass
+ elif props:
writer.write('@properties(%s)'%','.join(props))
for dec in node.decorator_list:
writer.write('@%s'%self.visit(dec))
@@ -824,7 +914,8 @@ def _visit_dart_classdef(self, node):
## constructor
if init:
methods.pop( '__init__' )
- init.name = node.name
+ if not self._with_go:
+ init.name = node.name
self.visit(init)
## methods
@@ -892,6 +983,8 @@ def _visit_js_classdef(self, node):
if init:
args = [self.visit(arg) for arg in init.args.args]
node._cached_init = init
+ if init.args.kwarg:
+ args.append( init.args.kwarg )
else:
args = []
@@ -996,7 +1089,7 @@ def _visit_js_classdef(self, node):
self._in_js_class = False
def visit_ClassDef(self, node):
- if self._with_dart:
+ if self._with_dart or self._with_go:
self._visit_dart_classdef(node)
return
elif self._with_js:
@@ -1124,7 +1217,8 @@ def visit_Or(self, node):
def visit_BoolOp(self, node):
op = self.visit(node.op)
- return op.join( [self.visit(v) for v in node.values] )
+ #raise SyntaxError(op)
+ return '('+ op.join( [self.visit(v) for v in node.values] ) + ')'
def visit_If(self, node):
if self._with_dart and writer.is_at_global_level():
@@ -1158,13 +1252,21 @@ def visit_If(self, node):
writer.pull()
def visit_TryExcept(self, node):
+ if len(node.handlers)==0:
+ raise SyntaxError(self.format_error('no except handlers'))
+
+ ## by default in js-mode some expections will not be raised,
+ ## this allows those cases to throw proper errors.
+ if node.handlers[0].type:
+ self._in_catch_exception = self.visit(node.handlers[0].type)
+ else:
+ self._in_catch_exception = None
+
writer.write('try:')
writer.push()
map(self.visit, node.body)
writer.pull()
map(self.visit, node.handlers)
- if len(node.handlers)==0:
- raise SyntaxError(self.format_error('no except handlers'))
def visit_Raise(self, node):
#if self._with_js or self._with_dart:
@@ -1273,10 +1375,25 @@ def visit_Return(self, node):
def visit_BinOp(self, node):
left = self.visit(node.left)
op = self.visit(node.op)
+
+ is_go_listcomp = False
+ if self._with_go:
+ if op == '<<':
+ if isinstance(node.left, ast.Call) and isinstance(node.left.func, ast.Name) and node.left.func.id=='__go__array__':
+ if isinstance(node.right, ast.GeneratorExp):
+ is_go_listcomp = True
+ node.right.go_listcomp_type = node.left.args[0].id
+
+
right = self.visit(node.right)
if self._with_glsl:
return '(%s %s %s)' % (left, op, right)
+ elif self._with_go:
+ if is_go_listcomp:
+ return right
+ else:
+ return '(%s %s %s)' % (left, op, right)
elif op == '|':
if isinstance(node.right, Str):
@@ -1539,15 +1656,14 @@ def visit_Attribute(self, node):
# return 'glsl_inline(%s.%s)' %(node_value, node.attr)
#else:
return '%s.%s' %(node_value, node.attr)
- elif self._with_dart or self._with_ll:
+ elif self._with_dart or self._with_ll or self._with_go:
return '%s.%s' %(node_value, node.attr)
+
elif self._with_js:
- return '%s.%s' %(node_value, node.attr)
- ## TODO pythonjs.configure to allow this
- #if self._in_assign_target or not isinstance(node.attr, str):
- # return '%s.%s' %(node_value, node.attr)
- #else:
- # return '__ternary_operator__(%s.%s is not undefined, %s.%s, __getattr__(%s, "%s"))' %(node_value, node.attr, node_value, node.attr, node_value, node.attr)
+ if self._in_catch_exception == 'AttributeError':
+ return '__getfast__(%s, "%s")' % (node_value, node.attr)
+ else:
+ return '%s.%s' %(node_value, node.attr)
elif self._with_lua and self._in_assign_target: ## this is required because lua has no support for inplace assignment ops like "+="
return '%s.%s' %(node_value, node.attr)
@@ -1574,7 +1690,7 @@ def visit_Subscript(self, node):
#return '%s["$wrapped"]' %name
return '%s[...]' %name
- elif self._with_ll or self._with_glsl:
+ elif self._with_ll or self._with_glsl or self._with_go:
return '%s[%s]' %(name, self.visit(node.slice))
elif self._with_js or self._with_dart:
@@ -1600,15 +1716,26 @@ def visit_Subscript(self, node):
return '%s[ %s ]' %(name, self.visit(node.slice))
- elif isinstance(node.slice, ast.Index) and isinstance(node.slice.value, ast.BinOp):
- return '%s[ %s ]' %(name, self.visit(node.slice))
+ else: ## ------------------ javascript mode ------------------------
+ if self._in_catch_exception == 'KeyError':
+ value = self.visit(node.value)
+ slice = self.visit(node.slice)
+ return '__get__(%s, "__getitem__")([%s], __NULL_OBJECT__)' % (value, slice)
+
+ elif isinstance(node.slice, ast.Index) and isinstance(node.slice.value, ast.BinOp):
+ ## TODO keep this optimization? in js mode `a[x+y]` is assumed to a direct key,
+ ## it would be safer to check if one of the operands is a number literal,
+ ## in that case it is safe to assume that this is a direct key.
+ return '%s[ %s ]' %(name, self.visit(node.slice))
- elif self._with_direct_keys:
- return '%s[ %s ]' %(name, self.visit(node.slice))
+ elif self._with_direct_keys:
+ return '%s[ %s ]' %(name, self.visit(node.slice))
- else: ## ------------------ javascript mode ------------------------
- s = self.visit(node.slice)
- return '%s[ __ternary_operator__(%s.__uid__, %s) ]' %(name, s, s)
+ else:
+ s = self.visit(node.slice)
+ #return '%s[ __ternary_operator__(%s.__uid__, %s) ]' %(name, s, s)
+ check_array = '__ternary_operator__( instanceof(%s,Array), JSON.stringify(%s), %s )' %(s, s, s)
+ return '%s[ __ternary_operator__(%s.__uid__, %s) ]' %(name, s, check_array)
elif isinstance(node.slice, ast.Slice):
return '__get__(%s, "__getslice__")([%s], __NULL_OBJECT__)' % (
@@ -1645,7 +1772,9 @@ def visit_Subscript(self, node):
return fallback
def visit_Slice(self, node):
- if self._with_dart:
+ if self._with_go:
+ lower = upper = step = None
+ elif self._with_dart:
lower = upper = step = 'null'
elif self._with_js:
lower = upper = step = 'undefined'
@@ -1657,10 +1786,19 @@ def visit_Slice(self, node):
upper = self.visit(node.upper)
if node.step:
step = self.visit(node.step)
- return "%s, %s, %s" % (lower, upper, step)
+
+ if self._with_go:
+ if lower and upper:
+ return '%s:%s' %(lower,upper)
+ elif upper:
+ return ':%s' %upper
+ elif lower:
+ return '%s:'%lower
+ else:
+ return "%s, %s, %s" % (lower, upper, step)
def visit_Assign(self, node):
- use_runtime_errors = not (self._with_js or self._with_ll or self._with_dart or self._with_coffee or self._with_lua)
+ use_runtime_errors = not (self._with_js or self._with_ll or self._with_dart or self._with_coffee or self._with_lua or self._with_go)
use_runtime_errors = use_runtime_errors and self._with_runtime_exceptions
lineno = node.lineno
@@ -1727,6 +1865,54 @@ def _visit_assign_helper(self, node, target):
self.visit(node.value) ## writes function def
writer.write('%s = __lambda__' %self.visit(target))
+ elif isinstance(node.value, ast.Dict) and self._with_go:
+ key_type = None
+ val_type = None
+
+ for i in range( len(node.value.keys) ):
+ k = node.value.keys[ i ]
+ v = node.value.values[i]
+ if isinstance(k, ast.Str):
+ key_type = 'string'
+ elif isinstance(k, ast.Num):
+ key_type = 'int'
+
+ if isinstance(v, ast.Str):
+ val_type = 'string'
+ elif isinstance(v, ast.Num):
+ if isinstance(v.n, int):
+ val_type = 'int'
+ else:
+ val_type = 'float64'
+
+ if not key_type:
+ raise SyntaxError( self.format_error('can not determine dict key type') )
+ if not val_type:
+ raise SyntaxError( self.format_error('can not determine dict value type') )
+
+ t = self.visit(target)
+ v = self.visit(node.value)
+ writer.write('%s = __go__map__(%s, %s) << %s' %(t, key_type, val_type, v))
+
+
+ elif isinstance(node.value, ast.List) and self._with_go:
+ guess_type = None
+ for elt in node.value.elts:
+ if isinstance(elt, ast.Num):
+ if isinstance(elt.n, int):
+ guess_type = 'int'
+ else:
+ guess_type = 'float64'
+ elif isinstance(elt, ast.Str):
+ guess_type = 'string'
+
+ if guess_type:
+ t = self.visit(target)
+ v = self.visit(node.value)
+ writer.write('%s = __go__array__(%s) << %s' %(t, guess_type, v))
+ else:
+ raise SyntaxError(self.format_error('can not determine type of array'))
+
elif isinstance(target, Subscript):
name = self.visit(target.value) ## target.value may have "returns_type" after being visited
@@ -1737,7 +1923,7 @@ def _visit_assign_helper(self, node, target):
elif isinstance(target.slice, ast.Slice):
code = '%s.__setslice__(%s, %s)' %(self.visit(target.value), self.visit(target.slice), self.visit(node.value))
- elif self._with_dart or self._with_ll or self._with_glsl:
+ elif self._with_dart or self._with_ll or self._with_glsl or self._with_go:
code = '%s[ %s ] = %s'
code = code % (self.visit(target.value), self.visit(target.slice.value), self.visit(node.value))
@@ -1748,7 +1934,8 @@ def _visit_assign_helper(self, node, target):
elif self._with_direct_keys:
code = '%s[ %s ] = %s' % (self.visit(target.value), s, self.visit(node.value))
else:
- code = '%s[ __ternary_operator__(%s.__uid__, %s) ] = %s' % (self.visit(target.value), s, s, self.visit(node.value))
+ check_array = '__ternary_operator__( instanceof(%s,Array), JSON.stringify(%s), %s )' %(s, s, s)
+ code = '%s[ __ternary_operator__(%s.__uid__, %s) ] = %s' %(self.visit(target.value), s, check_array, self.visit(node.value))
elif name in self._func_typedefs and self._func_typedefs[name] == 'list':
code = '%s[%s] = %s'%(name, self.visit(target.slice.value), self.visit(node.value))
@@ -1773,7 +1960,7 @@ def _visit_assign_helper(self, node, target):
#####################################
- if self._with_js or self._with_dart:
+ if self._with_js or self._with_dart or self._with_go:
writer.write( '%s.%s=%s' %(target_value, target.attr, self.visit(node.value)) )
elif typedef and target.attr in typedef.properties and 'set' in typedef.properties[ target.attr ]:
setter = typedef.properties[ target.attr ]['set']
@@ -1945,7 +2132,7 @@ def _visit_assign_helper(self, node, target):
writer.write("%s = __ternary_operator__(instanceof(%s,Array), %s[%s], %s)" % (self.visit(target), r, r,i, fallback ))
def visit_Print(self, node):
- writer.write('print %s' % ', '.join(map(self.visit, node.values)))
+ writer.write('print(%s)' % ', '.join(map(self.visit, node.values)))
def visit_Str(self, node):
s = node.s.replace('\\','\\\\').replace('\n', '\\n').replace('\r', '\\r').replace('\0', '\\0')
@@ -1971,7 +2158,7 @@ def visit_Expr(self, node):
self._line_number = node.lineno
self._line = src
- use_runtime_errors = not (self._with_js or self._with_ll or self._with_dart or self._with_coffee or self._with_lua)
+ use_runtime_errors = not (self._with_js or self._with_ll or self._with_dart or self._with_coffee or self._with_lua or self._with_go)
use_runtime_errors = use_runtime_errors and self._with_runtime_exceptions
if use_runtime_errors:
@@ -1980,7 +2167,8 @@ def visit_Expr(self, node):
line = self.visit(node.value)
if line:
- writer.write(line)
+ #writer.write('('+line+')')
+ writer.write( line )
elif use_runtime_errors:
writer.write('pass')
@@ -2016,6 +2204,10 @@ def visit_Call(self, node):
name = self.visit(node.func)
+ if name in typedpython.GO_SPECIAL_CALLS:
+ name = typedpython.GO_SPECIAL_CALLS[ name ]
+ args = [self.visit(e) for e in node.args ]
+ return '%s( %s )' %(name, ','.join(args))
if self._with_rpc:
if not self._with_rpc_name:
@@ -2137,7 +2329,7 @@ def visit_Call(self, node):
self._direct_operators.add( kw.value.s )
else:
- raise SyntaxError( self.format_error(node) )
+ raise SyntaxError( self.format_error('invalid keyword option') )
elif self._with_ll or name == 'inline' or self._with_glsl:
F = self.visit(node.func)
@@ -2168,6 +2360,18 @@ def visit_Call(self, node):
else:
return '%s(%s)' %( F, ','.join(args) )
+ elif self._with_go:
+ args = list( map(self.visit, node.args) )
+ if node.keywords:
+ args.extend( ['%s=%s'%(x.arg,self.visit(x.value)) for x in node.keywords] )
+ if node.starargs:
+ args.append('*%s' %self.visit(node.starargs))
+
+ if isinstance(node.func, Name) and node.func.id in self._js_classes:
+ return '__new__%s(%s)' %( self.visit(node.func), ','.join(args) )
+ else:
+ return '%s(%s)' %( self.visit(node.func), ','.join(args) )
+
elif self._with_js or self._with_dart:
args = list( map(self.visit, node.args) )
@@ -2266,14 +2470,16 @@ def visit_Call(self, node):
elif isinstance(node.func, Name) and node.func.id in self._js_classes:
if node.keywords:
- kwargs = [ '%s=%s'%(x.arg, self.visit(x.value)) for x in node.keywords ]
+ kwargs = [ '%s:%s'%(x.arg, self.visit(x.value)) for x in node.keywords ]
if args:
a = ','.join(args)
- return 'new( %s(%s, %s) )' %( self.visit(node.func), a, ','.join(kwargs) )
+ return 'new( %s(%s, {%s}) )' %( self.visit(node.func), a, ','.join(kwargs) )
else:
- return 'new( %s(%s) )' %( self.visit(node.func), ','.join(kwargs) )
-
+ return 'new( %s({%s}) )' %( self.visit(node.func), ','.join(kwargs) )
else:
+ if node.kwargs:
+ args.append( self.visit(node.kwargs) )
+
a = ','.join(args)
return 'new( %s(%s) )' %( self.visit(node.func), a )
@@ -2323,7 +2529,11 @@ def visit_Call(self, node):
a = ( self.visit(node.func),self.visit(node.func), self.visit(node.starargs), ','.join(kwargs) )
return '%s.apply(%s, [].extend(%s).append({%s}) )' %a
else:
- return '%s({%s})' %( self.visit(node.func), ','.join(kwargs) )
+ func_name = self.visit(node.func)
+ if func_name == 'dict':
+ return '{%s}' %','.join(kwargs)
+ else:
+ return '%s({%s})' %( func_name, ','.join(kwargs) )
else:
if node.starargs:
@@ -2458,7 +2668,7 @@ def visit_Call(self, node):
elif hasattr(node,'constant') or name in self._builtin_functions:
if args and kwargs:
- return '%s([%s], {%s})' %(args, kwargs)
+ return '%s([%s], {%s})' %(name, args, kwargs)
elif args:
return '%s([%s], __NULL_OBJECT__)' %(name,args)
elif kwargs:
@@ -2513,10 +2723,11 @@ def visit_Call(self, node):
def visit_Lambda(self, node):
args = [self.visit(a) for a in node.args.args]
- #if self._with_js: ## TODO is it better to return a normal lambda
- # return """JS('(function (%s) {return %s})')""" %(','.join(args), self.visit(node.body))
- #else:
- if hasattr(node, 'keep_as_lambda'):
+
+ ##'__INLINE_FUNCTION__' from typedpython.py
+
+ if hasattr(node, 'keep_as_lambda') or args and args[0]=='__INLINE_FUNCTION__':
+ ## TODO lambda keyword args
self._in_lambda = True
a = '(lambda %s: %s)' %(','.join(args), self.visit(node.body))
self._in_lambda = False
@@ -2564,6 +2775,8 @@ def visit_FunctionDef(self, node):
gpu_vectorize = False
gpu_method = False
local_typedefs = []
+ typedef_chans = []
+ func_expr = None
## deprecated?
self._cached_property = None
@@ -2577,15 +2790,25 @@ def visit_FunctionDef(self, node):
if isinstance(decorator, Name) and decorator.id == 'gpu':
gpu = True
- elif isinstance(decorator, Call) and decorator.func.id == 'typedef':
+ elif isinstance(decorator, Call) and decorator.func.id == 'expression':
+ assert len(decorator.args)==1
+ func_expr = self.visit(decorator.args[0])
+
+ elif isinstance(decorator, Call) and decorator.func.id in ('typedef', 'typedef_chan'):
c = decorator
assert len(c.args) == 0 and len(c.keywords)
for kw in c.keywords:
- assert isinstance( kw.value, Name)
- self._typedef_vars[ kw.arg ] = kw.value.id
- self._instances[ kw.arg ] = kw.value.id
- self._func_typedefs[ kw.arg ] = kw.value.id
- local_typedefs.append( '%s=%s' %(kw.arg, kw.value.id))
+ #assert isinstance( kw.value, Name)
+ kwval = self.visit(kw.value)
+ self._typedef_vars[ kw.arg ] = kwval
+ self._instances[ kw.arg ] = kwval
+ self._func_typedefs[ kw.arg ] = kwval
+ local_typedefs.append( '%s=%s' %(kw.arg, kwval))
+ if decorator.func.id=='typedef_chan':
+ typedef_chans.append( kw.arg )
+ writer.write('@__typedef_chan__(%s=%s)' %(kw.arg, kwval))
+ else:
+ writer.write('@__typedef__(%s=%s)' %(kw.arg, kwval))
elif isinstance(decorator, Name) and decorator.id == 'inline':
@@ -2715,7 +2938,8 @@ def visit_FunctionDef(self, node):
## force python variable scope, and pass user type information to second stage of translation.
- ## the dart backend can use this extra type information.
+ ## the dart backend can use this extra type information for speed and debugging.
+ ## the Go and GLSL backends require this extra type information.
vars = []
local_typedef_names = set()
if not self._with_coffee:
@@ -2752,6 +2976,9 @@ def visit_FunctionDef(self, node):
if args_typedefs:
writer.write('@__typedef__(%s)' %','.join(args_typedefs))
+ if func_expr:
+ writer.write('@expression(%s)' %func_expr)
+
if not self._with_dart and not self._with_lua and not self._with_js and not javascript and not self._with_glsl:
writer.write('@__pyfunction__')
@@ -2796,11 +3023,28 @@ def visit_FunctionDef(self, node):
args.append('__variable_args__%s' %node.args.vararg)
+ writer.write( 'def %s( %s ):' % (node.name, ','.join(args)) )
+
+ elif self._with_go:
+
+ args = []
+ offset = len(node.args.args) - len(node.args.defaults)
+ for i, arg in enumerate(node.args.args):
+ a = arg.id
+ dindex = i - offset
+ if dindex >= 0 and node.args.defaults:
+ default = self.visit(node.args.defaults[dindex])
+ args.append( '%s=%s' %(a, default))
+ else:
+ args.append( a )
+
+ if node.args.vararg:
+ args.append( '*%s' %node.args.vararg )
writer.write( 'def %s( %s ):' % (node.name, ','.join(args)) )
- elif self._with_js or javascript or self._with_ll or self._with_glsl:
+ elif self._with_js or javascript or self._with_ll or self._with_glsl or self._with_go:
if self._with_glsl:
writer.write('@__glsl__')
@@ -2829,7 +3073,11 @@ def visit_FunctionDef(self, node):
writer.write( 'def %s( %s ):' % (node.name, ','.join(args)) )
else:
- writer.write('def %s(args, kwargs):' % node.name)
+ if len(node.args.defaults) or node.args.kwarg or len(node.args.args) or node.args.vararg:
+ writer.write('def %s(args, kwargs):' % node.name)
+ else:
+ writer.write('def %s():' % node.name)
+
writer.push()
## write local typedefs and var scope ##
@@ -2840,7 +3088,7 @@ def visit_FunctionDef(self, node):
writer.write('var(%s)' %a)
#####################################################################
- if self._with_dart or self._with_glsl:
+ if self._with_dart or self._with_glsl or self._with_go:
pass
elif self._with_js or javascript or self._with_ll:
@@ -2926,19 +3174,19 @@ def visit_FunctionDef(self, node):
# First check the arguments are well formed
# ie. that this function is not a callback of javascript code
+ if not self._with_go:
+ writer.write("""if instanceof(args,Array) and Object.prototype.toString.call(kwargs) == '[object Object]' and arguments.length==2:""")
+ writer.push()
+ writer.write('pass') # do nothing if it's not called from javascript
+ writer.pull()
- writer.write("""if instanceof(args,Array) and Object.prototype.toString.call(kwargs) == '[object Object]' and arguments.length==2:""")
- writer.push()
- writer.write('pass') # do nothing if it's not called from javascript
- writer.pull()
-
- writer.write('else:')
- writer.push()
- # If it's the case, move use ``arguments`` to ``args``
- writer.write('args = Array.prototype.slice.call(arguments, 0, __sig__.args.length)')
- # This means you can't pass keyword argument from javascript but we already knew that
- writer.write('kwargs = JSObject()')
- writer.pull()
+ writer.write('else:')
+ writer.push()
+ # If it's the case, move use ``arguments`` to ``args``
+ writer.write('args = Array.prototype.slice.call(arguments, 0, __sig__.args.length)')
+ # This means you can't pass keyword argument from javascript but we already knew that
+ writer.write('kwargs = JSObject()')
+ writer.pull()
@@ -3230,6 +3478,8 @@ def visit_Break(self, node):
writer.write('break')
def visit_For(self, node):
+ if node.orelse:
+ raise SyntaxError( self.format_error('the syntax for/else is deprecated') )
if self._cache_for_body_calls: ## TODO add option for this
for n in node.body:
@@ -3244,7 +3494,7 @@ def visit_For(self, node):
c.constant = True
self._call_ids += 1
- if self._with_glsl:
+ if self._with_glsl or self._with_go:
writer.write( 'for %s in %s:' %(self.visit(node.target), self.visit(node.iter)) )
writer.push()
map(self.visit, node.body)
@@ -3476,6 +3726,7 @@ def visit_While(self, node):
self._call_ids += 1
if node.orelse:
+ raise SyntaxError( self.format_error('the syntax while/else is deprecated'))
self._in_loop_with_else = True
writer.write('var(__break__)')
writer.write('__break__ = False')
@@ -3579,9 +3830,40 @@ def visit_With(self, node):
map(self.visit, node.body)
self._with_inline = False
+ elif isinstance( node.context_expr, Name ) and node.context_expr.id in EXTRA_WITH_TYPES:
+ writer.write('with %s:' %self.visit(node.context_expr))
+ writer.push()
+ for b in node.body:
+ a = self.visit(b)
+ if a: writer.write(a)
+ writer.pull()
+
+ elif isinstance( node.context_expr, ast.Call ) and isinstance(node.context_expr.func, ast.Name) and node.context_expr.func.id in EXTRA_WITH_TYPES:
+
+ restore = self._with_js
+ self._with_js = True
+ if node.context_expr.keywords:
+ assert len(node.context_expr.keywords)==1
+ k = node.context_expr.keywords[0].arg
+ v = self.visit(node.context_expr.keywords[0].value)
+ a = 'with %s(%s=%s):' %( self.visit(node.context_expr.func), k,v )
+ writer.write(a)
+ else:
+ writer.write('with %s:' %self.visit(node.context_expr))
+
+
+ self._with_js = restore
+
+ writer.push()
+ for b in node.body:
+ a = self.visit(b)
+ if a: writer.write(a)
+ writer.pull()
+
else:
- raise SyntaxError('improper use of "with" statement')
+ raise SyntaxError('invalid use of "with" statement')
+EXTRA_WITH_TYPES = ('__switch__', '__default__', '__case__', '__select__')
class GeneratorFunctionTransformer( PythonToPythonJS ):
'''
@@ -3595,38 +3877,15 @@ class GeneratorFunctionTransformer( PythonToPythonJS ):
'''
def __init__(self, node, compiler=None):
- self._with_ll = False
- self._with_js = False
- self._with_dart = False
- self._with_coffee = False
- self._with_lua = False
- self._with_rpc = None
- self._with_rpc_name = None
- self._with_inline = False
- self._in_while_test = False
- self._in_lambda = False
+ assert '_stack' in dir(compiler)
+ #self.__dict___ = compiler.__dict__ ## share all state
+ for name in dir(compiler):
+ if name not in dir(self):
+ setattr(self, name, (getattr(compiler, name)))
- if compiler._with_dart: ## TODO
- self._with_dart = True
- elif compiler._with_coffee:
- self._with_coffee = True
- elif compiler._with_lua:
- self._with_lua = True
- else:
- self._with_js = True
-
- self._typedef_vars = compiler._typedef_vars
- self._direct_operators = compiler._direct_operators
- self._builtin_functions = compiler._builtin_functions
- self._js_classes = compiler._js_classes
- self._global_functions = compiler._global_functions
- self._addop_ids = compiler._addop_ids
- self._cache_for_body_calls = False
- self._source = compiler._source
- self._instances = dict()
self._head_yield = False
self.visit( node )
- compiler._addop_ids = self._addop_ids
+ compiler._addop_ids = self._addop_ids ## note: need to keep id index insync
def visit_Yield(self, node):
if self._in_head:
@@ -3788,12 +4047,13 @@ def collect_generator_functions(node):
-def main(script, dart=False, coffee=False, lua=False, module_path=None):
+def main(script, dart=False, coffee=False, lua=False, go=False, module_path=None):
translator = PythonToPythonJS(
source = script,
dart = dart or '--dart' in sys.argv,
coffee = coffee,
lua = lua,
+ go = go,
module_path = module_path
)
diff --git a/pythonjs/pythonjs.js b/pythonjs/pythonjs.js
index 12796fe..fa6a00b 100644
--- a/pythonjs/pythonjs.js
+++ b/pythonjs/pythonjs.js
@@ -2,16 +2,16 @@ __NULL_OBJECT__ = Object.create(null);
__WEBWORKER__ = false;
__NODEJS__ = false;
__BROWSER__ = false;
-if (( typeof(process) ) != "undefined") {
+if ((!(typeof(process) instanceof Array ? JSON.stringify(typeof(process))==JSON.stringify("undefined") : typeof(process)==="undefined"))) {
__NODEJS__ = true;
}
-if (( typeof(window) ) != "undefined") {
+if ((!(typeof(window) instanceof Array ? JSON.stringify(typeof(window))==JSON.stringify("undefined") : typeof(window)==="undefined"))) {
__BROWSER__ = true;
}
-if (( typeof(importScripts) ) == "function") {
+if ((typeof(importScripts) instanceof Array ? JSON.stringify(typeof(importScripts))==JSON.stringify("function") : typeof(importScripts)==="function")) {
__WEBWORKER__ = true;
}
-__create_array__ = function() {
+var __create_array__ = function() {
"Used to fix a bug/feature of Javascript where new Array(number)\n created a array with number of undefined elements which is not\n what we want";
var i,array;
array = [];
@@ -23,7 +23,7 @@ __create_array__ = function() {
return array;
}
-__get__ = function(object, attribute, error_message) {
+var __get__ = function(object, attribute, error_message) {
"Retrieve an attribute, method, property, or wrapper function.\n\n method are actually functions which are converted to methods by\n prepending their arguments with the current object. Properties are\n not functions!\n\n DOM support:\n http://stackoverflow.com/questions/14202699/document-createelement-not-working\n https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof\n\n Direct JavaScript Calls:\n if an external javascript function is found, and it was not a wrapper that was generated here,\n check the function for a 'cached_wrapper' attribute, if none is found then generate a new\n wrapper, cache it on the function, and return the wrapper.\n ";
if (( object ) === null) {
if (error_message) {
@@ -40,21 +40,21 @@ __get__ = function(object, attribute, error_message) {
}
}
}
- if (( attribute ) == "__call__") {
- if (object.pythonscript_function || object.is_wrapper) {
+ if ((attribute instanceof Array ? JSON.stringify(attribute)==JSON.stringify("__call__") : attribute==="__call__")) {
+ if ((object.pythonscript_function || object.is_wrapper)) {
return object;
} else {
if (object.cached_wrapper) {
return object.cached_wrapper;
} else {
if ({}.toString.call(object) === '[object Function]') {
- var wrapper = function(args, kwargs) {
+ var wrapper = function(args, kwargs) {
var i,arg,keys;
- if (( args ) != null) {
+ if ((!(args instanceof Array ? JSON.stringify(args)==JSON.stringify(null) : args===null))) {
i = 0;
while (( i ) < args.length) {
arg = args[i];
- if (arg && ( typeof(arg) ) == "object") {
+ if ((arg && (typeof(arg) instanceof Array ? JSON.stringify(typeof(arg))==JSON.stringify("object") : typeof(arg)==="object"))) {
if (arg.jsify) {
args[i] = arg.jsify();
}
@@ -62,14 +62,14 @@ __get__ = function(object, attribute, error_message) {
i += 1;
}
}
- if (( kwargs ) != null) {
+ if ((!(kwargs instanceof Array ? JSON.stringify(kwargs)==JSON.stringify(null) : kwargs===null))) {
keys = __object_keys__(kwargs);
- if (( keys.length ) != 0) {
+ if ((!(keys.length instanceof Array ? JSON.stringify(keys.length)==JSON.stringify(0) : keys.length===0))) {
args.push(kwargs);
i = 0;
while (( i ) < keys.length) {
arg = kwargs[keys[i]];
- if (arg && ( typeof(arg) ) == "object") {
+ if ((arg && (typeof(arg) instanceof Array ? JSON.stringify(typeof(arg))==JSON.stringify("object") : typeof(arg)==="object"))) {
if (arg.jsify) {
kwargs[keys[i]] = arg.jsify();
}
@@ -93,10 +93,10 @@ __get__ = function(object, attribute, error_message) {
}
var attr;
attr = object[attribute];
- if (( __NODEJS__ ) === false && ( __WEBWORKER__ ) === false) {
+ if ((( __NODEJS__ ) === false && ( __WEBWORKER__ ) === false)) {
if (object instanceof HTMLDocument) {
if (typeof(attr) === 'function') {
- var wrapper = function(args, kwargs) {
+ var wrapper = function(args, kwargs) {
return attr.apply(object, args);
}
@@ -108,7 +108,7 @@ __get__ = function(object, attribute, error_message) {
} else {
if (object instanceof HTMLElement) {
if (typeof(attr) === 'function') {
- var wrapper = function(args, kwargs) {
+ var wrapper = function(args, kwargs) {
return attr.apply(object, args);
}
@@ -121,18 +121,18 @@ __get__ = function(object, attribute, error_message) {
}
}
if (( attr ) !== undefined) {
- if (( typeof(attr) ) == "function") {
+ if ((typeof(attr) instanceof Array ? JSON.stringify(typeof(attr))==JSON.stringify("function") : typeof(attr)==="function")) {
if (attr.pythonscript_function === undefined && attr.is_wrapper === undefined) {
- if (attr.prototype instanceof Object && ( Object.keys(attr.prototype).length ) > 0) {
+ if ((attr.prototype instanceof Object && ( Object.keys(attr.prototype).length ) > 0)) {
return attr;
}
- var wrapper = function(args, kwargs) {
+ var wrapper = function(args, kwargs) {
var i,arg,keys;
- if (( args ) != null) {
+ if ((!(args instanceof Array ? JSON.stringify(args)==JSON.stringify(null) : args===null))) {
i = 0;
while (( i ) < args.length) {
arg = args[i];
- if (arg && ( typeof(arg) ) == "object") {
+ if ((arg && (typeof(arg) instanceof Array ? JSON.stringify(typeof(arg))==JSON.stringify("object") : typeof(arg)==="object"))) {
if (arg.jsify) {
args[i] = arg.jsify();
}
@@ -140,14 +140,14 @@ __get__ = function(object, attribute, error_message) {
i += 1;
}
}
- if (( kwargs ) != null) {
+ if ((!(kwargs instanceof Array ? JSON.stringify(kwargs)==JSON.stringify(null) : kwargs===null))) {
keys = __object_keys__(kwargs);
- if (( keys.length ) != 0) {
+ if ((!(keys.length instanceof Array ? JSON.stringify(keys.length)==JSON.stringify(0) : keys.length===0))) {
args.push(kwargs);
i = 0;
while (( i ) < keys.length) {
arg = kwargs[keys[i]];
- if (arg && ( typeof(arg) ) == "object") {
+ if ((arg && (typeof(arg) instanceof Array ? JSON.stringify(typeof(arg))==JSON.stringify("object") : typeof(arg)==="object"))) {
if (arg.jsify) {
kwargs[keys[i]] = arg.jsify();
}
@@ -164,10 +164,10 @@ __get__ = function(object, attribute, error_message) {
return wrapper;
} else {
if (attr.is_classmethod) {
- var method = function() {
+ var method = function() {
var args;
args = Array.prototype.slice.call(arguments);
- if (args[0] instanceof Array && {}.toString.call(args[1]) === '[object Object]' && ( args.length ) == 2) {
+ if ((args[0] instanceof Array && {}.toString.call(args[1]) === '[object Object]' && (args.length instanceof Array ? JSON.stringify(args.length)==JSON.stringify(2) : args.length===2))) {
/*pass*/
} else {
args = [args, {}];
@@ -200,8 +200,8 @@ __get__ = function(object, attribute, error_message) {
if (( attribute ) in __class__.__unbound_methods__) {
attr = __class__.__unbound_methods__[attribute];
if (attr.fastdef) {
- var method = function(args, kwargs) {
- if (arguments && arguments[0]) {
+ var method = function(args, kwargs) {
+ if ((arguments && arguments[0])) {
arguments[0].splice(0, 0, object);
return attr.apply(this, arguments);
} else {
@@ -210,11 +210,11 @@ __get__ = function(object, attribute, error_message) {
}
} else {
- var method = function(args, kwargs) {
- if (( arguments.length ) == 0) {
+ var method = function(args, kwargs) {
+ if ((arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(0) : arguments.length===0)) {
return attr([object], __NULL_OBJECT__);
} else {
- if (args instanceof Array && ( typeof(kwargs) ) === "object" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && ( typeof(kwargs) ) === "object" && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
args.splice(0, 0, object);
if (( kwargs ) === undefined) {
return attr(args, __NULL_OBJECT__);
@@ -242,8 +242,8 @@ __get__ = function(object, attribute, error_message) {
return attr;
} else {
if (attr.fastdef) {
- var method = function(args, kwargs) {
- if (arguments && arguments[0]) {
+ var method = function(args, kwargs) {
+ if ((arguments && arguments[0])) {
arguments[0].splice(0, 0, object);
return attr.apply(this, arguments);
} else {
@@ -252,11 +252,11 @@ __get__ = function(object, attribute, error_message) {
}
} else {
- var method = function(args, kwargs) {
- if (( arguments.length ) == 0) {
+ var method = function(args, kwargs) {
+ if ((arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(0) : arguments.length===0)) {
return attr([object], __NULL_OBJECT__);
} else {
- if (args instanceof Array && ( typeof(kwargs) ) === "object" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && ( typeof(kwargs) ) === "object" && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
args.splice(0, 0, object);
if (( kwargs ) === undefined) {
return attr(args, __NULL_OBJECT__);
@@ -290,8 +290,8 @@ __get__ = function(object, attribute, error_message) {
if (( attr ) !== undefined) {
if ({}.toString.call(attr) === '[object Function]') {
if (attr.fastdef) {
- var method = function(args, kwargs) {
- if (arguments && arguments[0]) {
+ var method = function(args, kwargs) {
+ if ((arguments && arguments[0])) {
arguments[0].splice(0, 0, object);
return attr.apply(this, arguments);
} else {
@@ -300,11 +300,11 @@ __get__ = function(object, attribute, error_message) {
}
} else {
- var method = function(args, kwargs) {
- if (( arguments.length ) == 0) {
+ var method = function(args, kwargs) {
+ if ((arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(0) : arguments.length===0)) {
return attr([object], __NULL_OBJECT__);
} else {
- if (args instanceof Array && ( typeof(kwargs) ) === "object" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && ( typeof(kwargs) ) === "object" && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
args.splice(0, 0, object);
if (( kwargs ) === undefined) {
return attr(args, __NULL_OBJECT__);
@@ -353,16 +353,19 @@ __get__ = function(object, attribute, error_message) {
}
}
}
- if (( attribute ) == "__getitem__") {
- var wrapper = function(args, kwargs) {
- return object[args[0]];
+ if ((attribute instanceof Array ? JSON.stringify(attribute)==JSON.stringify("__getitem__") : attribute==="__getitem__")) {
+ var wrapper = function(args, kwargs) {
+ v = object[args[0]];
+ if (( v ) === undefined) {
+ throw new KeyError(args[0]);
+ }
}
wrapper.is_wrapper = true;
return wrapper;
} else {
- if (( attribute ) == "__setitem__") {
- var wrapper = function(args, kwargs) {
+ if ((attribute instanceof Array ? JSON.stringify(attribute)==JSON.stringify("__setitem__") : attribute==="__setitem__")) {
+ var wrapper = function(args, kwargs) {
object[args[0]] = args[1];
}
@@ -370,20 +373,20 @@ __get__ = function(object, attribute, error_message) {
return wrapper;
}
}
- if (typeof(object, "function") && object.is_wrapper) {
+ if ((typeof(object, "function") && object.is_wrapper)) {
return object.wrapped[attribute];
}
- if (( attribute ) == "__iter__" && object instanceof Object) {
- var wrapper = function(args, kwargs) {
+ if (((attribute instanceof Array ? JSON.stringify(attribute)==JSON.stringify("__iter__") : attribute==="__iter__") && object instanceof Object)) {
+ var wrapper = function(args, kwargs) {
return new __ArrayIterator(Object.keys(object), 0);
}
wrapper.is_wrapper = true;
return wrapper;
}
- if (( attribute ) == "__contains__" && object instanceof Object) {
- var wrapper = function(args, kwargs) {
- return ( Object.keys(object).indexOf(args[0]) ) != -1;
+ if (((attribute instanceof Array ? JSON.stringify(attribute)==JSON.stringify("__contains__") : attribute==="__contains__") && object instanceof Object)) {
+ var wrapper = function(args, kwargs) {
+ return (!(Object.keys(object).indexOf(args[0]) instanceof Array ? JSON.stringify(Object.keys(object).indexOf(args[0]))==JSON.stringify(-1) : Object.keys(object).indexOf(args[0])===-1));
}
wrapper.is_wrapper = true;
@@ -400,7 +403,7 @@ __get__ = function(object, attribute, error_message) {
}
}
-_get_upstream_attribute = function(base, attr) {
+var _get_upstream_attribute = function(base, attr) {
if (( attr ) in base) {
return base[attr];
}
@@ -412,7 +415,7 @@ _get_upstream_attribute = function(base, attr) {
}
}
-_get_upstream_property = function(base, attr) {
+var _get_upstream_property = function(base, attr) {
if (( attr ) in base.__properties__) {
return base.__properties__[attr];
}
@@ -424,9 +427,9 @@ _get_upstream_property = function(base, attr) {
}
}
-__set__ = function(object, attribute, value) {
+var __set__ = function(object, attribute, value) {
"\n __setattr__ is always called when an attribute is set,\n unlike __getattr__ that only triggers when an attribute is not found,\n this asymmetry is in fact part of the Python spec.\n note there is no __setattribute__\n\n In normal Python a property setter is not called before __setattr__,\n this is bad language design because the user has been more explicit\n in having the property setter.\n\n In PythonJS, property setters are called instead of __setattr__.\n ";
- if (( "__class__" ) in object && ( object.__class__.__setters__.indexOf(attribute) ) != -1) {
+ if ((( "__class__" ) in object && (!(object.__class__.__setters__.indexOf(attribute) instanceof Array ? JSON.stringify(object.__class__.__setters__.indexOf(attribute))==JSON.stringify(-1) : object.__class__.__setters__.indexOf(attribute)===-1)))) {
object[attribute] = value;
} else {
if (( "__setattr__" ) in object) {
@@ -437,7 +440,7 @@ __set__ = function(object, attribute, value) {
}
}
-__getargs__ = function(func_name, signature, args, kwargs) {
+var __getargs__ = function(func_name, signature, args, kwargs) {
"Based on ``signature`` and ``args``, ``kwargs`` parameters retrieve\n the actual parameters.\n\n This will set default keyword arguments and retrieve positional arguments\n in kwargs if their called as such";
if (( args ) === null) {
args = [];
@@ -481,34 +484,41 @@ __getargs__ = function(func_name, signature, args, kwargs) {
return out;
}
-try {
-/*pass*/
-} catch(__exception__) {
-console.trace();
-console.error(__exception__, __exception__.message);
-console.error("line 4: pythonjs.configure( runtime_exceptions=False )");
-throw new RuntimeError("line 4: pythonjs.configure( runtime_exceptions=False )");
-
-}
_PythonJS_UID = 0;
IndexError = function(msg) {this.message = msg || "";}; IndexError.prototype = Object.create(Error.prototype); IndexError.prototype.name = "IndexError";
KeyError = function(msg) {this.message = msg || "";}; KeyError.prototype = Object.create(Error.prototype); KeyError.prototype.name = "KeyError";
ValueError = function(msg) {this.message = msg || "";}; ValueError.prototype = Object.create(Error.prototype); ValueError.prototype.name = "ValueError";
AttributeError = function(msg) {this.message = msg || "";}; AttributeError.prototype = Object.create(Error.prototype);AttributeError.prototype.name = "AttributeError";
RuntimeError = function(msg) {this.message = msg || "";}; RuntimeError.prototype = Object.create(Error.prototype);RuntimeError.prototype.name = "RuntimeError";
-__gpu_object = function(cls, struct_name, data_name) {
+var __getfast__ = function(ob, attr) {
+ var v;
+ v = ob[attr];
+ if (( v ) === undefined) {
+ throw new AttributeError(attr);
+ } else {
+ return v;
+ }
+}
+
+var __wrap_function__ = function(f) {
+
+ f.is_wrapper = true;
+ return f;
+}
+
+var __gpu_object = function(cls, struct_name, data_name) {
cls.prototype.__struct_name__ = struct_name;
cls.prototype.__struct_data__ = data_name;
}
gpu = { "object":__gpu_object };
-glsljit_runtime = function(header) {
+var glsljit_runtime = function(header) {
return new GLSLJITRuntime(header);
}
-GLSLJITRuntime = function(header) {
+var GLSLJITRuntime = function(header) {
GLSLJITRuntime.__init__(this, header);
this.__class__ = GLSLJITRuntime;
this.__uid__ = ("" + _PythonJS_UID);
@@ -575,34 +585,34 @@ GLSLJITRuntime.prototype.define_structure = function(ob) {
integers = [];
structs = [];
struct_type = [];
- if (__test_if_true__(struct_name && __contains__(this.glsltypes, struct_name))) {
+ if (__test_if_true__((struct_name && __contains__(this.glsltypes, struct_name)))) {
return struct_name;
}
var __iter2 = dir(ob);
if (! (__iter2 instanceof Array || typeof __iter2 == "string" || __is_typed_array(__iter2) || __is_some_array(__iter2) )) { __iter2 = __object_keys__(__iter2) }
for (var __idx2=0; __idx2 < __iter2.length; __idx2++) {
var key = __iter2[ __idx2 ];
- if (__test_if_true__(( key.length ) == 1 && __contains__("0123456789", key))) {
+ if (__test_if_true__(((key.length instanceof Array ? JSON.stringify(key.length)==JSON.stringify(1) : key.length===1) && __contains__("0123456789", key)))) {
throw new RuntimeError(key);
}
t = typeof(ob[key]);
- if (__test_if_true__(( t ) == "object" && ob[key] instanceof Array && ob[key].length && ( typeof(ob[key][0]) ) == "number")) {
+ if (__test_if_true__(((t instanceof Array ? JSON.stringify(t)==JSON.stringify("object") : t==="object") && ob[key] instanceof Array && ob[key].length && (typeof(ob[key][0]) instanceof Array ? JSON.stringify(typeof(ob[key][0]))==JSON.stringify("number") : typeof(ob[key][0])==="number")))) {
struct_type.push(("ARY_" + key));
arrays.push(key);
} else {
- if (( t ) == "number") {
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("number") : t==="number")) {
struct_type.push(("NUM_" + key));
floats.push(key);
} else {
if (__test_if_true__(ob[key] instanceof Int16Array)) {
struct_type.push(("INT_" + key));
- if (( ob[key].length ) == 1) {
+ if ((ob[key].length instanceof Array ? JSON.stringify(ob[key].length)==JSON.stringify(1) : ob[key].length===1)) {
integers.push(key);
} else {
/*pass*/
}
} else {
- if (__test_if_true__(( t ) == "object" && ob[key].__struct_name__)) {
+ if (__test_if_true__(((t instanceof Array ? JSON.stringify(t)==JSON.stringify("object") : t==="object") && ob[key].__struct_name__))) {
struct_type.push(("S_" + key));
structs.push(key);
if (! (__contains__(this.struct_types, ob[key].__struct_name__))) {
@@ -649,7 +659,7 @@ GLSLJITRuntime.prototype.define_structure = function(ob) {
subtype = ob[key].__struct_name__;
member_list.append((((subtype + " ") + key) + ";"));
}
- if (( len(member_list) ) == 0) {
+ if ((len(member_list) instanceof Array ? JSON.stringify(len(member_list))==JSON.stringify(0) : len(member_list)===0)) {
throw new RuntimeError(struct_name);
}
members = "".join(member_list);
@@ -661,7 +671,7 @@ GLSLJITRuntime.prototype.define_structure = function(ob) {
GLSLJITRuntime.define_structure = function () { return GLSLJITRuntime.prototype.define_structure.apply(arguments[0], Array.prototype.slice.call(arguments,1)) };
GLSLJITRuntime.prototype.structure = function(ob, name) {
- var sname,args,o,wrapper,value,aname,stype;
+ var sname,stype,args,value,has_arrays,o,aname,wrapper;
wrapper = null;
if (__test_if_true__(ob instanceof Object)) {
/*pass*/
@@ -679,7 +689,7 @@ GLSLJITRuntime.prototype.structure = function(ob, name) {
stype = this.struct_types[sname];
if (! (__contains__(this.struct_types, sname))) {
if (__contains__(this.glsltypes, sname)) {
- if (( sname ) == "mat4") {
+ if ((sname instanceof Array ? JSON.stringify(sname)==JSON.stringify("mat4") : sname==="mat4")) {
if (__test_if_true__(ob.__struct_data__)) {
o = ob[ob.__struct_data__];
} else {
@@ -701,7 +711,11 @@ GLSLJITRuntime.prototype.structure = function(ob, name) {
throw new RuntimeError(("no method to pack structure: " + sname));
}
}
+ has_arrays = false;
if (__test_if_true__(stype)) {
+ if (( stype["arrays"].length ) > 0) {
+ has_arrays = true;
+ }
var __iter7 = stype["integers"];
if (! (__iter7 instanceof Array || typeof __iter7 == "string" || __is_typed_array(__iter7) || __is_some_array(__iter7) )) { __iter7 = __object_keys__(__iter7) }
for (var __idx7=0; __idx7 < __iter7.length; __idx7++) {
@@ -736,7 +750,12 @@ GLSLJITRuntime.prototype.structure = function(ob, name) {
}
}
args = ",".join(args);
- this.shader.push((((((((sname + " ") + name) + "=") + sname) + "(") + args) + ");"));
+ if (__test_if_true__(has_arrays)) {
+ this.shader.push((((((((sname + " ") + name) + "=") + sname) + "(") + args) + ");"));
+ } else {
+ this.header.push((((((((("const " + sname) + " ") + name) + "=") + sname) + "(") + args) + ");"));
+ }
+ return stype;
}
GLSLJITRuntime.structure = function () { return GLSLJITRuntime.prototype.structure.apply(arguments[0], Array.prototype.slice.call(arguments,1)) };
@@ -760,7 +779,7 @@ GLSLJITRuntime.prototype.array = function(ob, name) {
while (( i ) < ob.length) {
subarr = ob[i];
subname = __sprintf("%s_%s", [name, i]);
- if (( a.length ) == 0) {
+ if ((a.length instanceof Array ? JSON.stringify(a.length)==JSON.stringify(0) : a.length===0)) {
a.append((((("float " + subname) + "[") + subarr.length) + "]"));
} else {
a.append(((((";float " + subname) + "[") + subarr.length) + "]"));
@@ -778,7 +797,7 @@ GLSLJITRuntime.prototype.array = function(ob, name) {
}
this.shader.push("".join(a));
} else {
- if (__test_if_true__(ob[0] instanceof Object || ( ob[0].__class__ ) === dict)) {
+ if (__test_if_true__((ob[0] instanceof Object || ( ob[0].__class__ ) === dict))) {
i = 0;
while (( i ) < ob.length) {
this.structure(ob[i], ((name + "_") + i));
@@ -816,7 +835,7 @@ GLSLJITRuntime.prototype.object = function(ob, name) {
GLSLJITRuntime.object = function () { return GLSLJITRuntime.prototype.object.apply(arguments[0], Array.prototype.slice.call(arguments,1)) };
GLSLJITRuntime.prototype.unpack_array2d = function(arr, dims) {
var h,rows,w,row;
- if (( typeof(dims) ) == "number") {
+ if ((typeof(dims) instanceof Array ? JSON.stringify(typeof(dims))==JSON.stringify("number") : typeof(dims)==="number")) {
return arr;
}
var __r_1;
@@ -836,7 +855,7 @@ GLSLJITRuntime.prototype.unpack_array2d = function(arr, dims) {
}
}
__jsdict_pop(rows);
- if (( rows.length ) != h) {
+ if ((!(rows.length instanceof Array ? JSON.stringify(rows.length)==JSON.stringify(h) : rows.length===h))) {
console.log("ERROR: __unpack_array2d, invalid height.");
}
return rows;
@@ -845,7 +864,7 @@ GLSLJITRuntime.prototype.unpack_array2d = function(arr, dims) {
GLSLJITRuntime.unpack_array2d = function () { return GLSLJITRuntime.prototype.unpack_array2d.apply(arguments[0], Array.prototype.slice.call(arguments,1)) };
GLSLJITRuntime.prototype.unpack_vec4 = function(arr, dims) {
var rows,i,h,vec,w,row;
- if (( typeof(dims) ) == "number") {
+ if ((typeof(dims) instanceof Array ? JSON.stringify(typeof(dims))==JSON.stringify("number") : typeof(dims)==="number")) {
w = dims;
h = 1;
} else {
@@ -880,7 +899,7 @@ GLSLJITRuntime.prototype.unpack_vec4 = function(arr, dims) {
}
y += 1;
}
- if (( rows.length ) != h) {
+ if ((!(rows.length instanceof Array ? JSON.stringify(rows.length)==JSON.stringify(h) : rows.length===h))) {
console.log("ERROR: __unpack_vec4, invalid height.");
}
return rows;
@@ -909,14 +928,13 @@ GLSLJITRuntime.prototype.unpack_mat4 = function(arr) {
GLSLJITRuntime.unpack_mat4 = function () { return GLSLJITRuntime.prototype.unpack_mat4.apply(arguments[0], Array.prototype.slice.call(arguments,1)) };
GLSLJITRuntime.prototype.__properties__ = { };
GLSLJITRuntime.prototype.__unbound_methods__ = { };
-__getattr__ = function(ob, a) {
+var __getattr__ = function(ob, a) {
if (ob.__getattr__) {
return ob.__getattr__(a);
}
-}
-;__getattr__.is_wrapper = true;
-__test_if_true__ = function(ob) {
+};__getattr__.is_wrapper = true;
+var __test_if_true__ = function(ob) {
if (( ob ) === true) {
return true;
@@ -924,23 +942,23 @@ __test_if_true__ = function(ob) {
if (( ob ) === false) {
return false;
} else {
- if (( typeof(ob) ) == "string") {
- return ( ob.length ) != 0;
+ if ((typeof(ob) instanceof Array ? JSON.stringify(typeof(ob))==JSON.stringify("string") : typeof(ob)==="string")) {
+ return (!(ob.length instanceof Array ? JSON.stringify(ob.length)==JSON.stringify(0) : ob.length===0));
} else {
if (! (ob)) {
return false;
} else {
if (ob instanceof Array) {
- return ( ob.length ) != 0;
+ return (!(ob.length instanceof Array ? JSON.stringify(ob.length)==JSON.stringify(0) : ob.length===0));
} else {
- if (( typeof(ob) ) == "function") {
+ if ((typeof(ob) instanceof Array ? JSON.stringify(typeof(ob))==JSON.stringify("function") : typeof(ob)==="function")) {
return true;
} else {
- if (ob.__class__ && ( ob.__class__ ) === dict) {
- return ( Object.keys(ob["$wrapped"]).length ) != 0;
+ if ((ob.__class__ && ( ob.__class__ ) === dict)) {
+ return (!(Object.keys(ob["$wrapped"]).length instanceof Array ? JSON.stringify(Object.keys(ob["$wrapped"]).length)==JSON.stringify(0) : Object.keys(ob["$wrapped"]).length===0));
} else {
if (ob instanceof Object) {
- return ( Object.keys(ob).length ) != 0;
+ return (!(Object.keys(ob).length instanceof Array ? JSON.stringify(Object.keys(ob).length)==JSON.stringify(0) : Object.keys(ob).length===0));
} else {
return true;
}
@@ -951,20 +969,18 @@ __test_if_true__ = function(ob) {
}
}
}
-}
-;__test_if_true__.is_wrapper = true;
-__replace_method = function(ob, a, b) {
+};__test_if_true__.is_wrapper = true;
+var __replace_method = function(ob, a, b) {
- if (( typeof(ob) ) == "string") {
+ if ((typeof(ob) instanceof Array ? JSON.stringify(typeof(ob))==JSON.stringify("string") : typeof(ob)==="string")) {
return ob.split(a).join(b);
} else {
return ob.replace(a, b);
}
-}
-;__replace_method.is_wrapper = true;
-__split_method = function(ob, delim) {
+};__replace_method.is_wrapper = true;
+var __split_method = function(ob, delim) {
- if (( typeof(ob) ) == "string") {
+ if ((typeof(ob) instanceof Array ? JSON.stringify(typeof(ob))==JSON.stringify("string") : typeof(ob)==="string")) {
if (( delim ) === undefined) {
return ob.split(" ");
} else {
@@ -977,16 +993,27 @@ __split_method = function(ob, delim) {
return ob.split(delim);
}
}
+};__split_method.is_wrapper = true;
+__dom_array_types__ = [];
+if ((typeof(NodeList) instanceof Array ? JSON.stringify(typeof(NodeList))==JSON.stringify("function") : typeof(NodeList)==="function")) {
+ __dom_array_types__ = [NodeList, FileList, DOMStringList, HTMLCollection, SVGNumberList, SVGTransformList];
+ if ((typeof(DataTransferItemList) instanceof Array ? JSON.stringify(typeof(DataTransferItemList))==JSON.stringify("function") : typeof(DataTransferItemList)==="function")) {
+ __dom_array_types__.push(DataTransferItemList);
+ }
+ if ((typeof(HTMLAllCollection) instanceof Array ? JSON.stringify(typeof(HTMLAllCollection))==JSON.stringify("function") : typeof(HTMLAllCollection)==="function")) {
+ __dom_array_types__.push(HTMLAllCollection);
+ }
+ if ((typeof(SVGElementInstanceList) instanceof Array ? JSON.stringify(typeof(SVGElementInstanceList))==JSON.stringify("function") : typeof(SVGElementInstanceList)==="function")) {
+ __dom_array_types__.push(SVGElementInstanceList);
+ }
+ if ((typeof(ClientRectList) instanceof Array ? JSON.stringify(typeof(ClientRectList))==JSON.stringify("function") : typeof(ClientRectList)==="function")) {
+ __dom_array_types__.push(ClientRectList);
+ }
}
-;__split_method.is_wrapper = true;
-__is_some_array = function(ob) {
- var dom_array_types;
- if (( typeof(NodeList) ) == "function") {
- dom_array_types = [NodeList, FileList, ClientRectList, DOMStringList, HTMLCollection, HTMLAllCollection, SVGElementInstanceList, SVGNumberList, SVGTransformList];
- if (( typeof(DataTransferItemList) ) == "function") {
- dom_array_types.append(DataTransferItemList);
- }
- var __iter14 = dom_array_types;
+var __is_some_array = function(ob) {
+
+ if (( __dom_array_types__.length ) > 0) {
+ var __iter14 = __dom_array_types__;
if (! (__iter14 instanceof Array || typeof __iter14 == "string" || __is_typed_array(__iter14) || __is_some_array(__iter14) )) { __iter14 = __object_keys__(__iter14) }
for (var __idx14=0; __idx14 < __iter14.length; __idx14++) {
var t = __iter14[ __idx14 ];
@@ -998,18 +1025,18 @@ __is_some_array = function(ob) {
return false;
}
-__is_typed_array = function(ob) {
+var __is_typed_array = function(ob) {
- if (__test_if_true__(ob instanceof Int8Array || ob instanceof Uint8Array)) {
+ if (__test_if_true__((ob instanceof Int8Array || ob instanceof Uint8Array))) {
return true;
} else {
- if (__test_if_true__(ob instanceof Int16Array || ob instanceof Uint16Array)) {
+ if (__test_if_true__((ob instanceof Int16Array || ob instanceof Uint16Array))) {
return true;
} else {
- if (__test_if_true__(ob instanceof Int32Array || ob instanceof Uint32Array)) {
+ if (__test_if_true__((ob instanceof Int32Array || ob instanceof Uint32Array))) {
return true;
} else {
- if (__test_if_true__(ob instanceof Float32Array || ob instanceof Float64Array)) {
+ if (__test_if_true__((ob instanceof Float32Array || ob instanceof Float64Array))) {
return true;
} else {
return false;
@@ -1019,26 +1046,26 @@ __is_typed_array = function(ob) {
}
}
-__js_typed_array = function(t, a) {
+var __js_typed_array = function(t, a) {
var arr;
- if (( t ) == "i") {
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("i") : t==="i")) {
arr = new Int32Array(a.length);
}
arr.set(a);
return arr;
}
-__contains__ = function(ob, a) {
+var __contains__ = function(ob, a) {
var t;
t = typeof(ob);
- if (( t ) == "string") {
- if (( ob.indexOf(a) ) == -1) {
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("string") : t==="string")) {
+ if ((ob.indexOf(a) instanceof Array ? JSON.stringify(ob.indexOf(a))==JSON.stringify(-1) : ob.indexOf(a)===-1)) {
return false;
} else {
return true;
}
} else {
- if (( t ) == "number") {
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("number") : t==="number")) {
throw new TypeError;
} else {
if (__test_if_true__(__is_typed_array(ob))) {
@@ -1046,7 +1073,7 @@ __contains__ = function(ob, a) {
if (! (__iter15 instanceof Array || typeof __iter15 == "string" || __is_typed_array(__iter15) || __is_some_array(__iter15) )) { __iter15 = __object_keys__(__iter15) }
for (var __idx15=0; __idx15 < __iter15.length; __idx15++) {
var x = __iter15[ __idx15 ];
- if (( x ) == a) {
+ if ((x instanceof Array ? JSON.stringify(x)==JSON.stringify(a) : x===a)) {
return true;
}
}
@@ -1055,7 +1082,7 @@ __contains__ = function(ob, a) {
if (__test_if_true__(ob.__contains__)) {
return ob.__contains__(a);
} else {
- if (__test_if_true__(ob instanceof Object && Object.hasOwnProperty.call(ob, a))) {
+ if (__test_if_true__((ob instanceof Object && Object.hasOwnProperty.call(ob, a)))) {
return true;
} else {
return false;
@@ -1066,10 +1093,10 @@ __contains__ = function(ob, a) {
}
}
-__add_op = function(a, b) {
+var __add_op = function(a, b) {
var c,t;
t = typeof(a);
- if (__test_if_true__(( t ) == "string" || ( t ) == "number")) {
+ if (__test_if_true__(((t instanceof Array ? JSON.stringify(t)==JSON.stringify("string") : t==="string") || (t instanceof Array ? JSON.stringify(t)==JSON.stringify("number") : t==="number")))) {
return a+b;
} else {
if (__test_if_true__(a instanceof Array)) {
@@ -1087,13 +1114,13 @@ __add_op = function(a, b) {
}
}
-__mul_op = function(a, b) {
+var __mul_op = function(a, b) {
var c,arr,t;
t = typeof(a);
- if (( t ) == "number") {
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("number") : t==="number")) {
return a * b;
} else {
- if (( t ) == "string") {
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("string") : t==="string")) {
arr = [];
var i,i__end__;
i = 0;
@@ -1125,7 +1152,7 @@ __mul_op = function(a, b) {
}
}
-__jsdict = function(items) {
+var __jsdict = function(items) {
var d,key;
d = {};
var __iter16 = items;
@@ -1133,17 +1160,24 @@ __jsdict = function(items) {
for (var __idx16=0; __idx16 < __iter16.length; __idx16++) {
var item = __iter16[ __idx16 ];
key = item[0];
- if (__test_if_true__(key.__uid__)) {
- key = key.__uid__;
+ if (__test_if_true__(key instanceof Array)) {
+ key = JSON.stringify(key);
+ } else {
+ if (__test_if_true__(key.__uid__)) {
+ key = key.__uid__;
+ }
}
d[key] = item[1];
}
return d;
}
-__jsdict_get = function(ob, key, default_value) {
+var __jsdict_get = function(ob, key, default_value) {
if (__test_if_true__(ob instanceof Object)) {
+ if (__test_if_true__(key instanceof Array)) {
+ key = JSON.stringify(key);
+ }
if (__test_if_true__(key in ob)) {
return ob[key];
}
@@ -1157,16 +1191,19 @@ __jsdict_get = function(ob, key, default_value) {
}
}
-__jsdict_set = function(ob, key, value) {
+var __jsdict_set = function(ob, key, value) {
if (__test_if_true__(ob instanceof Object)) {
+ if (__test_if_true__(key instanceof Array)) {
+ key = JSON.stringify(key);
+ }
ob[key] = value;
} else {
ob.set(key,value);
}
}
-__jsdict_keys = function(ob) {
+var __jsdict_keys = function(ob) {
if (__test_if_true__(ob instanceof Object)) {
return Object.keys( ob );
@@ -1175,7 +1212,7 @@ __jsdict_keys = function(ob) {
}
}
-__jsdict_values = function(ob) {
+var __jsdict_values = function(ob) {
var arr,value;
if (__test_if_true__(ob instanceof Object)) {
arr = [];
@@ -1194,9 +1231,9 @@ __jsdict_values = function(ob) {
}
}
-__jsdict_items = function(ob) {
+var __jsdict_items = function(ob) {
var arr,value;
- if (__test_if_true__(ob instanceof Object || ( ob.items ) === undefined)) {
+ if (__test_if_true__((ob instanceof Object || ( ob.items ) === undefined))) {
arr = [];
var __iter18 = ob;
if (! (__iter18 instanceof Array || typeof __iter18 == "string" || __is_typed_array(__iter18) || __is_some_array(__iter18) )) { __iter18 = __object_keys__(__iter18) }
@@ -1213,7 +1250,7 @@ __jsdict_items = function(ob) {
}
}
-__jsdict_pop = function(ob, key, _kwargs_) {
+var __jsdict_pop = function(ob, key, _kwargs_) {
var v;
if (!( _kwargs_ instanceof Object )) {;
var _kwargs_ = {ob: arguments[0],key: arguments[1],_default: arguments[2]};
@@ -1248,7 +1285,7 @@ __jsdict_pop = function(ob, key, _kwargs_) {
}
}
-dir = function(ob) {
+var dir = function(ob) {
if (__test_if_true__(ob instanceof Object)) {
return Object.keys( ob );
@@ -1257,7 +1294,7 @@ dir = function(ob) {
}
}
-__object_keys__ = function(ob) {
+var __object_keys__ = function(ob) {
var arr;
"\n notes:\n . Object.keys(ob) will not work because we create PythonJS objects using `Object.create(null)`\n . this is different from Object.keys because it traverses the prototype chain.\n ";
arr = [];
@@ -1265,7 +1302,7 @@ __object_keys__ = function(ob) {
return arr;
}
-__bind_property_descriptors__ = function(o, klass) {
+var __bind_property_descriptors__ = function(o, klass) {
var prop,desc;
var __iter19 = klass.__properties__;
if (! (__iter19 instanceof Array || typeof __iter19 == "string" || __is_typed_array(__iter19) || __is_some_array(__iter19) )) { __iter19 = __object_keys__(__iter19) }
@@ -1289,9 +1326,9 @@ __bind_property_descriptors__ = function(o, klass) {
}
}
-__generate_getter__ = function(klass, o, n) {
+var __generate_getter__ = function(klass, o, n) {
- var __lambda__ = function() {
+ var __lambda__ = function() {
return klass.__properties__[n]["get"]([o], __jsdict([]));
}
@@ -1299,9 +1336,9 @@ __generate_getter__ = function(klass, o, n) {
return __lambda__;
}
-__generate_setter__ = function(klass, o, n) {
+var __generate_setter__ = function(klass, o, n) {
- var __lambda__ = function(v) {
+ var __lambda__ = function(v) {
return klass.__properties__[n]["set"]([o, v], __jsdict([]));
}
@@ -1309,7 +1346,7 @@ __generate_setter__ = function(klass, o, n) {
return __lambda__;
}
-__sprintf = function(fmt, args) {
+var __sprintf = function(fmt, args) {
var chunks,item,arr;
if (__test_if_true__(args instanceof Array)) {
chunks = fmt.split("%s");
@@ -1325,10 +1362,10 @@ __sprintf = function(fmt, args) {
break;
}
item = args[i];
- if (( typeof(item) ) == "string") {
+ if ((typeof(item) instanceof Array ? JSON.stringify(typeof(item))==JSON.stringify("string") : typeof(item)==="string")) {
arr.append(item);
} else {
- if (( typeof(item) ) == "number") {
+ if ((typeof(item) instanceof Array ? JSON.stringify(typeof(item))==JSON.stringify("number") : typeof(item)==="number")) {
arr.append(("" + item));
} else {
arr.append(Object.prototype.toString.call(item));
@@ -1342,7 +1379,7 @@ __sprintf = function(fmt, args) {
}
}
-__create_class__ = function(class_name, parents, attrs, props) {
+var __create_class__ = function(class_name, parents, attrs, props) {
var f,klass,prop;
"Create a PythonScript class";
klass = Object.create(null);
@@ -1356,20 +1393,20 @@ __create_class__ = function(class_name, parents, attrs, props) {
if (! (__iter22 instanceof Array || typeof __iter22 == "string" || __is_typed_array(__iter22) || __is_some_array(__iter22) )) { __iter22 = __object_keys__(__iter22) }
for (var __idx22=0; __idx22 < __iter22.length; __idx22++) {
var key = __iter22[ __idx22 ];
- if (( typeof(attrs[key]) ) == "function") {
+ if ((typeof(attrs[key]) instanceof Array ? JSON.stringify(typeof(attrs[key]))==JSON.stringify("function") : typeof(attrs[key])==="function")) {
klass.__all_method_names__.push(key);
f = attrs[key];
- if (__test_if_true__(hasattr(f, "is_classmethod") && f.is_classmethod)) {
+ if (__test_if_true__((hasattr(f, "is_classmethod") && f.is_classmethod))) {
/*pass*/
} else {
- if (__test_if_true__(hasattr(f, "is_staticmethod") && f.is_staticmethod)) {
+ if (__test_if_true__((hasattr(f, "is_staticmethod") && f.is_staticmethod))) {
/*pass*/
} else {
klass.__unbound_methods__[key] = attrs[key];
}
}
}
- if (( key ) == "__getattribute__") {
+ if ((key instanceof Array ? JSON.stringify(key)==JSON.stringify("__getattribute__") : key==="__getattribute__")) {
continue
}
klass[key] = attrs[key];
@@ -1394,7 +1431,7 @@ __create_class__ = function(class_name, parents, attrs, props) {
Array.prototype.push.apply(klass.__setters__, base.__setters__);
Array.prototype.push.apply(klass.__all_method_names__, base.__all_method_names__);
}
- var __call__ = function() {
+ var __call__ = function() {
var has_getattr,wrapper,object,has_getattribute;
"Create a PythonJS object";
object = Object.create(null);
@@ -1406,15 +1443,15 @@ __create_class__ = function(class_name, parents, attrs, props) {
if (! (__iter25 instanceof Array || typeof __iter25 == "string" || __is_typed_array(__iter25) || __is_some_array(__iter25) )) { __iter25 = __object_keys__(__iter25) }
for (var __idx25=0; __idx25 < __iter25.length; __idx25++) {
var name = __iter25[ __idx25 ];
- if (( name ) == "__getattribute__") {
+ if ((name instanceof Array ? JSON.stringify(name)==JSON.stringify("__getattribute__") : name==="__getattribute__")) {
has_getattribute = true;
} else {
- if (( name ) == "__getattr__") {
+ if ((name instanceof Array ? JSON.stringify(name)==JSON.stringify("__getattr__") : name==="__getattr__")) {
has_getattr = true;
} else {
wrapper = __get__(object, name);
if (__test_if_true__(! (wrapper.is_wrapper))) {
- console.log("RUNTIME ERROR: failed to get wrapper for:", name);
+ console.log(["RUNTIME ERROR: failed to get wrapper for:", name]);
}
}
}
@@ -1437,11 +1474,11 @@ __create_class__ = function(class_name, parents, attrs, props) {
return klass;
}
-type = function(args, kwargs) {
+var type = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{"bases": null, "class_dict": null},args:["ob_or_class_name", "bases", "class_dict"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1451,19 +1488,18 @@ type = function(args, kwargs) {
var ob_or_class_name = __args__['ob_or_class_name'];
var bases = __args__['bases'];
var class_dict = __args__['class_dict'];
- "\n type(object) -> the object's type\n type(name, bases, dict) -> a new(type ## broken? - TODO test)\n ";
- if (__test_if_true__(( bases ) === null && ( class_dict ) === null)) {
+ "\n type(object) -> the object's type\n type(name, bases, dict) -> a __new__>>type ## broken? - TODO test\n ";
+ if (__test_if_true__((( bases ) === null && ( class_dict ) === null))) {
return ob_or_class_name.__class__;
} else {
return create_class(ob_or_class_name, bases, class_dict);
}
-}
-;type.is_wrapper = true;
-hasattr = function(args, kwargs) {
+};type.is_wrapper = true;
+var hasattr = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["ob", "attr"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1473,13 +1509,12 @@ hasattr = function(args, kwargs) {
var ob = __args__['ob'];
var attr = __args__['attr'];
return Object.hasOwnProperty.call(ob, attr);
-}
-;hasattr.is_wrapper = true;
-getattr = function(args, kwargs) {
+};hasattr.is_wrapper = true;
+var getattr = function(args, kwargs) {
var prop;
var __sig__,__args__;
__sig__ = { kwargs:{"property": false},args:["ob", "attr", "property"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1491,21 +1526,20 @@ getattr = function(args, kwargs) {
var property = __args__['property'];
if (__test_if_true__(property)) {
prop = _get_upstream_property(ob.__class__, attr);
- if (__test_if_true__(prop && prop["get"])) {
+ if (__test_if_true__((prop && prop["get"]))) {
return prop["get"]([ob], __jsdict([]));
} else {
- console.log("ERROR: getattr property error", prop);
+ console.log(["ERROR: getattr property error", prop]);
}
} else {
return __get__(ob, attr);
}
-}
-;getattr.is_wrapper = true;
-setattr = function(args, kwargs) {
+};getattr.is_wrapper = true;
+var setattr = function(args, kwargs) {
var prop;
var __sig__,__args__;
__sig__ = { kwargs:{"property": false},args:["ob", "attr", "value", "property"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1518,21 +1552,20 @@ setattr = function(args, kwargs) {
var property = __args__['property'];
if (__test_if_true__(property)) {
prop = _get_upstream_property(ob.__class__, attr);
- if (__test_if_true__(prop && prop["set"])) {
+ if (__test_if_true__((prop && prop["set"]))) {
prop["set"]([ob, value], __jsdict([]));
} else {
- console.log("ERROR: setattr property error", prop);
+ console.log(["ERROR: setattr property error", prop]);
}
} else {
__set__(ob, attr, value);
}
-}
-;setattr.is_wrapper = true;
-issubclass = function(args, kwargs) {
+};setattr.is_wrapper = true;
+var issubclass = function(args, kwargs) {
var i,bases;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["C", "B"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1546,20 +1579,19 @@ issubclass = function(args, kwargs) {
}
bases = C.__bases__;
i = 0;
- while (( i ) < __get__(bases, "length", "missing attribute `length` - line 610: while i < bases.length:")) {
- if (__test_if_true__(issubclass([((bases instanceof Array) ? bases[i] : __get__(bases, "__getitem__", "line 611: if issubclass( bases[i], B ):")([i], __NULL_OBJECT__)), B], __NULL_OBJECT__))) {
+ while (( i ) < __get__(bases, "length", "missing attribute `length` - line 655: while i < bases.length:")) {
+ if (__test_if_true__(issubclass([((bases instanceof Array) ? bases[i] : __get__(bases, "__getitem__", "line 656: if issubclass( bases[i], B ):")([i], __NULL_OBJECT__)), B], __NULL_OBJECT__))) {
return true;
}
i += 1;
}
return false;
-}
-;issubclass.is_wrapper = true;
-isinstance = function(args, kwargs) {
+};issubclass.is_wrapper = true;
+var isinstance = function(args, kwargs) {
var ob_class;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["ob", "klass"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1568,10 +1600,10 @@ isinstance = function(args, kwargs) {
__args__ = __getargs__("isinstance", __sig__, args, kwargs);
var ob = __args__['ob'];
var klass = __args__['klass'];
- if (__test_if_true__(( ob ) === undefined || ( ob ) === null)) {
+ if (__test_if_true__((( ob ) === undefined || ( ob ) === null))) {
return false;
} else {
- if (__test_if_true__(ob instanceof Array && ( klass ) === list)) {
+ if (__test_if_true__((ob instanceof Array && ( klass ) === list))) {
return true;
} else {
if (__test_if_true__(! (Object.hasOwnProperty.call(ob, "__class__")))) {
@@ -1585,13 +1617,12 @@ isinstance = function(args, kwargs) {
} else {
return issubclass([ob_class, klass], __NULL_OBJECT__);
}
-}
-;isinstance.is_wrapper = true;
-int = function(args, kwargs) {
+};isinstance.is_wrapper = true;
+var int = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["a"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1604,20 +1635,19 @@ int = function(args, kwargs) {
throw new ValueError("not a number");
}
return a;
-}
-;int.is_wrapper = true;
-int16 = function(a) {
+};int.is_wrapper = true;
+var int16 = function(a) {
var arr;
arr = new Int16Array(1);
arr[0] = a;
return arr;
}
-float = function(args, kwargs) {
-
+var float = function(args, kwargs) {
+ var b;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["a"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1625,18 +1655,26 @@ float = function(args, kwargs) {
}
__args__ = __getargs__("float", __sig__, args, kwargs);
var a = __args__['a'];
- a = Number(a);
- if (__test_if_true__(isNaN(a))) {
- throw new ValueError("not a number");
+ if ((typeof(a) instanceof Array ? JSON.stringify(typeof(a))==JSON.stringify("string") : typeof(a)==="string")) {
+ if ((a.lower() instanceof Array ? JSON.stringify(a.lower())==JSON.stringify("nan") : a.lower()==="nan")) {
+ return NaN;
+ } else {
+ if ((a.lower() instanceof Array ? JSON.stringify(a.lower())==JSON.stringify("inf") : a.lower()==="inf")) {
+ return Infinity;
+ }
+ }
}
- return a;
-}
-;float.is_wrapper = true;
-round = function(args, kwargs) {
- var y,x,c,b;
+ b = Number(a);
+ if (__test_if_true__(isNaN(b))) {
+ throw new ValueError(("can not convert to float: " + a));
+ }
+ return b;
+};float.is_wrapper = true;
+var round = function(args, kwargs) {
+ var p,b;
var __sig__,__args__;
- __sig__ = { kwargs:{},args:["a", "places"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ __sig__ = { kwargs:{"places": 0},args:["a", "places"] };
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1646,21 +1684,18 @@ round = function(args, kwargs) {
var a = __args__['a'];
var places = __args__['places'];
b = ("" + a);
- if (( b.indexOf(".") ) == -1) {
+ if ((b.indexOf(".") instanceof Array ? JSON.stringify(b.indexOf("."))==JSON.stringify(-1) : b.indexOf(".")===-1)) {
return a;
} else {
- c = b.split(".");
- x = c[0];
- y = c[1].substring(0, places);
- return parseFloat(((x + ".") + y));
+ p = Math.pow(10, places);
+ return (Math.round((a * p)) / p);
}
-}
-;round.is_wrapper = true;
-str = function(args, kwargs) {
+};round.is_wrapper = true;
+var str = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["s"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -1669,14 +1704,13 @@ str = function(args, kwargs) {
__args__ = __getargs__("str", __sig__, args, kwargs);
var s = __args__['s'];
return ("" + s);
-}
-;str.is_wrapper = true;
-_setup_str_prototype = function(args, kwargs) {
+};str.is_wrapper = true;
+var _setup_str_prototype = function() {
"\n Extend JavaScript String.prototype with methods that implement the Python str API.\n The decorator @String.prototype.[name] assigns the function to the prototype,\n and ensures that the special 'this' variable will work.\n ";
- var func = function(a) {
+ var func = function(a) {
- if (( this.indexOf(a) ) == -1) {
+ if ((this.indexOf(a) instanceof Array ? JSON.stringify(this.indexOf(a))==JSON.stringify(-1) : this.indexOf(a)===-1)) {
return false;
} else {
return true;
@@ -1684,7 +1718,7 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "__contains__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(index) {
+ var func = function(index) {
if (( index ) < 0) {
return this[(this.length + index)];
@@ -1694,13 +1728,13 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "get", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(self) {
+ var func = function(self) {
return __get__(Iterator, "__call__")([this, 0], __NULL_OBJECT__);
}
Object.defineProperty(String.prototype, "__iter__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(idx) {
+ var func = function(idx) {
if (( idx ) < 0) {
return this[(this.length + idx)];
@@ -1710,15 +1744,15 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "__getitem__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return this.length;
}
Object.defineProperty(String.prototype, "__len__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(start, stop, step) {
+ var func = function(start, stop, step) {
- if (__test_if_true__(( start ) === undefined && ( stop ) === undefined && ( step ) == -1)) {
+ if (__test_if_true__((( start ) === undefined && ( stop ) === undefined && (step instanceof Array ? JSON.stringify(step)==JSON.stringify(-1) : step===-1)))) {
return this.split("").reverse().join("");
} else {
if (( stop ) < 0) {
@@ -1729,21 +1763,21 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "__getslice__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return this.split("\n");
}
Object.defineProperty(String.prototype, "splitlines", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return this.trim();
}
Object.defineProperty(String.prototype, "strip", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(a) {
+ var func = function(a) {
- if (( this.substring(0, a.length) ) == a) {
+ if ((this.substring(0, a.length) instanceof Array ? JSON.stringify(this.substring(0, a.length))==JSON.stringify(a) : this.substring(0, a.length)===a)) {
return true;
} else {
return false;
@@ -1751,9 +1785,9 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "startswith", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(a) {
+ var func = function(a) {
- if (( this.substring((this.length - a.length), this.length) ) == a) {
+ if ((this.substring((this.length - a.length), this.length) instanceof Array ? JSON.stringify(this.substring((this.length - a.length), this.length))==JSON.stringify(a) : this.substring((this.length - a.length), this.length)===a)) {
return true;
} else {
return false;
@@ -1761,7 +1795,7 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "endswith", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(a) {
+ var func = function(a) {
var i,arr,out;
out = "";
if (__test_if_true__(a instanceof Array)) {
@@ -1784,35 +1818,35 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "join", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return this.toUpperCase();
}
Object.defineProperty(String.prototype, "upper", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return this.toLowerCase();
}
Object.defineProperty(String.prototype, "lower", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(a) {
+ var func = function(a) {
var i;
i = this.indexOf(a);
- if (( i ) == -1) {
+ if ((i instanceof Array ? JSON.stringify(i)==JSON.stringify(-1) : i===-1)) {
throw new ValueError((a + " - not in string"));
}
return i;
}
Object.defineProperty(String.prototype, "index", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(a) {
+ var func = function(a) {
return this.indexOf(a);
}
Object.defineProperty(String.prototype, "find", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
var digits;
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var __iter27 = this;
@@ -1829,7 +1863,7 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "isdigit", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
var digits;
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."];
var __iter28 = this;
@@ -1846,19 +1880,19 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "isnumber", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(encoding) {
+ var func = function(encoding) {
return this;
}
Object.defineProperty(String.prototype, "decode", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(encoding) {
+ var func = function(encoding) {
return this;
}
Object.defineProperty(String.prototype, "encode", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(fmt) {
+ var func = function(fmt) {
var keys,r;
r = this;
keys = Object.keys(fmt);
@@ -1873,13 +1907,12 @@ _setup_str_prototype = function(args, kwargs) {
}
Object.defineProperty(String.prototype, "format", { enumerable:false,value:func,writeable:true,configurable:true });
-}
-;_setup_str_prototype.is_wrapper = true;
+};_setup_str_prototype.is_wrapper = true;
_setup_str_prototype();
-__sort_method = function(ob) {
+var __sort_method = function(ob) {
if (__test_if_true__(ob instanceof Array)) {
- var f = function(a, b) {
+ var f = function(a, b) {
if (( a ) < b) {
return -1;
@@ -1898,14 +1931,14 @@ __sort_method = function(ob) {
}
}
-_setup_array_prototype = function(args, kwargs) {
+var _setup_array_prototype = function() {
- var func = function() {
+ var func = function() {
var i,item;
i = 0;
while (( i ) < this.length) {
item = this[i];
- if (( typeof(item) ) == "object") {
+ if ((typeof(item) instanceof Array ? JSON.stringify(typeof(item))==JSON.stringify("object") : typeof(item)==="object")) {
if (__test_if_true__(item.jsify)) {
this[i] = item.jsify();
}
@@ -1916,9 +1949,9 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "jsify", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(a) {
+ var func = function(a) {
- if (( this.indexOf(a) ) == -1) {
+ if ((this.indexOf(a) instanceof Array ? JSON.stringify(this.indexOf(a))==JSON.stringify(-1) : this.indexOf(a)===-1)) {
return false;
} else {
return true;
@@ -1926,19 +1959,19 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "__contains__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return this.length;
}
Object.defineProperty(Array.prototype, "__len__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(index) {
+ var func = function(index) {
return this[index];
}
Object.defineProperty(Array.prototype, "get", { enumerable:false,value:func,writeable:true,configurable:true });
- var __getitem__ = function(index) {
+ var __getitem__ = function(index) {
if (( index ) < 0) {
index = (this.length + index);
@@ -1947,7 +1980,7 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "__getitem__", { enumerable:false,value:__getitem__,writeable:true,configurable:true });
- var __setitem__ = function(index, value) {
+ var __setitem__ = function(index, value) {
if (( index ) < 0) {
index = (this.length + index);
@@ -1956,24 +1989,26 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "__setitem__", { enumerable:false,value:__setitem__,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return __get__(Iterator, "__call__")([this, 0], __NULL_OBJECT__);
}
Object.defineProperty(Array.prototype, "__iter__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(start, stop, step) {
+ var func = function(start, stop, step) {
var i,arr,n;
arr = [];
start = (start | 0);
- stop = (stop | this.length);
+ if (( stop ) === undefined) {
+ stop = this.length;
+ }
if (( start ) < 0) {
start = (this.length + start);
}
if (( stop ) < 0) {
stop = (this.length + stop);
}
- if (( typeof(step) ) == "number") {
+ if ((typeof(step) instanceof Array ? JSON.stringify(typeof(step))==JSON.stringify("number") : typeof(step)==="number")) {
if (( step ) < 0) {
i = start;
while (( i ) >= 0) {
@@ -2002,7 +2037,7 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "__getslice__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(start, stop, step, items) {
+ var func = function(start, stop, step, items) {
var arr;
if (( start ) === undefined) {
start = 0;
@@ -2021,14 +2056,14 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "__setslice__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(item) {
+ var func = function(item) {
this.push(item);
return this;
}
Object.defineProperty(Array.prototype, "append", { enumerable:false,value:func,writeable:true,configurable:true });
- var extend = function(other) {
+ var extend = function(other) {
var __iter31 = other;
if (! (__iter31 instanceof Array || typeof __iter31 == "string" || __is_typed_array(__iter31) || __is_some_array(__iter31) )) { __iter31 = __object_keys__(__iter31) }
@@ -2040,14 +2075,14 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "extend", { enumerable:false,value:extend,writeable:true,configurable:true });
- var func = function(item) {
+ var func = function(item) {
var index;
index = this.indexOf(item);
this.splice(index, 1);
}
Object.defineProperty(Array.prototype, "remove", { enumerable:false,value:func,writeable:true,configurable:true });
- var insert = function(index, obj) {
+ var insert = function(index, obj) {
if (( index ) < 0) {
index = (this.length + index);
@@ -2056,13 +2091,13 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "insert", { enumerable:false,value:insert,writeable:true,configurable:true });
- var index = function(obj) {
+ var index = function(obj) {
return this.indexOf(obj);
}
Object.defineProperty(Array.prototype, "index", { enumerable:false,value:index,writeable:true,configurable:true });
- var count = function(obj) {
+ var count = function(obj) {
var a;
a = 0;
var __iter32 = this;
@@ -2077,7 +2112,7 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "count", { enumerable:false,value:count,writeable:true,configurable:true });
- var func = function(x, low, high) {
+ var func = function(x, low, high) {
var a,mid;
if (( low ) === undefined) {
low = 0;
@@ -2098,11 +2133,11 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "bisect", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(other) {
+ var func = function(other) {
var f;
- var __lambda__ = function(i) {
+ var __lambda__ = function(i) {
- return ( other.indexOf(i) ) == -1;
+ return (other.indexOf(i) instanceof Array ? JSON.stringify(other.indexOf(i))==JSON.stringify(-1) : other.indexOf(i)===-1);
}
f = __lambda__;
@@ -2110,11 +2145,11 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "difference", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(other) {
+ var func = function(other) {
var f;
- var __lambda__ = function(i) {
+ var __lambda__ = function(i) {
- return ( other.indexOf(i) ) != -1;
+ return (!(other.indexOf(i) instanceof Array ? JSON.stringify(other.indexOf(i))==JSON.stringify(-1) : other.indexOf(i)===-1));
}
f = __lambda__;
@@ -2122,13 +2157,13 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "intersection", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(other) {
+ var func = function(other) {
var __iter33 = this;
if (! (__iter33 instanceof Array || typeof __iter33 == "string" || __is_typed_array(__iter33) || __is_some_array(__iter33) )) { __iter33 = __object_keys__(__iter33) }
for (var __idx33=0; __idx33 < __iter33.length; __idx33++) {
var item = __iter33[ __idx33 ];
- if (( other.indexOf(item) ) == -1) {
+ if ((other.indexOf(item) instanceof Array ? JSON.stringify(other.indexOf(item))==JSON.stringify(-1) : other.indexOf(item)===-1)) {
return false;
}
}
@@ -2136,7 +2171,7 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "issubset", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
var i,arr;
arr = [];
i = 0;
@@ -2148,14 +2183,13 @@ _setup_array_prototype = function(args, kwargs) {
}
Object.defineProperty(Array.prototype, "copy", { enumerable:false,value:func,writeable:true,configurable:true });
-}
-;_setup_array_prototype.is_wrapper = true;
+};_setup_array_prototype.is_wrapper = true;
_setup_array_prototype();
-_setup_nodelist_prototype = function(args, kwargs) {
+var _setup_nodelist_prototype = function() {
- var func = function(a) {
+ var func = function(a) {
- if (( this.indexOf(a) ) == -1) {
+ if ((this.indexOf(a) instanceof Array ? JSON.stringify(this.indexOf(a))==JSON.stringify(-1) : this.indexOf(a)===-1)) {
return false;
} else {
return true;
@@ -2163,19 +2197,19 @@ _setup_nodelist_prototype = function(args, kwargs) {
}
Object.defineProperty(NodeList.prototype, "__contains__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return this.length;
}
Object.defineProperty(NodeList.prototype, "__len__", { enumerable:false,value:func,writeable:true,configurable:true });
- var func = function(index) {
+ var func = function(index) {
return this[index];
}
Object.defineProperty(NodeList.prototype, "get", { enumerable:false,value:func,writeable:true,configurable:true });
- var __getitem__ = function(index) {
+ var __getitem__ = function(index) {
if (( index ) < 0) {
index = (this.length + index);
@@ -2184,7 +2218,7 @@ _setup_nodelist_prototype = function(args, kwargs) {
}
Object.defineProperty(NodeList.prototype, "__getitem__", { enumerable:false,value:__getitem__,writeable:true,configurable:true });
- var __setitem__ = function(index, value) {
+ var __setitem__ = function(index, value) {
if (( index ) < 0) {
index = (this.length + index);
@@ -2193,28 +2227,27 @@ _setup_nodelist_prototype = function(args, kwargs) {
}
Object.defineProperty(NodeList.prototype, "__setitem__", { enumerable:false,value:__setitem__,writeable:true,configurable:true });
- var func = function() {
+ var func = function() {
return __get__(Iterator, "__call__")([this, 0], __NULL_OBJECT__);
}
Object.defineProperty(NodeList.prototype, "__iter__", { enumerable:false,value:func,writeable:true,configurable:true });
- var index = function(obj) {
+ var index = function(obj) {
return this.indexOf(obj);
}
Object.defineProperty(NodeList.prototype, "index", { enumerable:false,value:index,writeable:true,configurable:true });
-}
-;_setup_nodelist_prototype.is_wrapper = true;
-if (__test_if_true__(( __NODEJS__ ) == false && ( __WEBWORKER__ ) == false)) {
+};_setup_nodelist_prototype.is_wrapper = true;
+if (__test_if_true__(((__NODEJS__ instanceof Array ? JSON.stringify(__NODEJS__)==JSON.stringify(false) : __NODEJS__===false) && (__WEBWORKER__ instanceof Array ? JSON.stringify(__WEBWORKER__)==JSON.stringify(false) : __WEBWORKER__===false)))) {
_setup_nodelist_prototype();
}
-bisect = function(args, kwargs) {
+var bisect = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{"low": null, "high": null},args:["a", "x", "low", "high"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2226,13 +2259,12 @@ bisect = function(args, kwargs) {
var low = __args__['low'];
var high = __args__['high'];
return a.bisect(x, low, high);
-}
-;bisect.is_wrapper = true;
-range = function(args, kwargs) {
+};bisect.is_wrapper = true;
+var range = function(args, kwargs) {
var i,arr;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["num", "stop", "step"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2258,13 +2290,12 @@ range = function(args, kwargs) {
i += step;
}
return arr;
-}
-;range.is_wrapper = true;
-xrange = function(args, kwargs) {
+};range.is_wrapper = true;
+var xrange = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["num", "stop", "step"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2275,13 +2306,12 @@ xrange = function(args, kwargs) {
var stop = __args__['stop'];
var step = __args__['step'];
return range([num, stop, step], __NULL_OBJECT__);
-}
-;xrange.is_wrapper = true;
-sum = function(args, kwargs) {
+};xrange.is_wrapper = true;
+var sum = function(args, kwargs) {
var a;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["arr"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2291,7 +2321,7 @@ sum = function(args, kwargs) {
var arr = __args__['arr'];
a = 0;
var b,__iterator__40;
- __iterator__40 = __get__(__get__(arr, "__iter__", "no iterator - line 1013: for b in arr:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__40 = __get__(__get__(arr, "__iter__", "no iterator - line 1065: for b in arr:"), "__call__")([], __NULL_OBJECT__);
var __next__40;
__next__40 = __get__(__iterator__40, "next");
while (( __iterator__40.index ) < __iterator__40.length) {
@@ -2299,18 +2329,17 @@ sum = function(args, kwargs) {
a += b;
}
return a;
-}
-;sum.is_wrapper = true;
+};sum.is_wrapper = true;
var StopIteration,__StopIteration_attrs,__StopIteration_parents;
__StopIteration_attrs = {};
__StopIteration_parents = [];
__StopIteration_properties = {};
StopIteration = __create_class__("StopIteration", __StopIteration_parents, __StopIteration_attrs, __StopIteration_properties);
-len = function(args, kwargs) {
+var len = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["ob"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2335,13 +2364,12 @@ len = function(args, kwargs) {
}
}
}
-}
-;len.is_wrapper = true;
-next = function(args, kwargs) {
+};len.is_wrapper = true;
+var next = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["obj"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2349,14 +2377,13 @@ next = function(args, kwargs) {
}
__args__ = __getargs__("next", __sig__, args, kwargs);
var obj = __args__['obj'];
- return __get__(__get__(obj, "next", "missing attribute `next` - line 1031: return obj.next()"), "__call__")();
-}
-;next.is_wrapper = true;
-map = function(args, kwargs) {
+ return __get__(__get__(obj, "next", "missing attribute `next` - line 1083: return obj.next()"), "__call__")();
+};next.is_wrapper = true;
+var map = function(args, kwargs) {
var arr,v;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["func", "objs"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2367,7 +2394,7 @@ map = function(args, kwargs) {
var objs = __args__['objs'];
arr = [];
var ob,__iterator__41;
- __iterator__41 = __get__(__get__(objs, "__iter__", "no iterator - line 1034: for ob in objs:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__41 = __get__(__get__(objs, "__iter__", "no iterator - line 1086: for ob in objs:"), "__call__")([], __NULL_OBJECT__);
var __next__41;
__next__41 = __get__(__iterator__41, "next");
while (( __iterator__41.index ) < __iterator__41.length) {
@@ -2376,13 +2403,12 @@ map = function(args, kwargs) {
arr.push(v);
}
return arr;
-}
-;map.is_wrapper = true;
-filter = function(args, kwargs) {
+};map.is_wrapper = true;
+var filter = function(args, kwargs) {
var arr;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["func", "objs"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2393,7 +2419,7 @@ filter = function(args, kwargs) {
var objs = __args__['objs'];
arr = [];
var ob,__iterator__42;
- __iterator__42 = __get__(__get__(objs, "__iter__", "no iterator - line 1041: for ob in objs:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__42 = __get__(__get__(objs, "__iter__", "no iterator - line 1093: for ob in objs:"), "__call__")([], __NULL_OBJECT__);
var __next__42;
__next__42 = __get__(__iterator__42, "next");
while (( __iterator__42.index ) < __iterator__42.length) {
@@ -2403,13 +2429,12 @@ filter = function(args, kwargs) {
}
}
return arr;
-}
-;filter.is_wrapper = true;
-min = function(args, kwargs) {
+};filter.is_wrapper = true;
+var min = function(args, kwargs) {
var a;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["lst"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2419,7 +2444,7 @@ min = function(args, kwargs) {
var lst = __args__['lst'];
a = null;
var value,__iterator__43;
- __iterator__43 = __get__(__get__(lst, "__iter__", "no iterator - line 1048: for value in lst:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__43 = __get__(__get__(lst, "__iter__", "no iterator - line 1100: for value in lst:"), "__call__")([], __NULL_OBJECT__);
var __next__43;
__next__43 = __get__(__iterator__43, "next");
while (( __iterator__43.index ) < __iterator__43.length) {
@@ -2433,13 +2458,12 @@ min = function(args, kwargs) {
}
}
return a;
-}
-;min.is_wrapper = true;
-max = function(args, kwargs) {
+};min.is_wrapper = true;
+var max = function(args, kwargs) {
var a;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["lst"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2449,7 +2473,7 @@ max = function(args, kwargs) {
var lst = __args__['lst'];
a = null;
var value,__iterator__44;
- __iterator__44 = __get__(__get__(lst, "__iter__", "no iterator - line 1054: for value in lst:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__44 = __get__(__get__(lst, "__iter__", "no iterator - line 1106: for value in lst:"), "__call__")([], __NULL_OBJECT__);
var __next__44;
__next__44 = __get__(__iterator__44, "next");
while (( __iterator__44.index ) < __iterator__44.length) {
@@ -2463,13 +2487,12 @@ max = function(args, kwargs) {
}
}
return a;
-}
-;max.is_wrapper = true;
-abs = function(args, kwargs) {
+};max.is_wrapper = true;
+var abs = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["num"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2478,13 +2501,12 @@ abs = function(args, kwargs) {
__args__ = __getargs__("abs", __sig__, args, kwargs);
var num = __args__['num'];
return Math.abs(num);
-}
-;abs.is_wrapper = true;
-ord = function(args, kwargs) {
+};abs.is_wrapper = true;
+var ord = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["char"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2493,13 +2515,12 @@ ord = function(args, kwargs) {
__args__ = __getargs__("ord", __sig__, args, kwargs);
var char = __args__['char'];
return char.charCodeAt(0);
-}
-;ord.is_wrapper = true;
-chr = function(args, kwargs) {
+};ord.is_wrapper = true;
+var chr = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["num"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2508,9 +2529,8 @@ chr = function(args, kwargs) {
__args__ = __getargs__("chr", __sig__, args, kwargs);
var num = __args__['num'];
return String.fromCharCode(num);
-}
-;chr.is_wrapper = true;
-__ArrayIterator = function(arr, index) {
+};chr.is_wrapper = true;
+var __ArrayIterator = function(arr, index) {
__ArrayIterator.__init__(this, arr, index);
this.__class__ = __ArrayIterator;
this.__uid__ = ("" + _PythonJS_UID);
@@ -2542,11 +2562,11 @@ var Iterator,__Iterator_attrs,__Iterator_parents;
__Iterator_attrs = {};
__Iterator_parents = [];
__Iterator_properties = {};
-__Iterator___init__ = function(args, kwargs) {
+var __Iterator___init__ = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "obj", "index"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2559,15 +2579,14 @@ __Iterator___init__ = function(args, kwargs) {
self.obj = obj;
self.index = index;
self.length = len([obj], __NULL_OBJECT__);
- self.obj_get = __get__(obj, "get", "missing attribute `get` - line 1082: self.obj_get = obj.get ## cache this for speed");
-}
-;__Iterator___init__.is_wrapper = true;
+ self.obj_get = __get__(obj, "get", "missing attribute `get` - line 1134: self.obj_get = obj.get ## cache this for speed");
+};__Iterator___init__.is_wrapper = true;
__Iterator_attrs.__init__ = __Iterator___init__;
-__Iterator_next = function(args, kwargs) {
+var __Iterator_next = function(args, kwargs) {
var index;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2578,15 +2597,14 @@ __Iterator_next = function(args, kwargs) {
index = self.index;
self.index += 1;
return self.obj_get([index], __jsdict([]));
-}
-;__Iterator_next.is_wrapper = true;
+};__Iterator_next.is_wrapper = true;
__Iterator_attrs.next = __Iterator_next;
Iterator = __create_class__("Iterator", __Iterator_parents, __Iterator_attrs, __Iterator_properties);
-tuple = function(args, kwargs) {
+var tuple = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["a"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2594,13 +2612,13 @@ tuple = function(args, kwargs) {
}
__args__ = __getargs__("tuple", __sig__, args, kwargs);
var a = __args__['a'];
- if (( Object.keys(arguments).length ) == 0) {
+ if ((Object.keys(arguments).length instanceof Array ? JSON.stringify(Object.keys(arguments).length)==JSON.stringify(0) : Object.keys(arguments).length===0)) {
return [];
} else {
if (__test_if_true__(a instanceof Array)) {
return a.slice();
} else {
- if (( typeof(a) ) == "string") {
+ if ((typeof(a) instanceof Array ? JSON.stringify(typeof(a))==JSON.stringify("string") : typeof(a)==="string")) {
return a.split("");
} else {
console.log(a);
@@ -2609,13 +2627,12 @@ tuple = function(args, kwargs) {
}
}
}
-}
-;tuple.is_wrapper = true;
-list = function(args, kwargs) {
+};tuple.is_wrapper = true;
+var list = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["a"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2623,13 +2640,13 @@ list = function(args, kwargs) {
}
__args__ = __getargs__("list", __sig__, args, kwargs);
var a = __args__['a'];
- if (( Object.keys(arguments).length ) == 0) {
+ if ((Object.keys(arguments).length instanceof Array ? JSON.stringify(Object.keys(arguments).length)==JSON.stringify(0) : Object.keys(arguments).length===0)) {
return [];
} else {
if (__test_if_true__(a instanceof Array)) {
return a.slice();
} else {
- if (( typeof(a) ) == "string") {
+ if ((typeof(a) instanceof Array ? JSON.stringify(typeof(a))==JSON.stringify("string") : typeof(a)==="string")) {
return a.split("");
} else {
console.log(a);
@@ -2638,17 +2655,44 @@ list = function(args, kwargs) {
}
}
}
+};list.is_wrapper = true;
+var __tuple_key__ = function(arr) {
+ var i,item,r,t;
+ r = [];
+ i = 0;
+ while (( i ) < arr.length) {
+ item = arr[i];
+ t = typeof(item);
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("string") : t==="string")) {
+ r.append((("'" + item) + "'"));
+ } else {
+ if (__test_if_true__(item instanceof Array)) {
+ r.append(__tuple_key__(item));
+ } else {
+ if ((t instanceof Array ? JSON.stringify(t)==JSON.stringify("object") : t==="object")) {
+ if (( item.__uid__ ) === undefined) {
+ throw new KeyError(item);
+ }
+ r.append(item.__uid__);
+ } else {
+ r.append(item);
+ }
+ }
+ }
+ i += 1;
+ }
+ return r.join(",");
}
-;list.is_wrapper = true;
+
var dict,__dict_attrs,__dict_parents;
__dict_attrs = {};
__dict_parents = [];
__dict_properties = {};
-__dict___init__ = function(args, kwargs) {
- var ob,value;
+var __dict___init__ = function(args, kwargs) {
+ var k,ob,value,v;
var __sig__,__args__;
__sig__ = { kwargs:{"js_object": null, "pointer": null},args:["self", "js_object", "pointer"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2666,43 +2710,52 @@ __dict___init__ = function(args, kwargs) {
ob = js_object;
if (__test_if_true__(ob instanceof Array)) {
var o,__iterator__45;
- __iterator__45 = __get__(__get__(ob, "__iter__", "no iterator - line 1125: for o in ob:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__45 = __get__(__get__(ob, "__iter__", "no iterator - line 1196: for o in ob:"), "__call__")([], __NULL_OBJECT__);
var __next__45;
__next__45 = __get__(__iterator__45, "next");
while (( __iterator__45.index ) < __iterator__45.length) {
o = __next__45();
- if (__test_if_true__(o instanceof Array)) {
- __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1127: self.__setitem__( o[0], o[1] )"), "__call__")([((o instanceof Array) ? o[0] : __get__(o, "__getitem__", "line 1127: self.__setitem__( o[0], o[1] )")([0], __NULL_OBJECT__)), ((o instanceof Array) ? o[1] : __get__(o, "__getitem__", "line 1127: self.__setitem__( o[0], o[1] )")([1], __NULL_OBJECT__))], __NULL_OBJECT__);
+ if (o instanceof Array) {
+ k = o[0];
+ v = o[1];
} else {
- __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1129: self.__setitem__( o['key'], o['value'] )"), "__call__")([((o instanceof Array) ? o["key"] : __get__(o, "__getitem__", "line 1129: self.__setitem__( o['key'], o['value'] )")(["key"], __NULL_OBJECT__)), ((o instanceof Array) ? o["value"] : __get__(o, "__getitem__", "line 1129: self.__setitem__( o['key'], o['value'] )")(["value"], __NULL_OBJECT__))], __NULL_OBJECT__);
+ k = o["key"];
+ v = o["value"];
}
+ try {
+__get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1203: self.__setitem__( k,v )"), "__call__")([k, v], __NULL_OBJECT__);
+ } catch(__exception__) {
+if (__exception__ == KeyError || __exception__ instanceof KeyError) {
+throw new KeyError("error in dict init, bad key");
+}
+
+}
}
} else {
if (__test_if_true__(isinstance([ob, dict], __NULL_OBJECT__))) {
var key,__iterator__46;
- __iterator__46 = __get__(__get__(__jsdict_keys(ob), "__iter__", "no iterator - line 1131: for key in ob.keys():"), "__call__")([], __NULL_OBJECT__);
+ __iterator__46 = __get__(__get__(__jsdict_keys(ob), "__iter__", "no iterator - line 1207: for key in ob.keys():"), "__call__")([], __NULL_OBJECT__);
var __next__46;
__next__46 = __get__(__iterator__46, "next");
while (( __iterator__46.index ) < __iterator__46.length) {
key = __next__46();
- value = ((ob instanceof Array) ? ob[key] : __get__(ob, "__getitem__", "line 1132: value = ob[ key ]")([key], __NULL_OBJECT__));
- __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1133: self.__setitem__( key, value )"), "__call__")([key, value], __NULL_OBJECT__);
+ value = ((ob instanceof Array) ? ob[key] : __get__(ob, "__getitem__", "line 1208: value = ob[ key ]")([key], __NULL_OBJECT__));
+ __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1209: self.__setitem__( key, value )"), "__call__")([key, value], __NULL_OBJECT__);
}
} else {
- console.log("ERROR init dict from:", js_object);
+ console.log(["ERROR init dict from:", js_object]);
throw new TypeError;
}
}
}
}
-}
-;__dict___init__.is_wrapper = true;
+};__dict___init__.is_wrapper = true;
__dict_attrs.__init__ = __dict___init__;
-__dict_jsify = function(args, kwargs) {
+var __dict_jsify = function(args, kwargs) {
var keys,value;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2712,31 +2765,30 @@ __dict_jsify = function(args, kwargs) {
var self = __args__['self'];
keys = __object_keys__([self["$wrapped"]], __NULL_OBJECT__);
var key,__iterator__47;
- __iterator__47 = __get__(__get__(keys, "__iter__", "no iterator - line 1140: for key in keys:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__47 = __get__(__get__(keys, "__iter__", "no iterator - line 1216: for key in keys:"), "__call__")([], __NULL_OBJECT__);
var __next__47;
__next__47 = __get__(__iterator__47, "next");
while (( __iterator__47.index ) < __iterator__47.length) {
key = __next__47();
- value = __get__(self["$wrapped"], "__getitem__", "line 1141: value = self[...][key]")([key], __NULL_OBJECT__);
- if (( typeof(value) ) == "object") {
+ value = __get__(self["$wrapped"], "__getitem__", "line 1217: value = self[...][key]")([key], __NULL_OBJECT__);
+ if ((typeof(value) instanceof Array ? JSON.stringify(typeof(value))==JSON.stringify("object") : typeof(value)==="object")) {
if (__test_if_true__(hasattr([value, "jsify"], __NULL_OBJECT__))) {
- __get__(__get__(self["$wrapped"], "__setitem__"), "__call__")([key, __get__(__get__(value, "jsify", "missing attribute `jsify` - line 1144: self[...][key] = value.jsify()"), "__call__")()], {});
+ __get__(__get__(self["$wrapped"], "__setitem__"), "__call__")([key, __get__(__get__(value, "jsify", "missing attribute `jsify` - line 1220: self[...][key] = value.jsify()"), "__call__")()], {});
}
} else {
- if (( typeof(value) ) == "function") {
+ if ((typeof(value) instanceof Array ? JSON.stringify(typeof(value))==JSON.stringify("function") : typeof(value)==="function")) {
throw new RuntimeError("can not jsify function");
}
}
}
return self["$wrapped"];
-}
-;__dict_jsify.is_wrapper = true;
+};__dict_jsify.is_wrapper = true;
__dict_attrs.jsify = __dict_jsify;
-__dict_copy = function(args, kwargs) {
+var __dict_copy = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2745,14 +2797,13 @@ __dict_copy = function(args, kwargs) {
__args__ = __getargs__("__dict_copy", __sig__, args, kwargs);
var self = __args__['self'];
return __get__(dict, "__call__")([self], __NULL_OBJECT__);
-}
-;__dict_copy.is_wrapper = true;
+};__dict_copy.is_wrapper = true;
__dict_attrs.copy = __dict_copy;
-__dict_clear = function(args, kwargs) {
+var __dict_clear = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2761,14 +2812,13 @@ __dict_clear = function(args, kwargs) {
__args__ = __getargs__("__dict_clear", __sig__, args, kwargs);
var self = __args__['self'];
self["$wrapped"] = __jsdict([]);
-}
-;__dict_clear.is_wrapper = true;
+};__dict_clear.is_wrapper = true;
__dict_attrs.clear = __dict_clear;
-__dict_has_key = function(args, kwargs) {
+var __dict_has_key = function(args, kwargs) {
var __dict;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "key"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2779,21 +2829,20 @@ __dict_has_key = function(args, kwargs) {
var key = __args__['key'];
__dict = self["$wrapped"];
if (__test_if_true__(typeof(key) === 'object' || typeof(key) === 'function')) {
- key = __get__(key, "__uid__", "missing attribute `__uid__` - line 1157: key = key.__uid__");
+ key = __get__(key, "__uid__", "missing attribute `__uid__` - line 1233: key = key.__uid__");
}
if (__test_if_true__(key in __dict)) {
return true;
} else {
return false;
}
-}
-;__dict_has_key.is_wrapper = true;
+};__dict_has_key.is_wrapper = true;
__dict_attrs.has_key = __dict_has_key;
-__dict_update = function(args, kwargs) {
+var __dict_update = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "other"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2803,21 +2852,20 @@ __dict_update = function(args, kwargs) {
var self = __args__['self'];
var other = __args__['other'];
var key,__iterator__48;
- __iterator__48 = __get__(__get__(other, "__iter__", "no iterator - line 1163: for key in other:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__48 = __get__(__get__(other, "__iter__", "no iterator - line 1239: for key in other:"), "__call__")([], __NULL_OBJECT__);
var __next__48;
__next__48 = __get__(__iterator__48, "next");
while (( __iterator__48.index ) < __iterator__48.length) {
key = __next__48();
- __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1164: self.__setitem__( key, other[key] )"), "__call__")([key, ((other instanceof Array) ? other[key] : __get__(other, "__getitem__", "line 1164: self.__setitem__( key, other[key] )")([key], __NULL_OBJECT__))], __NULL_OBJECT__);
+ __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1240: self.__setitem__( key, other[key] )"), "__call__")([key, ((other instanceof Array) ? other[key] : __get__(other, "__getitem__", "line 1240: self.__setitem__( key, other[key] )")([key], __NULL_OBJECT__))], __NULL_OBJECT__);
}
-}
-;__dict_update.is_wrapper = true;
+};__dict_update.is_wrapper = true;
__dict_attrs.update = __dict_update;
-__dict_items = function(args, kwargs) {
+var __dict_items = function(args, kwargs) {
var arr;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2827,22 +2875,21 @@ __dict_items = function(args, kwargs) {
var self = __args__['self'];
arr = [];
var key,__iterator__49;
- __iterator__49 = __get__(__get__(__jsdict_keys(self), "__iter__", "no iterator - line 1167: for key in self.keys():"), "__call__")([], __NULL_OBJECT__);
+ __iterator__49 = __get__(__get__(__jsdict_keys(self), "__iter__", "no iterator - line 1243: for key in self.keys():"), "__call__")([], __NULL_OBJECT__);
var __next__49;
__next__49 = __get__(__iterator__49, "next");
while (( __iterator__49.index ) < __iterator__49.length) {
key = __next__49();
- __get__(__get__(arr, "append", "missing attribute `append` - line 1168: arr.append( [key, self[key]] )"), "__call__")([[key, __get__(self, "__getitem__")([key], __NULL_OBJECT__)]], __NULL_OBJECT__);
+ __get__(__get__(arr, "append", "missing attribute `append` - line 1244: arr.append( [key, self[key]] )"), "__call__")([[key, __get__(self, "__getitem__")([key], __NULL_OBJECT__)]], __NULL_OBJECT__);
}
return arr;
-}
-;__dict_items.is_wrapper = true;
+};__dict_items.is_wrapper = true;
__dict_attrs.items = __dict_items;
-__dict_get = function(args, kwargs) {
+var __dict_get = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{"_default": null},args:["self", "key", "_default"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2858,14 +2905,13 @@ return __get__(self, "__getitem__")([key], __NULL_OBJECT__);
return _default;
}
-}
-;__dict_get.is_wrapper = true;
+};__dict_get.is_wrapper = true;
__dict_attrs.get = __dict_get;
-__dict_set = function(args, kwargs) {
+var __dict_set = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "key", "value"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2875,15 +2921,14 @@ __dict_set = function(args, kwargs) {
var self = __args__['self'];
var key = __args__['key'];
var value = __args__['value'];
- __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1176: self.__setitem__(key, value)"), "__call__")([key, value], __NULL_OBJECT__);
-}
-;__dict_set.is_wrapper = true;
+ __get__(__get__(self, "__setitem__", "missing attribute `__setitem__` - line 1252: self.__setitem__(key, value)"), "__call__")([key, value], __NULL_OBJECT__);
+};__dict_set.is_wrapper = true;
__dict_attrs.set = __dict_set;
-__dict___len__ = function(args, kwargs) {
+var __dict___len__ = function(args, kwargs) {
var __dict;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2893,14 +2938,13 @@ __dict___len__ = function(args, kwargs) {
var self = __args__['self'];
__dict = self["$wrapped"];
return Object.keys(__dict).length;
-}
-;__dict___len__.is_wrapper = true;
+};__dict___len__.is_wrapper = true;
__dict_attrs.__len__ = __dict___len__;
-__dict___getitem__ = function(args, kwargs) {
- var __dict;
+var __dict___getitem__ = function(args, kwargs) {
+ var __dict,msg,err;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "key"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2909,26 +2953,36 @@ __dict___getitem__ = function(args, kwargs) {
__args__ = __getargs__("__dict___getitem__", __sig__, args, kwargs);
var self = __args__['self'];
var key = __args__['key'];
- "\n notes:\n . '4' and 4 are the same key\n . it is possible that the translator mistakes a javascript-object for a dict and inlines this function,\n that is why below we return the key in self if __dict is undefined.\n ";
+ "\n note: `\"4\"` and `4` are the same key in javascript, is there a sane way to workaround this,\n that can remain compatible with external javascript?\n ";
__dict = self["$wrapped"];
- if (__test_if_true__(typeof(key) === 'object' || typeof(key) === 'function')) {
- if (__test_if_true__(key.__uid__ && key.__uid__ in __dict)) {
- return __dict[key.__uid__];
+ err = false;
+ if (__test_if_true__(key instanceof Array)) {
+ key = __tuple_key__(key);
+ } else {
+ if (__test_if_true__(typeof(key) === 'object' || typeof(key) === 'function')) {
+ if (__test_if_true__(key.__uid__ && key.__uid__ in __dict)) {
+ return __dict[key.__uid__];
+ } else {
+ err = true;
+ }
}
- throw new KeyError(key);
}
- if (__test_if_true__(__dict && key in __dict)) {
+ if (__test_if_true__((__dict && key in __dict))) {
return __dict[key];
+ } else {
+ err = true;
}
- throw new KeyError(key);
-}
-;__dict___getitem__.is_wrapper = true;
+ if (__test_if_true__(err)) {
+ msg = __sprintf("missing key: %s -\n", key);
+ throw new KeyError(__jsdict_keys(__dict));
+ }
+};__dict___getitem__.is_wrapper = true;
__dict_attrs.__getitem__ = __dict___getitem__;
-__dict___setitem__ = function(args, kwargs) {
+var __dict___setitem__ = function(args, kwargs) {
var __dict;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "key", "value"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2938,23 +2992,36 @@ __dict___setitem__ = function(args, kwargs) {
var self = __args__['self'];
var key = __args__['key'];
var value = __args__['value'];
+ if (( key ) === undefined) {
+ throw new KeyError("undefined is invalid key type");
+ }
+ if (( key ) === null) {
+ throw new KeyError("null is invalid key type");
+ }
__dict = self["$wrapped"];
- if (__test_if_true__(typeof(key) === 'object' || typeof(key) === 'function')) {
- if (__test_if_true__(key.__uid__ === undefined)) {
- key.__uid__ = '' + _PythonJS_UID++;
+ if (__test_if_true__(key instanceof Array)) {
+ key = __tuple_key__(key);
+ if (( key ) === undefined) {
+ throw new KeyError("undefined is invalid key type (tuple)");
}
- __dict[key.__uid__] = value;
- } else {
__dict[key] = value;
+ } else {
+ if (__test_if_true__(typeof(key) === 'object' || typeof(key) === 'function')) {
+ if (__test_if_true__(key.__uid__ === undefined)) {
+ key.__uid__ = '' + _PythonJS_UID++;
+ }
+ __dict[key.__uid__] = value;
+ } else {
+ __dict[key] = value;
+ }
}
-}
-;__dict___setitem__.is_wrapper = true;
+};__dict___setitem__.is_wrapper = true;
__dict_attrs.__setitem__ = __dict___setitem__;
-__dict_keys = function(args, kwargs) {
+var __dict_keys = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2963,14 +3030,13 @@ __dict_keys = function(args, kwargs) {
__args__ = __getargs__("__dict_keys", __sig__, args, kwargs);
var self = __args__['self'];
return Object.keys(self["$wrapped"]);
-}
-;__dict_keys.is_wrapper = true;
+};__dict_keys.is_wrapper = true;
__dict_attrs.keys = __dict_keys;
-__dict_pop = function(args, kwargs) {
+var __dict_pop = function(args, kwargs) {
var js_object,v;
var __sig__,__args__;
__sig__ = { kwargs:{"d": null},args:["self", "key", "d"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -2988,14 +3054,13 @@ __dict_pop = function(args, kwargs) {
delete js_object[key];
return v;
}
-}
-;__dict_pop.is_wrapper = true;
+};__dict_pop.is_wrapper = true;
__dict_attrs.pop = __dict_pop;
-__dict_values = function(args, kwargs) {
+var __dict_values = function(args, kwargs) {
var keys,out;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3012,14 +3077,13 @@ __dict_values = function(args, kwargs) {
out.push(self["$wrapped"][key]);
}
return out;
-}
-;__dict_values.is_wrapper = true;
+};__dict_values.is_wrapper = true;
__dict_attrs.values = __dict_values;
-__dict___contains__ = function(args, kwargs) {
+var __dict___contains__ = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "value"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3035,14 +3099,13 @@ return true;
return false;
}
-}
-;__dict___contains__.is_wrapper = true;
+};__dict___contains__.is_wrapper = true;
__dict_attrs.__contains__ = __dict___contains__;
-__dict___iter__ = function(args, kwargs) {
+var __dict___iter__ = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3051,15 +3114,14 @@ __dict___iter__ = function(args, kwargs) {
__args__ = __getargs__("__dict___iter__", __sig__, args, kwargs);
var self = __args__['self'];
return __get__(Iterator, "__call__")([__jsdict_keys(self), 0], __NULL_OBJECT__);
-}
-;__dict___iter__.is_wrapper = true;
+};__dict___iter__.is_wrapper = true;
__dict_attrs.__iter__ = __dict___iter__;
dict = __create_class__("dict", __dict_parents, __dict_attrs, __dict_properties);
-set = function(args, kwargs) {
+var set = function(args, kwargs) {
var keys,mask,s,hashtable,key,fallback;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["a"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3067,7 +3129,7 @@ set = function(args, kwargs) {
}
__args__ = __getargs__("set", __sig__, args, kwargs);
var a = __args__['a'];
- "\n This returns an array that is a minimal implementation of set.\n Often sets are used simply to remove duplicate entries from a list, \n and then it get converted back to a list, it is safe to use fastset for this.\n The array prototype is overloaded with basic set functions:\n difference\n intersection\n issubset\n Note: sets in Python are not subscriptable, but can be iterated over.\n Python docs say that set are unordered, some programs may rely on this disorder\n for randomness, for sets of integers we emulate the unorder only uppon initalization \n of the set, by masking the value by bits-1. Python implements sets starting with an \n array of length 8, and mask of 7, if set length grows to 6 (3/4th), then it allocates \n a new(array of length 32 and mask of 31. This is only emulated for arrays of )\n integers up to an array length of 1536.\n ";
+ "\n This returns an array that is a minimal implementation of set.\n Often sets are used simply to remove duplicate entries from a list, \n and then it get converted back to a list, it is safe to use fastset for this.\n The array prototype is overloaded with basic set functions:\n difference\n intersection\n issubset\n Note: sets in Python are not subscriptable, but can be iterated over.\n Python docs say that set are unordered, some programs may rely on this disorder\n for randomness, for sets of integers we emulate the unorder only uppon initalization \n of the set, by masking the value by bits-1. Python implements sets starting with an \n array of length 8, and mask of 7, if set length grows to 6 (3/4th), then it allocates \n a __new__>>array of length 32 and mask of 31. This is only emulated for arrays of \n integers up to an array length of 1536.\n ";
hashtable = null;
if (( a.length ) <= 1536) {
hashtable = __jsdict([]);
@@ -3096,7 +3158,7 @@ set = function(args, kwargs) {
if (! (__iter35 instanceof Array || typeof __iter35 == "string" || __is_typed_array(__iter35) || __is_some_array(__iter35) )) { __iter35 = __object_keys__(__iter35) }
for (var __idx35=0; __idx35 < __iter35.length; __idx35++) {
var b = __iter35[ __idx35 ];
- if (__test_if_true__(( typeof(b) ) == "number" && ( b ) === ( (b | 0) ))) {
+ if (__test_if_true__(((typeof(b) instanceof Array ? JSON.stringify(typeof(b))==JSON.stringify("number") : typeof(b)==="number") && ( b ) === ( (b | 0) )))) {
key = (b & mask);
hashtable[key] = b;
keys.push(key);
@@ -3114,7 +3176,7 @@ set = function(args, kwargs) {
if (! (__iter36 instanceof Array || typeof __iter36 == "string" || __is_typed_array(__iter36) || __is_some_array(__iter36) )) { __iter36 = __object_keys__(__iter36) }
for (var __idx36=0; __idx36 < __iter36.length; __idx36++) {
var item = __iter36[ __idx36 ];
- if (( s.indexOf(item) ) == -1) {
+ if ((s.indexOf(item) instanceof Array ? JSON.stringify(s.indexOf(item))==JSON.stringify(-1) : s.indexOf(item)===-1)) {
s.push(item);
}
}
@@ -3128,13 +3190,12 @@ set = function(args, kwargs) {
}
}
return s;
-}
-;set.is_wrapper = true;
-frozenset = function(args, kwargs) {
+};set.is_wrapper = true;
+var frozenset = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["a"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3143,8 +3204,7 @@ frozenset = function(args, kwargs) {
__args__ = __getargs__("frozenset", __sig__, args, kwargs);
var a = __args__['a'];
return set([a], __NULL_OBJECT__);
-}
-;frozenset.is_wrapper = true;
+};frozenset.is_wrapper = true;
var array,__array_attrs,__array_parents;
__array_attrs = {};
__array_parents = [];
@@ -3153,11 +3213,11 @@ __array_typecodes = __jsdict([["c", 1], ["b", 1], ["B", 1], ["u", 2], ["h", 2],
__array_attrs.typecodes = __array_typecodes;
__array_typecode_names = __jsdict([["c", "Int8"], ["b", "Int8"], ["B", "Uint8"], ["u", "Uint16"], ["h", "Int16"], ["H", "Uint16"], ["i", "Int32"], ["I", "Uint32"], ["f", "Float32"], ["d", "Float64"], ["float32", "Float32"], ["float16", "Int16"], ["float8", "Int8"], ["int32", "Int32"], ["uint32", "Uint32"], ["int16", "Int16"], ["uint16", "Uint16"], ["int8", "Int8"], ["uint8", "Uint8"]]);
__array_attrs.typecode_names = __array_typecode_names;
-__array___init__ = function(args, kwargs) {
+var __array___init__ = function(args, kwargs) {
var size,buff;
var __sig__,__args__;
__sig__ = { kwargs:{"initializer": null, "little_endian": false},args:["self", "typecode", "initializer", "little_endian"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3169,17 +3229,17 @@ __array___init__ = function(args, kwargs) {
var initializer = __args__['initializer'];
var little_endian = __args__['little_endian'];
self.typecode = typecode;
- self.itemsize = __get__(__get__(self, "typecodes", "missing attribute `typecodes` - line 1344: self.itemsize = self.typecodes[ typecode ]"), "__getitem__", "line 1344: self.itemsize = self.typecodes[ typecode ]")([typecode], __NULL_OBJECT__);
+ self.itemsize = __get__(__get__(self, "typecodes", "missing attribute `typecodes` - line 1436: self.itemsize = self.typecodes[ typecode ]"), "__getitem__", "line 1436: self.itemsize = self.typecodes[ typecode ]")([typecode], __NULL_OBJECT__);
self.little_endian = little_endian;
if (__test_if_true__(initializer)) {
self.length = len([initializer], __NULL_OBJECT__);
self.bytes = (self.length * self.itemsize);
- if (( self.typecode ) == "float8") {
+ if ((self.typecode instanceof Array ? JSON.stringify(self.typecode)==JSON.stringify("float8") : self.typecode==="float8")) {
self._scale = max([[abs([min([initializer], __NULL_OBJECT__)], __NULL_OBJECT__), max([initializer], __NULL_OBJECT__)]], __NULL_OBJECT__);
self._norm_get = (self._scale / 127);
self._norm_set = (1.0 / self._norm_get);
} else {
- if (( self.typecode ) == "float16") {
+ if ((self.typecode instanceof Array ? JSON.stringify(self.typecode)==JSON.stringify("float16") : self.typecode==="float16")) {
self._scale = max([[abs([min([initializer], __NULL_OBJECT__)], __NULL_OBJECT__), max([initializer], __NULL_OBJECT__)]], __NULL_OBJECT__);
self._norm_get = (self._scale / 32767);
self._norm_set = (1.0 / self._norm_get);
@@ -3193,15 +3253,14 @@ __array___init__ = function(args, kwargs) {
buff = new ArrayBuffer(size);
self.dataview = new DataView(buff);
self.buffer = buff;
- __get__(__get__(self, "fromlist", "missing attribute `fromlist` - line 1365: self.fromlist( initializer )"), "__call__")([initializer], __NULL_OBJECT__);
-}
-;__array___init__.is_wrapper = true;
+ __get__(__get__(self, "fromlist", "missing attribute `fromlist` - line 1457: self.fromlist( initializer )"), "__call__")([initializer], __NULL_OBJECT__);
+};__array___init__.is_wrapper = true;
__array_attrs.__init__ = __array___init__;
-__array___len__ = function(args, kwargs) {
+var __array___len__ = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3210,14 +3269,13 @@ __array___len__ = function(args, kwargs) {
__args__ = __getargs__("__array___len__", __sig__, args, kwargs);
var self = __args__['self'];
return self.length;
-}
-;__array___len__.is_wrapper = true;
+};__array___len__.is_wrapper = true;
__array_attrs.__len__ = __array___len__;
-__array___contains__ = function(args, kwargs) {
+var __array___contains__ = function(args, kwargs) {
var arr;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "value"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3226,20 +3284,19 @@ __array___contains__ = function(args, kwargs) {
__args__ = __getargs__("__array___contains__", __sig__, args, kwargs);
var self = __args__['self'];
var value = __args__['value'];
- arr = __get__(__get__(self, "to_array", "missing attribute `to_array` - line 1371: arr = self.to_array()"), "__call__")();
- if (( arr.indexOf(value) ) == -1) {
+ arr = __get__(__get__(self, "to_array", "missing attribute `to_array` - line 1463: arr = self.to_array()"), "__call__")();
+ if ((arr.indexOf(value) instanceof Array ? JSON.stringify(arr.indexOf(value))==JSON.stringify(-1) : arr.indexOf(value)===-1)) {
return false;
} else {
return true;
}
-}
-;__array___contains__.is_wrapper = true;
+};__array___contains__.is_wrapper = true;
__array_attrs.__contains__ = __array___contains__;
-__array___getitem__ = function(args, kwargs) {
+var __array___getitem__ = function(args, kwargs) {
var func_name,dataview,value,step,func,offset;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "index"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3251,14 +3308,14 @@ __array___getitem__ = function(args, kwargs) {
step = self.itemsize;
offset = (step * index);
dataview = self.dataview;
- func_name = ("get" + __get__(__get__(self, "typecode_names", "missing attribute `typecode_names` - line 1379: func_name = 'get'+self.typecode_names[ self.typecode ]"), "__getitem__", "line 1379: func_name = 'get'+self.typecode_names[ self.typecode ]")([self.typecode], __NULL_OBJECT__));
+ func_name = ("get" + __get__(__get__(self, "typecode_names", "missing attribute `typecode_names` - line 1471: func_name = 'get'+self.typecode_names[ self.typecode ]"), "__getitem__", "line 1471: func_name = 'get'+self.typecode_names[ self.typecode ]")([self.typecode], __NULL_OBJECT__));
func = dataview[func_name].bind(dataview);
if (( offset ) < self.bytes) {
value = func(offset);
- if (( self.typecode ) == "float8") {
+ if ((self.typecode instanceof Array ? JSON.stringify(self.typecode)==JSON.stringify("float8") : self.typecode==="float8")) {
value = (value * self._norm_get);
} else {
- if (( self.typecode ) == "float16") {
+ if ((self.typecode instanceof Array ? JSON.stringify(self.typecode)==JSON.stringify("float16") : self.typecode==="float16")) {
value = (value * self._norm_get);
}
}
@@ -3266,14 +3323,13 @@ __array___getitem__ = function(args, kwargs) {
} else {
throw new IndexError(index);
}
-}
-;__array___getitem__.is_wrapper = true;
+};__array___getitem__.is_wrapper = true;
__array_attrs.__getitem__ = __array___getitem__;
-__array___setitem__ = function(args, kwargs) {
+var __array___setitem__ = function(args, kwargs) {
var func_name,dataview,step,func,offset;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "index", "value"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3289,13 +3345,13 @@ __array___setitem__ = function(args, kwargs) {
}
offset = (step * index);
dataview = self.dataview;
- func_name = ("set" + __get__(__get__(self, "typecode_names", "missing attribute `typecode_names` - line 1395: func_name = 'set'+self.typecode_names[ self.typecode ]"), "__getitem__", "line 1395: func_name = 'set'+self.typecode_names[ self.typecode ]")([self.typecode], __NULL_OBJECT__));
+ func_name = ("set" + __get__(__get__(self, "typecode_names", "missing attribute `typecode_names` - line 1487: func_name = 'set'+self.typecode_names[ self.typecode ]"), "__getitem__", "line 1487: func_name = 'set'+self.typecode_names[ self.typecode ]")([self.typecode], __NULL_OBJECT__));
func = dataview[func_name].bind(dataview);
if (( offset ) < self.bytes) {
- if (( self.typecode ) == "float8") {
+ if ((self.typecode instanceof Array ? JSON.stringify(self.typecode)==JSON.stringify("float8") : self.typecode==="float8")) {
value = (value * self._norm_set);
} else {
- if (( self.typecode ) == "float16") {
+ if ((self.typecode instanceof Array ? JSON.stringify(self.typecode)==JSON.stringify("float16") : self.typecode==="float16")) {
value = (value * self._norm_set);
}
}
@@ -3303,14 +3359,13 @@ __array___setitem__ = function(args, kwargs) {
} else {
throw new IndexError(index);
}
-}
-;__array___setitem__.is_wrapper = true;
+};__array___setitem__.is_wrapper = true;
__array_attrs.__setitem__ = __array___setitem__;
-__array___iter__ = function(args, kwargs) {
+var __array___iter__ = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3319,14 +3374,13 @@ __array___iter__ = function(args, kwargs) {
__args__ = __getargs__("__array___iter__", __sig__, args, kwargs);
var self = __args__['self'];
return __get__(Iterator, "__call__")([self, 0], __NULL_OBJECT__);
-}
-;__array___iter__.is_wrapper = true;
+};__array___iter__.is_wrapper = true;
__array_attrs.__iter__ = __array___iter__;
-__array_get = function(args, kwargs) {
+var __array_get = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "index"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3336,14 +3390,13 @@ __array_get = function(args, kwargs) {
var self = __args__['self'];
var index = __args__['index'];
return __array___getitem__([self, index], {});
-}
-;__array_get.is_wrapper = true;
+};__array_get.is_wrapper = true;
__array_attrs.get = __array_get;
-__array_fromlist = function(args, kwargs) {
+var __array_fromlist = function(args, kwargs) {
var typecode,i,func_name,dataview,length,item,step,func,offset,size;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "lst"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3357,17 +3410,17 @@ __array_fromlist = function(args, kwargs) {
typecode = self.typecode;
size = (length * step);
dataview = self.dataview;
- func_name = ("set" + __get__(__get__(self, "typecode_names", "missing attribute `typecode_names` - line 1415: func_name = 'set'+self.typecode_names[ typecode ]"), "__getitem__", "line 1415: func_name = 'set'+self.typecode_names[ typecode ]")([typecode], __NULL_OBJECT__));
+ func_name = ("set" + __get__(__get__(self, "typecode_names", "missing attribute `typecode_names` - line 1507: func_name = 'set'+self.typecode_names[ typecode ]"), "__getitem__", "line 1507: func_name = 'set'+self.typecode_names[ typecode ]")([typecode], __NULL_OBJECT__));
func = dataview[func_name].bind(dataview);
if (( size ) <= self.bytes) {
i = 0;
offset = 0;
while (( i ) < length) {
- item = ((lst instanceof Array) ? lst[i] : __get__(lst, "__getitem__", "line 1420: item = lst[i]")([i], __NULL_OBJECT__));
- if (( typecode ) == "float8") {
+ item = ((lst instanceof Array) ? lst[i] : __get__(lst, "__getitem__", "line 1512: item = lst[i]")([i], __NULL_OBJECT__));
+ if ((typecode instanceof Array ? JSON.stringify(typecode)==JSON.stringify("float8") : typecode==="float8")) {
item *= self._norm_set;
} else {
- if (( typecode ) == "float16") {
+ if ((typecode instanceof Array ? JSON.stringify(typecode)==JSON.stringify("float16") : typecode==="float16")) {
item *= self._norm_set;
}
}
@@ -3378,14 +3431,13 @@ __array_fromlist = function(args, kwargs) {
} else {
throw new TypeError;
}
-}
-;__array_fromlist.is_wrapper = true;
+};__array_fromlist.is_wrapper = true;
__array_attrs.fromlist = __array_fromlist;
-__array_resize = function(args, kwargs) {
+var __array_resize = function(args, kwargs) {
var source,new_buff,target,new_size,buff;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "length"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3404,14 +3456,13 @@ __array_resize = function(args, kwargs) {
self.bytes = new_size;
self.buffer = new_buff;
self.dataview = new DataView(new_buff);
-}
-;__array_resize.is_wrapper = true;
+};__array_resize.is_wrapper = true;
__array_attrs.resize = __array_resize;
-__array_append = function(args, kwargs) {
+var __array_append = function(args, kwargs) {
var length;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "value"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3421,16 +3472,15 @@ __array_append = function(args, kwargs) {
var self = __args__['self'];
var value = __args__['value'];
length = self.length;
- __get__(__get__(self, "resize", "missing attribute `resize` - line 1443: self.resize( self.length + 1 )"), "__call__")([(self.length + 1)], __NULL_OBJECT__);
+ __get__(__get__(self, "resize", "missing attribute `resize` - line 1535: self.resize( self.length + 1 )"), "__call__")([(self.length + 1)], __NULL_OBJECT__);
__get__(__get__(self, "__setitem__"), "__call__")([length, value], {});
-}
-;__array_append.is_wrapper = true;
+};__array_append.is_wrapper = true;
__array_attrs.append = __array_append;
-__array_extend = function(args, kwargs) {
+var __array_extend = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "lst"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3440,21 +3490,20 @@ __array_extend = function(args, kwargs) {
var self = __args__['self'];
var lst = __args__['lst'];
var value,__iterator__54;
- __iterator__54 = __get__(__get__(lst, "__iter__", "no iterator - line 1446: for value in lst:"), "__call__")([], __NULL_OBJECT__);
+ __iterator__54 = __get__(__get__(lst, "__iter__", "no iterator - line 1538: for value in lst:"), "__call__")([], __NULL_OBJECT__);
var __next__54;
__next__54 = __get__(__iterator__54, "next");
while (( __iterator__54.index ) < __iterator__54.length) {
value = __next__54();
- __get__(__get__(self, "append", "missing attribute `append` - line 1447: self.append( value )"), "__call__")([value], __NULL_OBJECT__);
+ __get__(__get__(self, "append", "missing attribute `append` - line 1539: self.append( value )"), "__call__")([value], __NULL_OBJECT__);
}
-}
-;__array_extend.is_wrapper = true;
+};__array_extend.is_wrapper = true;
__array_attrs.extend = __array_extend;
-__array_to_array = function(args, kwargs) {
+var __array_to_array = function(args, kwargs) {
var i,item,arr;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3470,14 +3519,13 @@ __array_to_array = function(args, kwargs) {
i += 1;
}
return arr;
-}
-;__array_to_array.is_wrapper = true;
+};__array_to_array.is_wrapper = true;
__array_attrs.to_array = __array_to_array;
-__array_to_list = function(args, kwargs) {
+var __array_to_list = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3485,15 +3533,14 @@ __array_to_list = function(args, kwargs) {
}
__args__ = __getargs__("__array_to_list", __sig__, args, kwargs);
var self = __args__['self'];
- return __get__(__get__(self, "to_array", "missing attribute `to_array` - line 1457: return self.to_array()"), "__call__")();
-}
-;__array_to_list.is_wrapper = true;
+ return __get__(__get__(self, "to_array", "missing attribute `to_array` - line 1549: return self.to_array()"), "__call__")();
+};__array_to_list.is_wrapper = true;
__array_attrs.to_list = __array_to_list;
-__array_to_ascii = function(args, kwargs) {
+var __array_to_ascii = function(args, kwargs) {
var i,length,arr,string;
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3502,9 +3549,9 @@ __array_to_ascii = function(args, kwargs) {
__args__ = __getargs__("__array_to_ascii", __sig__, args, kwargs);
var self = __args__['self'];
string = "";
- arr = __get__(__get__(self, "to_array", "missing attribute `to_array` - line 1460: arr = self.to_array()"), "__call__")();
+ arr = __get__(__get__(self, "to_array", "missing attribute `to_array` - line 1552: arr = self.to_array()"), "__call__")();
i = 0;
- length = __get__(arr, "length", "missing attribute `length` - line 1461: i = 0; length = arr.length");
+ length = __get__(arr, "length", "missing attribute `length` - line 1553: i = 0; length = arr.length");
while (( i ) < length) {
var num = arr[i];
var char = String.fromCharCode(num);
@@ -3512,19 +3559,18 @@ __array_to_ascii = function(args, kwargs) {
i += 1;
}
return string;
-}
-;__array_to_ascii.is_wrapper = true;
+};__array_to_ascii.is_wrapper = true;
__array_attrs.to_ascii = __array_to_ascii;
array = __create_class__("array", __array_parents, __array_attrs, __array_properties);
var file,__file_attrs,__file_parents;
__file_attrs = {};
__file_parents = [];
__file_properties = {};
-__file___init__ = function(args, kwargs) {
+var __file___init__ = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self", "path", "flags"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3535,11 +3581,11 @@ __file___init__ = function(args, kwargs) {
var path = __args__['path'];
var flags = __args__['flags'];
self.path = path;
- if (( flags ) == "rb") {
+ if ((flags instanceof Array ? JSON.stringify(flags)==JSON.stringify("rb") : flags==="rb")) {
self.flags = "r";
self.binary = true;
} else {
- if (( flags ) == "wb") {
+ if ((flags instanceof Array ? JSON.stringify(flags)==JSON.stringify("wb") : flags==="wb")) {
self.flags = "w";
self.binary = true;
} else {
@@ -3548,14 +3594,13 @@ __file___init__ = function(args, kwargs) {
}
}
self.flags = flags;
-}
-;__file___init__.is_wrapper = true;
+};__file___init__.is_wrapper = true;
__file_attrs.__init__ = __file___init__;
-__file_read = function(args, kwargs) {
+var __file_read = function(args, kwargs) {
var _fs,path;
var __sig__,__args__;
__sig__ = { kwargs:{"binary": false},args:["self", "binary"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3566,19 +3611,18 @@ __file_read = function(args, kwargs) {
var binary = __args__['binary'];
_fs = __get__(require, "__call__")(["fs"], __NULL_OBJECT__);
path = self.path;
- if (__test_if_true__(binary || self.binary)) {
- return _fs.readFileSync(path);
+ if (__test_if_true__((binary || self.binary))) {
+ return _fs.readFileSync(path, { encoding:null });
} else {
return _fs.readFileSync(path, __jsdict([["encoding", "utf8"]]));
}
-}
-;__file_read.is_wrapper = true;
+};__file_read.is_wrapper = true;
__file_attrs.read = __file_read;
-__file_write = function(args, kwargs) {
- var _fs,path;
+var __file_write = function(args, kwargs) {
+ var path,buff,_fs;
var __sig__,__args__;
__sig__ = { kwargs:{"binary": false},args:["self", "data", "binary"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3590,19 +3634,24 @@ __file_write = function(args, kwargs) {
var binary = __args__['binary'];
_fs = __get__(require, "__call__")(["fs"], __NULL_OBJECT__);
path = self.path;
- if (__test_if_true__(binary || self.binary)) {
- _fs.writeFileSync(path, data);
+ if (__test_if_true__((binary || self.binary))) {
+ binary = (binary || self.binary);
+ if ((binary instanceof Array ? JSON.stringify(binary)==JSON.stringify("base64") : binary==="base64")) {
+ buff = new Buffer(data, "base64");
+ _fs.writeFileSync(path, buff, __jsdict([["encoding", null]]));
+ } else {
+ _fs.writeFileSync(path, data, __jsdict([["encoding", null]]));
+ }
} else {
_fs.writeFileSync(path, data, __jsdict([["encoding", "utf8"]]));
}
-}
-;__file_write.is_wrapper = true;
+};__file_write.is_wrapper = true;
__file_attrs.write = __file_write;
-__file_close = function(args, kwargs) {
+var __file_close = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{},args:["self"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3611,15 +3660,14 @@ __file_close = function(args, kwargs) {
__args__ = __getargs__("__file_close", __sig__, args, kwargs);
var self = __args__['self'];
/*pass*/
-}
-;__file_close.is_wrapper = true;
+};__file_close.is_wrapper = true;
__file_attrs.close = __file_close;
file = __create_class__("file", __file_parents, __file_attrs, __file_properties);
-__open__ = function(args, kwargs) {
+var __open__ = function(args, kwargs) {
var __sig__,__args__;
__sig__ = { kwargs:{"mode": null},args:["path", "mode"] };
- if (args instanceof Array && ( Object.prototype.toString.call(kwargs) ) == "[object Object]" && ( arguments.length ) == 2) {
+ if ((args instanceof Array && (Object.prototype.toString.call(kwargs) instanceof Array ? JSON.stringify(Object.prototype.toString.call(kwargs))==JSON.stringify("[object Object]") : Object.prototype.toString.call(kwargs)==="[object Object]") && (arguments.length instanceof Array ? JSON.stringify(arguments.length)==JSON.stringify(2) : arguments.length===2))) {
/*pass*/
} else {
args = Array.prototype.slice.call(arguments, 0, __sig__.args.length);
@@ -3629,10 +3677,9 @@ __open__ = function(args, kwargs) {
var path = __args__['path'];
var mode = __args__['mode'];
return __get__(file, "__call__")([path, mode], __NULL_OBJECT__);
-}
-;__open__.is_wrapper = true;
+};__open__.is_wrapper = true;
json = __jsdict([["loads", (function (s) {return JSON.parse(s);})], ["dumps", (function (o) {return JSON.stringify(o);})]]);
-__get_other_workers_with_shared_arg = function(worker, ob) {
+var __get_other_workers_with_shared_arg = function(worker, ob) {
var a,other,args;
a = [];
var __iter38 = threading.workers;
@@ -3658,23 +3705,23 @@ __get_other_workers_with_shared_arg = function(worker, ob) {
}
threading = __jsdict([["workers", []], ["_blocking_callback", null]]);
-__start_new_thread = function(f, args) {
+var __start_new_thread = function(f, args) {
var jsargs,worker;
worker = new Worker(f);
worker.__uid__ = len(threading.workers);
threading.workers.append(__jsdict([["worker", worker], ["args", args]]));
- var func = function(event) {
+ var func = function(event) {
var a,res,value;
- if (( event.data.type ) == "terminate") {
+ if ((event.data.type instanceof Array ? JSON.stringify(event.data.type)==JSON.stringify("terminate") : event.data.type==="terminate")) {
worker.terminate();
} else {
- if (( event.data.type ) == "call") {
+ if ((event.data.type instanceof Array ? JSON.stringify(event.data.type)==JSON.stringify("call") : event.data.type==="call")) {
res = __module__[event.data.function].apply(null, event.data.args);
- if (__test_if_true__(( res ) !== null && ( res ) !== undefined)) {
+ if (__test_if_true__((( res ) !== null && ( res ) !== undefined))) {
worker.postMessage(__jsdict([["type", "return_to_blocking_callback"], ["result", res]]));
}
} else {
- if (( event.data.type ) == "append") {
+ if ((event.data.type instanceof Array ? JSON.stringify(event.data.type)==JSON.stringify("append") : event.data.type==="append")) {
a = args[event.data.argindex];
a.push(event.data.value);
var __iter40 = __get_other_workers_with_shared_arg(worker, a);
@@ -3684,7 +3731,7 @@ __start_new_thread = function(f, args) {
other.postMessage(__jsdict([["type", "append"], ["argindex", event.data.argindex], ["value", event.data.value]]));
}
} else {
- if (( event.data.type ) == "__setitem__") {
+ if ((event.data.type instanceof Array ? JSON.stringify(event.data.type)==JSON.stringify("__setitem__") : event.data.type==="__setitem__")) {
a = args[event.data.argindex];
value = event.data.value;
if (__test_if_true__(a.__setitem__)) {
@@ -3728,9 +3775,9 @@ __start_new_thread = function(f, args) {
return worker;
}
-__gen_worker_append = function(worker, ob, index) {
+var __gen_worker_append = function(worker, ob, index) {
- var append = function(item) {
+ var append = function(item) {
worker.postMessage(__jsdict([["type", "append"], ["argindex", index], ["value", item]]));
ob.push(item);
@@ -3739,17 +3786,17 @@ __gen_worker_append = function(worker, ob, index) {
Object.defineProperty(ob, "append", __jsdict([["enumerable", false], ["value", append], ["writeable", true], ["configurable", true]]));
}
-__webworker_wrap = function(ob, argindex) {
+var __webworker_wrap = function(ob, argindex) {
if (__test_if_true__(ob instanceof Array)) {
- var func = function(index, item) {
+ var func = function(index, item) {
postMessage(__jsdict([["type", "__setitem__"], ["index", index], ["value", item], ["argindex", argindex]]));
Array.prototype.__setitem__.call(ob, index, item);
}
Object.defineProperty(ob, "__setitem__", __jsdict([["enumerable", false], ["value", func], ["writeable", true], ["configurable", true]]));
- var func = function(item) {
+ var func = function(item) {
postMessage(__jsdict([["type", "append"], ["value", item], ["argindex", argindex]]));
Array.prototype.push.call(ob, item);
@@ -3757,8 +3804,8 @@ __webworker_wrap = function(ob, argindex) {
Object.defineProperty(ob, "append", __jsdict([["enumerable", false], ["value", func], ["writeable", true], ["configurable", true]]));
} else {
- if (( typeof(ob) ) == "object") {
- var func = function(key, item) {
+ if ((typeof(ob) instanceof Array ? JSON.stringify(typeof(ob))==JSON.stringify("object") : typeof(ob)==="object")) {
+ var func = function(key, item) {
postMessage(__jsdict([["type", "__setitem__"], ["index", key], ["value", item], ["argindex", argindex]]));
ob[key] = item;
@@ -3770,7 +3817,7 @@ __webworker_wrap = function(ob, argindex) {
return ob;
}
-__rpc__ = function(url, func, args) {
+var __rpc__ = function(url, func, args) {
var req;
req = new XMLHttpRequest();
req.open("POST", url, false);
@@ -3779,7 +3826,7 @@ __rpc__ = function(url, func, args) {
return JSON.parse(req.responseText);
}
-__rpc_iter__ = function(url, attr) {
+var __rpc_iter__ = function(url, attr) {
var req;
req = new XMLHttpRequest();
req.open("POST", url, false);
@@ -3788,7 +3835,7 @@ __rpc_iter__ = function(url, attr) {
return JSON.parse(req.responseText);
}
-__rpc_set__ = function(url, attr, value) {
+var __rpc_set__ = function(url, attr, value) {
var req;
req = new XMLHttpRequest();
req.open("POST", url, false);
@@ -3796,7 +3843,7 @@ __rpc_set__ = function(url, attr, value) {
req.send(JSON.stringify(__jsdict([["set", attr], ["value", value]])));
}
-__rpc_get__ = function(url, attr) {
+var __rpc_get__ = function(url, attr) {
var req;
req = new XMLHttpRequest();
req.open("POST", url, false);
diff --git a/pythonjs/pythonjs.py b/pythonjs/pythonjs.py
index aa72bb6..159f25c 100755
--- a/pythonjs/pythonjs.py
+++ b/pythonjs/pythonjs.py
@@ -19,8 +19,13 @@
#import code_writer
import typedpython
+class SwapLambda( RuntimeError ):
+ def __init__(self, node):
+ self.node = node
+ RuntimeError.__init__(self)
+
class JSGenerator(NodeVisitor): #, inline_function.Inliner):
- def __init__(self, requirejs=True, insert_runtime=True, webworker=False, function_expressions=False):
+ def __init__(self, requirejs=True, insert_runtime=True, webworker=False, function_expressions=True):
#writer = code_writer.Writer()
#self.setup_inliner( writer )
self._func_expressions = function_expressions
@@ -31,8 +36,9 @@ def __init__(self, requirejs=True, insert_runtime=True, webworker=False, functio
self._insert_runtime = insert_runtime
self._webworker = webworker
self._exports = set()
+ self._inline_lambda = False
- self.special_decorators = set(['__typedef__', '__glsl__', '__pyfunction__'])
+ self.special_decorators = set(['__typedef__', '__glsl__', '__pyfunction__', 'expression'])
self._glsl = False
self._has_glsl = False
self._typed_vars = dict()
@@ -47,6 +53,10 @@ def push(self): self._indent += 1
def pull(self):
if self._indent > 0: self._indent -= 1
+ def visit_ClassDef(self, node):
+ raise NotImplementedError(node)
+
+
def visit_Global(self, node):
return '/*globals: %s */' %','.join(node.names)
@@ -81,6 +91,42 @@ def visit_AugAssign(self, node):
a = '%s %s= %s;' %(target, op, value)
return a
+ def visit_With(self, node):
+ r = []
+ is_switch = False
+ if isinstance( node.context_expr, Name ) and node.context_expr.id == '__default__':
+ r.append('default:')
+ elif isinstance( node.context_expr, Name ) and node.context_expr.id == '__select__':
+ r.append('select {')
+ is_switch = True
+ elif isinstance( node.context_expr, ast.Call ):
+ if not isinstance(node.context_expr.func, ast.Name):
+ raise SyntaxError( self.visit(node.context_expr))
+
+ if len(node.context_expr.args):
+ a = self.visit(node.context_expr.args[0])
+ else:
+ assert len(node.context_expr.keywords)
+ a = '%s = %s' %(node.context_expr.keywords[0].arg, self.visit(node.context_expr.keywords[0].value))
+
+ if node.context_expr.func.id == '__case__':
+ r.append('case %s:' %a)
+ elif node.context_expr.func.id == '__switch__':
+ r.append('switch (%s) {' %self.visit(node.context_expr.args[0]))
+ is_switch = True
+ else:
+ raise SyntaxError( 'invalid use of with')
+
+
+ for b in node.body:
+ a = self.visit(b)
+ if a: r.append(a)
+
+ if is_switch:
+ r.append('}')
+
+ return '\n'.join(r)
+
def visit_Module(self, node):
header = []
lines = []
@@ -124,7 +170,8 @@ def visit_Expr(self, node):
s = self.visit(node.value)
if s.strip() and not s.endswith(';'):
s += ';'
- return s
+ if s==';': return ''
+ else: return s
def visit_In(self, node):
@@ -134,7 +181,13 @@ def visit_Tuple(self, node):
return '[%s]' % ', '.join(map(self.visit, node.elts))
def visit_List(self, node):
- return '[%s]' % ', '.join(map(self.visit, node.elts))
+ a = []
+ for elt in node.elts:
+ b = self.visit(elt)
+ if b is None: raise SyntaxError(elt)
+ a.append( b )
+ return '[%s]' % ', '.join(a)
+
def visit_TryExcept(self, node):
out = []
@@ -178,7 +231,12 @@ def visit_ExceptHandler(self, node):
def visit_Lambda(self, node):
args = [self.visit(a) for a in node.args.args]
- return '(function (%s) {return %s;})' %(','.join(args), self.visit(node.body))
+ if args and args[0]=='__INLINE_FUNCTION__':
+ self._inline_lambda = True
+ #return '' ## skip node, the next function contains the real def
+ raise SwapLambda( node )
+ else:
+ return '(function (%s) {return %s;})' %(','.join(args), self.visit(node.body))
@@ -217,6 +275,7 @@ def _visit_call_helper_var_glsl(self, node):
def _visit_function(self, node):
is_main = node.name == 'main'
+ is_annon = node.name == ''
is_pyfunc = False
return_type = None
glsl = False
@@ -225,8 +284,15 @@ def _visit_function(self, node):
gpu_vectorize = False
gpu_method = False
args_typedefs = {}
+ func_expr = False
+
for decor in node.decorator_list:
- if isinstance(decor, ast.Name) and decor.id == '__pyfunction__':
+ if isinstance(decor, ast.Call) and isinstance(decor.func, ast.Name) and decor.func.id == 'expression':
+ assert len(decor.args)==1
+ func_expr = True
+ node.name = self.visit(decor.args[0])
+
+ elif isinstance(decor, ast.Name) and decor.id == '__pyfunction__':
is_pyfunc = True
elif isinstance(decor, ast.Name) and decor.id == '__glsl__':
glsl = True
@@ -314,9 +380,14 @@ def _visit_function(self, node):
raise RuntimeError(chunks)
sub = []
for ci,chk in enumerate(chunks):
+ #if not chk.startswith('@'): ## special inline javascript.
+ # chk = '```'+chk+'```'
+ #chk = chk.replace('$', '```')
+
if not ci%2:
if '@' in chk:
raise SyntaxError(chunks)
+
if ci==0:
if chk:
sub.append('"%s"'%chk)
@@ -339,6 +410,7 @@ def _visit_function(self, node):
lines.append( 'glsljit.push(%s);' %''.join(sub))
else:
+ sub = sub.replace('$', '```')
lines.append( 'glsljit.push("%s");' %(self.indent()+sub) )
@@ -376,7 +448,11 @@ def _visit_function(self, node):
lines.append(' var __webclgl = new WebCLGL()')
lines.append(' var header = glsljit.compile_header()')
lines.append(' var shader = glsljit.compile_main()')
- #lines.append(' console.log(shader)')
+
+ #lines.append(' console.log(header)')
+ lines.append(' console.log("-----------")')
+ lines.append(' console.log(shader)')
+
## create the webCLGL kernel, compiles GLSL source
lines.append(' var __kernel = __webclgl.createKernel( shader, header );')
@@ -454,10 +530,13 @@ def _visit_function(self, node):
elif len(self._function_stack) == 1:
## this style will not make function global to the eval context in NodeJS ##
#buffer = self.indent() + 'function %s(%s) {\n' % (node.name, ', '.join(args))
- ## this is required for eval to be able to work in NodeJS, note there is no var keyword.
- if self._func_expressions:
- buffer = self.indent() + '%s = function(%s) {\n' % (node.name, ', '.join(args))
+ ## note if there is no var keyword and this function is at the global level,
+ ## then it should be callable from eval in NodeJS - this is not correct.
+ ## infact, var should always be used with function expressions.
+
+ if self._func_expressions or func_expr:
+ buffer = self.indent() + 'var %s = function(%s) {\n' % (node.name, ', '.join(args))
else:
buffer = self.indent() + 'function %s(%s) {\n' % (node.name, ', '.join(args))
@@ -466,22 +545,32 @@ def _visit_function(self, node):
else:
- if self._func_expressions:
+ if self._func_expressions or func_expr:
buffer = self.indent() + 'var %s = function(%s) {\n' % (node.name, ', '.join(args))
else:
buffer = self.indent() + 'function %s(%s) {\n' % (node.name, ', '.join(args))
self.push()
body = list()
- for child in node.body:
- if isinstance(child, Str):
+ next = None
+ for i,child in enumerate(node.body):
+ if isinstance(child, Str) or hasattr(child, 'SKIP'):
continue
- #if isinstance(child, GeneratorType): ## not tested
- # for sub in child:
- # body.append( self.indent()+self.visit(sub))
- #else:
- v = self.visit(child)
+ #try:
+ # v = self.visit(child)
+ #except SwapLambda as error:
+ # error.node.__class__ = ast.FunctionDef
+ # next = node.body[i+1]
+ # if not isinstance(next, ast.FunctionDef):
+ # raise SyntaxError('inline def is only allowed in javascript mode')
+ # error.node.__dict__ = next.__dict__
+ # error.node.name = ''
+ # v = self.visit(child)
+
+ v = self.try_and_catch_swap_lambda(child, node.body)
+
+
if v is None:
msg = 'error in function: %s'%node.name
msg += '\n%s' %child
@@ -491,10 +580,41 @@ def _visit_function(self, node):
buffer += '\n'.join(body)
self.pull()
- buffer += '\n%s}\n' %self.indent()
- if is_pyfunc:
- buffer += ';%s.is_wrapper = true;' %node.name ## TODO change to .__pyfunc__
- return buffer
+ buffer += '\n%s}' %self.indent()
+ #if self._inline_lambda:
+ # self._inline_lambda = False
+ if is_annon:
+ buffer = '__wrap_function__(' + buffer + ')'
+ elif is_pyfunc:
+ ## TODO change .is_wrapper to .__pyfunc__
+ buffer += ';%s.is_wrapper = true;' %node.name
+ else:
+ buffer += '\n'
+
+ return self.indent() + buffer
+
+ def try_and_catch_swap_lambda(self, child, body):
+ try:
+ return self.visit(child)
+ except SwapLambda as e:
+
+ next = None
+ for i in range( body.index(child), len(body) ):
+ n = body[ i ]
+ if isinstance(n, ast.FunctionDef):
+ if hasattr(n, 'SKIP'):
+ continue
+ else:
+ next = n
+ break
+ assert next
+ next.SKIP = True
+ e.node.__class__ = ast.FunctionDef
+ e.node.__dict__ = next.__dict__
+ e.node.name = ''
+ return self.try_and_catch_swap_lambda( child, body )
+
+
def _visit_subscript_ellipsis(self, node):
name = self.visit(node.value)
@@ -515,10 +635,7 @@ def visit_Index(self, node):
return self.visit(node.value)
def visit_Slice(self, node):
- #print(node.lower)
- #print(node.upper)
- #print(node.step)
- raise SyntaxError(node) ## slicing not allowed here at js level
+ raise SyntaxError('list slice') ## slicing not allowed here at js level
def visit_arguments(self, node):
out = []
@@ -571,10 +688,16 @@ def _visit_call_helper_new(self, node):
else:
raise SyntaxError( args )
+ def _visit_call_helper_go( self, node ):
+ raise NotImplementedError('go call')
+
+
def visit_Call(self, node):
name = self.visit(node.func)
+ if name in typedpython.GO_SPECIAL_CALLS.values():
+ return self._visit_call_helper_go( node )
- if self._glsl and isinstance(node.func, ast.Attribute):
+ elif self._glsl and isinstance(node.func, ast.Attribute):
if isinstance(node.func.value, ast.Name) and node.func.value.id in self._typed_vars:
args = ','.join( [self.visit(a) for a in node.args] )
return '`__struct_name__`_%s(%s, %s)' %(node.func.attr, node.func.value.id, args)
@@ -706,6 +829,9 @@ def visit_Call(self, node):
# return_id = self.inline_function( node )
# code = self.writer.getvalue()
# return '\n'.join([code, return_id])
+ elif name.split('.')[-1] == '__go__receive__':
+ raise SyntaxError('__go__receive__')
+
else:
return self._visit_call_helper(node)
@@ -790,9 +916,12 @@ def _visit_call_helper_var(self, node):
return ';'.join(out)
def _inline_code_helper(self, s):
+ ## TODO, should newline be changed here?
s = s.replace('\n', '\\n').replace('\0', '\\0') ## AttributeError: 'BinOp' object has no attribute 's' - this is caused by bad quotes
if s.strip().startswith('#'): s = '/*%s*/'%s
- if '"' in s or "'" in s: ## can not trust direct-replace hacks
+ if '__new__>>' in s: ## fixes inline `JS("new XXX")`
+ s = s.replace('__new__>>', ' new ')
+ elif '"' in s or "'" in s: ## can not trust direct-replace hacks
pass
else:
if ' or ' in s:
@@ -823,6 +952,31 @@ def visit_BinOp(self, node):
op = self.visit(node.op)
right = self.visit(node.right)
+ if op == '>>' and left == '__new__':
+ return ' new %s' %right
+
+ elif op == '<<':
+ if left in ('__go__receive__', '__go__send__'):
+ return '<- %s' %right
+ elif isinstance(node.left, ast.Call) and isinstance(node.left.func, ast.Name) and node.left.func.id in ('__go__array__', '__go__arrayfixed__', '__go__map__'):
+ if node.left.func.id == '__go__map__':
+ key_type = self.visit(node.left.args[0])
+ value_type = self.visit(node.left.args[1])
+ if value_type == 'interface': value_type = 'interface{}'
+ return 'map[%s]%s%s' %(key_type, value_type, right)
+ else:
+ if not right.startswith('{') and not right.endswith('}'):
+ right = '{%s}' %right[1:-1]
+
+ if node.left.func.id == '__go__array__':
+ return '[]%s%s' %(self.visit(node.left.args[0]), right)
+ elif node.left.func.id == '__go__arrayfixed__':
+ asize = self.visit(node.left.args[0])
+ atype = self.visit(node.left.args[1])
+ return '[%s]%s%s' %(asize, atype, right)
+ elif isinstance(node.left, ast.Name) and node.left.id=='__go__array__' and op == '<<':
+ return '[]%s' %self.visit(node.right)
+
if left in self._typed_vars and self._typed_vars[left] == 'numpy.float32':
left += '[_id_]'
if right in self._typed_vars and self._typed_vars[right] == 'numpy.float32':
@@ -893,20 +1047,32 @@ def visit_Is(self, node):
def visit_Compare(self, node):
if self._glsl:
comp = [self.visit(node.left)]
+ elif isinstance(node.ops[0], ast.Eq):
+ left = self.visit(node.left)
+ right = self.visit(node.comparators[0])
+ return '(%s instanceof Array ? JSON.stringify(%s)==JSON.stringify(%s) : %s===%s)' %(left, left, right, left, right)
+ elif isinstance(node.ops[0], ast.NotEq):
+ left = self.visit(node.left)
+ right = self.visit(node.comparators[0])
+ return '(!(%s instanceof Array ? JSON.stringify(%s)==JSON.stringify(%s) : %s===%s))' %(left, left, right, left, right)
+
else:
comp = [ '(']
comp.append( self.visit(node.left) )
comp.append( ')' )
- for i in range( len(node.ops) ):
- comp.append( self.visit(node.ops[i]) )
+ for i in range( len(node.ops) ):
+ comp.append( self.visit(node.ops[i]) )
- if isinstance(node.comparators[i], ast.BinOp):
- comp.append('(')
- comp.append( self.visit(node.comparators[i]) )
- comp.append(')')
- else:
- comp.append( self.visit(node.comparators[i]) )
+ if isinstance(node.ops[i], ast.Eq):
+ raise SyntaxError('TODO')
+
+ elif isinstance(node.comparators[i], ast.BinOp):
+ comp.append('(')
+ comp.append( self.visit(node.comparators[i]) )
+ comp.append(')')
+ else:
+ comp.append( self.visit(node.comparators[i]) )
return ' '.join( comp )
@@ -931,7 +1097,7 @@ def visit_Or(self, node):
def visit_BoolOp(self, node):
op = self.visit(node.op)
- return op.join( [self.visit(v) for v in node.values] )
+ return '('+ op.join( [self.visit(v) for v in node.values] ) +')'
def visit_If(self, node):
out = []
@@ -1008,6 +1174,8 @@ def visit_For(self, node):
'`@var %s = %s[0];`' %(target, iter) ## capture first item with target name so that for loops can get the length of member arrays
]
+ ##TODO## lines.append('$') ## optimizes webclgl parser
+
lines.append('for (int _iter=0; _iter < `__length__`; _iter++) {' )
## declare struct variable ##
@@ -1018,6 +1186,8 @@ def visit_For(self, node):
lines.append( '`@glsljit.push("if (_iter==" +__j+ ") { %s=%s_" +__j+ ";}");`' %(target, iter))
lines.append( '`@}`')
+ ##TODO## lines.append('$') ## optimizes webclgl parser
+
elif isinstance(node.iter, ast.Call): ## `for i in range(n):`
iter = self.visit(node.iter.args[0])
@@ -1099,10 +1269,79 @@ def generate_runtime():
]
return '\n'.join( lines )
-def main(script, requirejs=True, insert_runtime=True, webworker=False, function_expressions=False):
- #print(script)
- tree = ast.parse( script )
- return JSGenerator( requirejs=requirejs, insert_runtime=insert_runtime, webworker=webworker, function_expressions=function_expressions ).visit(tree)
+def main(source, requirejs=True, insert_runtime=True, webworker=False, function_expressions=True):
+ head = []
+ tail = []
+ script = False
+ osource = source
+ if source.strip().startswith('')
+ script = list()
+ elif line.strip() == '':
+ if type(script) is list:
+ source = '\n'.join(script)
+ script = True
+ tail.append( '')
+ elif script is True:
+ tail.append( '')
+ else:
+ head.append( '')
+
+ elif isinstance( script, list ):
+ script.append( line )
+
+ elif script is True:
+ tail.append( line )
+
+ else:
+ head.append( line )
+
+
+ try:
+ tree = ast.parse( source )
+ #raise SyntaxError(source)
+ except SyntaxError:
+ import traceback
+ err = traceback.format_exc()
+ sys.stderr.write( err )
+ sys.stderr.write( '\n--------------error in second stage translation--------------\n' )
+
+ lineno = 0
+ for line in err.splitlines():
+ if "" in line:
+ lineno = int(line.split()[-1])
+
+
+ lines = source.splitlines()
+ if lineno > 10:
+ for i in range(lineno-5, lineno+5):
+ sys.stderr.write( 'line %s->'%i )
+ sys.stderr.write( lines[i] )
+ if i==lineno-1:
+ sys.stderr.write(' <>')
+ sys.stderr.write( '\n' )
+
+ else:
+ sys.stderr.write( lines[lineno] )
+ sys.stderr.write( '\n' )
+
+ if '--debug' in sys.argv:
+ sys.stderr.write( osource )
+ sys.stderr.write( '\n' )
+
+ sys.exit(1)
+
+ gen = JSGenerator( requirejs=requirejs, insert_runtime=insert_runtime, webworker=webworker, function_expressions=function_expressions )
+ output = gen.visit(tree)
+ if head:
+ head.append( output )
+ head.extend( tail )
+ output = '\n'.join( head )
+
+ return output
def command():
diff --git a/pythonjs/pythonjs_to_go.py b/pythonjs/pythonjs_to_go.py
new file mode 100644
index 0000000..c0ff87c
--- /dev/null
+++ b/pythonjs/pythonjs_to_go.py
@@ -0,0 +1,570 @@
+#!/usr/bin/env python
+# PythonJS to Go Translator
+# by Brett Hartshorn - copyright 2014
+# License: "New BSD"
+import os, sys
+import ast
+import pythonjs
+
+
+
+class GoGenerator( pythonjs.JSGenerator ):
+
+ def __init__(self, requirejs=False, insert_runtime=False):
+ pythonjs.JSGenerator.__init__(self, requirejs=False, insert_runtime=False)
+
+ self._class_stack = list()
+ self._classes = dict()
+ self._class_props = dict()
+
+ self._vars = set()
+ self._known_vars = set()
+ self._kwargs_type_ = dict()
+
+ self._imports = []
+
+ def visit_ClassDef(self, node):
+ self._class_stack.append( node )
+ node._parents = set()
+ node._struct_def = dict()
+ out = []
+ sdef = dict()
+ props = set()
+ bases = set()
+ base_classes = set()
+
+ self._classes[ node.name ] = node
+ self._class_props[ node.name ] = props
+
+
+ for base in node.bases:
+ n = self.visit(base)
+ if n == 'object':
+ continue
+ node._parents.add( n )
+
+ bases.add( n )
+ if n in self._class_props:
+ props.update( self._class_props[n] )
+ base_classes.add( self._classes[n] )
+ #else: ## special case - subclassing a builtin like `list`
+ # continue
+
+ for p in self._classes[ n ]._parents:
+ bases.add( p )
+ props.update( self._class_props[p] )
+ base_classes.add( self._classes[p] )
+
+
+ for decor in node.decorator_list: ## class decorators
+ if isinstance(decor, ast.Call):
+ assert decor.func.id=='__struct__'
+ #props.update( [self.visit(a) for a in decor.args] )
+ for kw in decor.keywords:
+ props.add( kw.arg )
+ sdef[ kw.arg ] = kw.value.id
+
+ node._struct_def.update( sdef )
+ out.append( 'type %s struct {' %node.name)
+ if base_classes:
+ for bnode in base_classes:
+ ## Go only needs the name of the parent struct and all its items are inserted automatically ##
+ out.append('%s' %bnode.name)
+
+ for name in sdef:
+ out.append('%s %s' %(name, sdef[name]))
+ out.append('}')
+
+
+ init = None
+ method_names = set()
+ for b in node.body:
+ assert isinstance(b, ast.FunctionDef)
+ method_names.add( b.name )
+ out.append( self.visit(b) )
+ if b.name == '__init__':
+ init = b
+
+
+ parent_init = None
+ if base_classes:
+ for bnode in base_classes:
+ for b in bnode.body:
+ if isinstance(b, ast.FunctionDef):
+ if b.name in method_names:
+ continue
+ if b.name == '__init__':
+ parent_init = {'class':bnode, 'init':b}
+ #continue
+ out.append( self.visit(b) )
+
+ if init or parent_init:
+ if parent_init:
+ classname = parent_init['class'].name
+ init = parent_init['init']
+ else:
+ classname = node.name
+
+ out.append( 'func __new__%s( %s ) *%s {' %(node.name, init._args_signature, node.name))
+ out.append( ' ob := %s{}' %node.name )
+ out.append( ' ob.__init__(%s)' %','.join(init._arg_names))
+ out.append( ' return &ob')
+ out.append('}')
+
+ else:
+ out.append( 'func __new__%s() *%s { return &%s{} }' %(node.name, node.name, node.name))
+
+
+ self._class_stack.pop()
+ return '\n'.join(out)
+
+
+ def visit_Slice(self, node):
+ lower = upper = step = None
+ if node.lower:
+ lower = self.visit(node.lower)
+ if node.upper:
+ upper = self.visit(node.upper)
+ if node.step:
+ step = self.visit(node.step)
+
+ if lower and upper:
+ return '%s:%s' %(lower,upper)
+ elif upper:
+ return ':%s' %upper
+ elif lower:
+ return '%s:'%lower
+ else:
+ raise SyntaxError('TODO slice')
+
+
+ def visit_Print(self, node):
+ r = []
+ for e in node.values:
+ s = self.visit(e)
+ if isinstance(e, ast.List):
+ r.append('fmt.Println(%s);' %s[1:-1])
+ else:
+ r.append('fmt.Println(%s);' %s)
+ return ''.join(r)
+
+ def visit_Expr(self, node):
+ return self.visit(node.value)
+
+ def visit_Import(self, node):
+ r = [alias.name.replace('__SLASH__', '/') for alias in node.names]
+ if r:
+ for name in r:
+ self._imports.append('import("%s");' %name)
+ return ''
+
+ def visit_Module(self, node):
+ header = [
+ 'package main',
+ 'import "fmt"'
+ ]
+ lines = []
+
+ for b in node.body:
+ line = self.visit(b)
+
+ if line:
+ for sub in line.splitlines():
+ if sub==';':
+ raise SyntaxError(line)
+ else:
+ lines.append( sub )
+ else:
+ if isinstance(b, ast.Import):
+ pass
+ else:
+ raise SyntaxError(b)
+
+ lines.append('type _kwargs_type_ struct {')
+ for name in self._kwargs_type_:
+ type = self._kwargs_type_[name]
+ lines.append( ' %s %s' %(name,type))
+ lines.append( ' __use__%s bool' %name)
+ lines.append('}')
+
+ lines = header + self._imports + lines
+ return '\n'.join( lines )
+
+
+ def visit_Compare(self, node):
+ comp = [ '(']
+ comp.append( self.visit(node.left) )
+ comp.append( ')' )
+
+ for i in range( len(node.ops) ):
+ comp.append( self.visit(node.ops[i]) )
+
+ if isinstance(node.comparators[i], ast.BinOp):
+ comp.append('(')
+ comp.append( self.visit(node.comparators[i]) )
+ comp.append(')')
+ else:
+ comp.append( self.visit(node.comparators[i]) )
+
+ return ' '.join( comp )
+
+ def visit_For(self, node):
+ target = self.visit(node.target)
+ lines = []
+ if isinstance(node.iter, ast.Call) and isinstance(node.iter.func, ast.Name):
+
+ if node.iter.func.id == 'range':
+ if len(node.iter.args)==1:
+ iter = self.visit(node.iter.args[0])
+ lines.append('for %s := 0; %s < %s; %s++ {' %(target, target, iter, target))
+ elif len(node.iter.args)==2:
+ start = self.visit(node.iter.args[0])
+ iter = self.visit(node.iter.args[1])
+ lines.append('for %s := %s; %s < %s; %s++ {' %(target, start, target, iter, target))
+ else:
+ raise SyntaxError('invalid for range loop')
+
+ elif node.iter.func.id == 'enumerate':
+ iter = self.visit(node.iter.args[0])
+ idx = self.visit(node.target.elts[0])
+ tar = self.visit(node.target.elts[1])
+ lines.append('for %s,%s := range %s {' %(idx,tar, iter))
+
+ else:
+ raise SyntaxError('invalid for loop - bad iterator')
+
+ elif isinstance(node.target, ast.List) or isinstance(node.target, ast.Tuple):
+ iter = self.visit( node.iter )
+ key = self.visit(node.target.elts[0])
+ val = self.visit(node.target.elts[1])
+ lines.append('for %s,%s := range %s {' %(key,val, iter))
+
+ else:
+ iter = self.visit( node.iter )
+ lines.append('for _,%s := range %s {' %(target, iter))
+
+ self.push()
+ for b in node.body:
+ lines.append( self.indent()+self.visit(b) )
+ self.pull()
+ lines.append( self.indent()+'}' ) ## end of for loop
+ return '\n'.join(lines)
+
+
+ def _visit_call_helper(self, node):
+ fname = self.visit(node.func)
+ if fname=='__DOLLAR__': fname = '$'
+ elif fname == 'range':
+ assert len(node.args)
+ fname += str(len(node.args))
+
+
+ if node.args:
+ args = [self.visit(e) for e in node.args]
+ args = ', '.join([e for e in args if e])
+ else:
+ args = ''
+
+ if node.keywords:
+ if args: args += ','
+ args += '_kwargs_type_{'
+ x = ['%s:%s' %(kw.arg,self.visit(kw.value)) for kw in node.keywords]
+ x.extend( ['__use__%s:true' %kw.arg for kw in node.keywords] )
+ args += ','.join( x )
+ args += '}'
+
+ if node.starargs:
+ if args: args += ','
+ args += '%s...' %self.visit(node.starargs)
+
+ return '%s(%s)' % (fname, args)
+
+ def _visit_call_helper_go(self, node):
+ name = self.visit(node.func)
+ if name == '__go__':
+ return 'go %s' %self.visit(node.args[0])
+ elif name == '__go_make__':
+ if len(node.args)==2:
+ return 'make(%s, %s)' %(self.visit(node.args[0]), self.visit(node.args[1]))
+ elif len(node.args)==3:
+ return 'make(%s, %s, %s)' %(self.visit(node.args[0]), self.visit(node.args[1]), self.visit(node.args[1]))
+ else:
+ raise SyntaxError('go make requires 2 or 3 arguments')
+ elif name == '__go_make_chan__':
+ return 'make(chan %s)' %self.visit(node.args[0])
+ elif name == '__go__array__':
+ if isinstance(node.args[0], ast.BinOp):# and node.args[0].op == '<<': ## todo assert right is `typedef`
+ a = self.visit(node.args[0].left)
+ return '[]%s' %a
+ else:
+ a = self.visit(node.args[0])
+ return '[]%s{}' %a
+ else:
+ raise SyntaxError(name)
+
+ def visit_Return(self, node):
+ if isinstance(node.value, ast.Tuple):
+ return 'return %s' % ', '.join(map(self.visit, node.value.elts))
+ if node.value:
+ return 'return %s' % self.visit(node.value)
+ return 'return'
+
+ def _visit_function(self, node):
+ if self._function_stack[0] is node:
+ self._vars = set()
+ self._known_vars = set()
+
+ args_typedefs = {}
+ chan_args_typedefs = {}
+ return_type = None
+ for decor in node.decorator_list:
+ if isinstance(decor, ast.Call) and isinstance(decor.func, ast.Name) and decor.func.id == '__typedef__':
+ for key in decor.keywords:
+ #args_typedefs[ key.arg ] = key.value.id
+ args_typedefs[ key.arg ] = self.visit(key.value)
+ elif isinstance(decor, ast.Call) and isinstance(decor.func, ast.Name) and decor.func.id == '__typedef_chan__':
+ for key in decor.keywords:
+ chan_args_typedefs[ key.arg ] = self.visit(key.value)
+ elif isinstance(decor, ast.Call) and isinstance(decor.func, ast.Name) and decor.func.id == 'returns':
+ if decor.keywords:
+ raise SyntaxError('invalid go return type')
+ else:
+ return_type = decor.args[0].id
+
+
+ node._arg_names = []
+ args = []
+ oargs = []
+ offset = len(node.args.args) - len(node.args.defaults)
+ varargs = False
+ varargs_name = None
+ is_method = False
+ for i, arg in enumerate(node.args.args):
+ arg_name = arg.id
+
+ if arg_name not in args_typedefs.keys()+chan_args_typedefs.keys():
+ if arg_name=='self':
+ assert i==0
+ is_method = True
+ continue
+ else:
+ err = 'error in function: %s' %node.name
+ err += '\n missing typedef: %s' %arg.id
+ raise SyntaxError(err)
+
+ if arg_name in args_typedefs:
+ arg_type = args_typedefs[arg_name]
+ a = '%s %s' %(arg_name, arg_type)
+ else:
+ arg_type = chan_args_typedefs[arg_name]
+ a = '%s chan %s' %(arg_name, arg_type)
+
+ dindex = i - offset
+
+ if a.startswith('__variable_args__'): ## TODO support go `...` varargs
+ #varargs_name = a.split('__')[-1]
+ #varargs = ['_vararg_%s'%n for n in range(16) ]
+ #args.append( '[%s]'%','.join(varargs) )
+ raise SyntaxError('TODO *args')
+
+ elif dindex >= 0 and node.args.defaults:
+ default_value = self.visit( node.args.defaults[dindex] )
+ self._kwargs_type_[ arg_name ] = arg_type
+ oargs.append( (arg_name, default_value) )
+ else:
+ args.append( a )
+ node._arg_names.append( arg_name )
+
+ if oargs:
+ #args.append( '[%s]' % ','.join(oargs) )
+ #args.append( '{%s}' % ','.join(oargs) )
+ args.append( '__kwargs _kwargs_type_')
+ node._arg_names.append( '__kwargs' )
+
+ if node.args.vararg:
+ starargs = node.args.vararg
+ assert starargs in args_typedefs
+ args.append( '%s ...%s' %(starargs, args_typedefs[starargs]))
+ node._arg_names.append( starargs )
+
+ node._args_signature = ','.join(args)
+
+ ####
+ if is_method:
+ assert self._class_stack
+ method = '(self *%s) ' %self._class_stack[-1].name
+ else:
+ method = ''
+ out = []
+ if return_type:
+ out.append( self.indent() + 'func %s%s(%s) %s {\n' % (method, node.name, ', '.join(args), return_type) )
+ else:
+ out.append( self.indent() + 'func %s%s(%s) {\n' % (method, node.name, ', '.join(args)) )
+ self.push()
+
+ if oargs:
+ for n,v in oargs:
+ out.append('%s := %s' %(n,v))
+ out.append('if __kwargs.__use__%s {' %n )
+ out.append( ' %s = __kwargs.%s' %(n,n))
+ out.append('}')
+ #out.append('} else { %s := %s }' %(n,v))
+
+ for b in node.body:
+ v = self.visit(b)
+ if v:
+ out.append( self.indent() + v )
+
+ self.pull()
+ out.append( self.indent()+'}' )
+ return '\n'.join(out)
+
+ def _visit_call_helper_var(self, node):
+ args = [ self.visit(a) for a in node.args ]
+ #if args:
+ # out.append( 'var ' + ','.join(args) )
+ if node.keywords:
+ for key in node.keywords:
+ args.append( key.arg )
+
+ for name in args:
+ if name not in self._vars:
+ self._vars.add( name )
+
+ #out = []
+ #for v in args:
+ # out.append( self.indent() + 'var ' + v + ' int')
+
+ #return '\n'.join(out)
+ return ''
+
+ def visit_With(self, node):
+ r = []
+ is_switch = False
+ if isinstance( node.context_expr, ast.Name ) and node.context_expr.id == '__default__':
+ r.append('default:')
+ elif isinstance( node.context_expr, ast.Name ) and node.context_expr.id == '__select__':
+ r.append('select {')
+ is_switch = True
+ elif isinstance( node.context_expr, ast.Call ):
+ if not isinstance(node.context_expr.func, ast.Name):
+ raise SyntaxError( self.visit(node.context_expr))
+
+ if len(node.context_expr.args):
+ a = self.visit(node.context_expr.args[0])
+ else:
+ assert len(node.context_expr.keywords)
+ ## need to catch if this is a new variable ##
+ name = node.context_expr.keywords[0].arg
+ if name not in self._known_vars:
+ a = '%s := %s' %(name, self.visit(node.context_expr.keywords[0].value))
+ else:
+ a = '%s = %s' %(name, self.visit(node.context_expr.keywords[0].value))
+
+ if node.context_expr.func.id == '__case__':
+ r.append('case %s:' %a)
+ elif node.context_expr.func.id == '__switch__':
+ r.append('switch (%s) {' %self.visit(node.context_expr.args[0]))
+ is_switch = True
+ else:
+ raise SyntaxError( 'invalid use of with')
+
+
+ for b in node.body:
+ a = self.visit(b)
+ if a: r.append(a)
+
+ if is_switch:
+ r.append('}')
+
+ return '\n'.join(r)
+
+ def visit_Assign(self, node):
+ target = node.targets[0]
+ if isinstance(target, ast.Tuple):
+ raise NotImplementedError('TODO')
+
+ elif isinstance(node.value, ast.BinOp) and self.visit(node.value.op)=='<<' and isinstance(node.value.left, ast.Name) and node.value.left.id=='__go__send__':
+ target = self.visit(target)
+ value = self.visit(node.value.right)
+ return '%s <- %s;' % (target, value)
+
+ elif not self._function_stack:
+ target = self.visit(target)
+ value = self.visit(node.value)
+ return 'var %s = %s;' % (target, value)
+
+ elif isinstance(node.targets[0], ast.Name) and target.id in self._vars:
+ target = self.visit(target)
+ value = self.visit(node.value)
+ self._vars.remove( target )
+ self._known_vars.add( target )
+ return '%s := %s;' % (target, value)
+
+ else:
+ target = self.visit(target)
+ value = self.visit(node.value)
+
+ #if '<-' in value:
+ # raise RuntimeError(target+value)
+
+ return '%s = %s;' % (target, value)
+
+ def visit_While(self, node):
+ cond = self.visit(node.test)
+ if cond == 'true' or cond == '1': cond = ''
+ body = [ 'for %s {' %cond]
+ self.push()
+ for line in list( map(self.visit, node.body) ):
+ body.append( self.indent()+line )
+ self.pull()
+ body.append( self.indent() + '}' )
+ return '\n'.join( body )
+
+ def _inline_code_helper(self, s):
+ return s
+ #return 'js.Global.Call("eval", "%s")' %s ## TODO inline JS()
+
+
+
+
+
+def main(script, insert_runtime=True):
+
+ if insert_runtime:
+ dirname = os.path.dirname(os.path.abspath(__file__))
+ dirname = os.path.join(dirname, 'runtime')
+ runtime = open( os.path.join(dirname, 'go_builtins.py') ).read()
+ script = runtime + '\n' + script
+
+ tree = ast.parse(script)
+ #return GoGenerator().visit(tree)
+ try:
+ return GoGenerator().visit(tree)
+ except SyntaxError as err:
+ sys.stderr.write(script)
+ raise err
+
+
+
+def command():
+ scripts = []
+ if len(sys.argv) > 1:
+ for arg in sys.argv[1:]:
+ if arg.endswith('.py'):
+ scripts.append( arg )
+
+ if len(scripts):
+ a = []
+ for script in scripts:
+ a.append( open(script, 'rb').read() )
+ data = '\n'.join( a )
+ else:
+ data = sys.stdin.read()
+
+ out = main( data )
+ print( out )
+
+
+if __name__ == '__main__':
+ command()
diff --git a/pythonjs/runtime/builtins.py b/pythonjs/runtime/builtins.py
index 5feb40d..7047472 100644
--- a/pythonjs/runtime/builtins.py
+++ b/pythonjs/runtime/builtins.py
@@ -9,13 +9,27 @@
_PythonJS_UID = 0
-JS('IndexError = function(msg) {this.message = msg || "";}; IndexError.prototype = Object.create(Error.prototype); IndexError.prototype.name = "IndexError";')
-JS('KeyError = function(msg) {this.message = msg || "";}; KeyError.prototype = Object.create(Error.prototype); KeyError.prototype.name = "KeyError";')
-JS('ValueError = function(msg) {this.message = msg || "";}; ValueError.prototype = Object.create(Error.prototype); ValueError.prototype.name = "ValueError";')
-JS('AttributeError = function(msg) {this.message = msg || "";}; AttributeError.prototype = Object.create(Error.prototype);AttributeError.prototype.name = "AttributeError";')
-JS('RuntimeError = function(msg) {this.message = msg || "";}; RuntimeError.prototype = Object.create(Error.prototype);RuntimeError.prototype.name = "RuntimeError";')
+inline('IndexError = function(msg) {this.message = msg || "";}; IndexError.prototype = Object.create(Error.prototype); IndexError.prototype.name = "IndexError";')
+inline('KeyError = function(msg) {this.message = msg || "";}; KeyError.prototype = Object.create(Error.prototype); KeyError.prototype.name = "KeyError";')
+inline('ValueError = function(msg) {this.message = msg || "";}; ValueError.prototype = Object.create(Error.prototype); ValueError.prototype.name = "ValueError";')
+inline('AttributeError = function(msg) {this.message = msg || "";}; AttributeError.prototype = Object.create(Error.prototype);AttributeError.prototype.name = "AttributeError";')
+inline('RuntimeError = function(msg) {this.message = msg || "";}; RuntimeError.prototype = Object.create(Error.prototype);RuntimeError.prototype.name = "RuntimeError";')
+
+with lowlevel:
+ def __getfast__(ob, attr):
+ v = ob[ attr ]
+ if v is undefined:
+ raise AttributeError(attr)
+ else:
+ return v
+
with javascript:
+ def __wrap_function__(f):
+ f.is_wrapper = True
+ return f
+
+
def __gpu_object(cls, struct_name, data_name):
cls.prototype.__struct_name__ = struct_name
cls.prototype.__struct_data__ = data_name
@@ -48,6 +62,18 @@ def compile_header(self):
a.push('int matrix_index() { return int(get_global_id().y*%s.0); }' %self.matrices.length)
a.push('int matrix_row() { return int(get_global_id().x*4.0); }') ## returns: 0, 1, 2, 3
+ ## first class array error, can not return an array, even when the size is known ##
+ #a.push('float[3] floatN( float a, float b, float c) { float f[3]; f[0]=a; f[1]=b; f[2]=b; return f; }')
+
+ ## these could be generated for each array size to reduce the mess in main,
+ ## TODO it would be better to upload them as uniforms.
+ #a.push('void floatN( float f[3], float a, float b, float c) { f[0]=a; f[1]=b; f[2]=b; }')
+
+ ## the array can be declared in the header, but not filled with data here.
+ #a.push('float XXX[3];')
+ #a.push('floatN( XXX, 1.1, 2.2, 3.3 );')
+ #a.push('XXX[0]=1.1;')
+
a = '\n'.join(a)
## code in header could be methods that reference the struct types above.
@@ -172,7 +198,11 @@ def structure(self, ob, name):
else:
raise RuntimeError('no method to pack structure: ' +sname)
+ has_arrays = False
if stype:
+ if stype['arrays'].length > 0:
+ has_arrays = True
+
for key in stype['integers']:
args.push( ob[key][0]+'' )
@@ -196,7 +226,11 @@ def structure(self, ob, name):
args.push( aname )
args = ','.join(args)
- self.shader.push( sname + ' ' +name+ '=' +sname+ '(' +args+ ');' )
+ if has_arrays:
+ self.shader.push( sname + ' ' +name+ '=' +sname+ '(' +args+ ');' )
+ else:
+ self.header.push( 'const ' + sname + ' ' +name+ '=' +sname+ '(' +args+ ');' )
+ return stype
def int16array(self, ob, name):
a = ['int ' + name + '[' + ob.length + ']']
@@ -349,13 +383,24 @@ def __split_method( ob, delim ):
with javascript:
- def __is_some_array( ob ):
- if typeof(NodeList) == 'function': ## NodeList is only available in browsers
- dom_array_types = [ NodeList, FileList, ClientRectList, DOMStringList, HTMLCollection, HTMLAllCollection, SVGElementInstanceList, SVGNumberList, SVGTransformList]
- if typeof(DataTransferItemList) == 'function': ## missing in NodeWebkit
- dom_array_types.append( DataTransferItemList )
+ __dom_array_types__ = []
+ if typeof(NodeList) == 'function': ## NodeList is only available in browsers
+ ## minimal dom array types common to allow browsers ##
+ __dom_array_types__ = [ NodeList, FileList, DOMStringList, HTMLCollection, SVGNumberList, SVGTransformList]
+
+ ## extra dom array types ##
+ if typeof(DataTransferItemList) == 'function': ## missing in NodeWebkit
+ __dom_array_types__.push( DataTransferItemList )
+ if typeof(HTMLAllCollection) == 'function': ## missing in Firefox
+ __dom_array_types__.push( HTMLAllCollection )
+ if typeof(SVGElementInstanceList) == 'function':## missing in Firefox
+ __dom_array_types__.push( SVGElementInstanceList )
+ if typeof(ClientRectList) == 'function': ## missing in Firefox-trunk
+ __dom_array_types__.push( ClientRectList )
- for t in dom_array_types:
+ def __is_some_array( ob ):
+ if __dom_array_types__.length > 0:
+ for t in __dom_array_types__:
if instanceof(ob, t):
return True
return False
@@ -439,13 +484,17 @@ def __jsdict( items ):
d = JS("{}")
for item in items:
key = item[0]
- if key.__uid__:
+ if instanceof(key, Array):
+ key = JSON.stringify(key)
+ elif key.__uid__:
key = key.__uid__
d[ key ] = item[1]
return d
def __jsdict_get(ob, key, default_value):
if instanceof(ob, Object):
+ if instanceof(key, Array):
+ key = JSON.stringify(key)
if JS("key in ob"): return ob[key]
return default_value
else: ## PythonJS object instance ##
@@ -457,6 +506,8 @@ def __jsdict_get(ob, key, default_value):
def __jsdict_set(ob, key, value):
if instanceof(ob, Object):
+ if instanceof(key, Array):
+ key = JSON.stringify(key)
ob[ key ] = value
else: ## PythonJS object instance ##
## this works because instances from PythonJS are created using Object.create(null) ##
@@ -464,6 +515,9 @@ def __jsdict_set(ob, key, value):
def __jsdict_keys(ob):
if instanceof(ob, Object):
+ ## in the case of tuple keys this would return stringified JSON instead of the original arrays,
+ ## TODO, should this loop over the keys and convert the json strings back to objects?
+ ## but then how would we know if a given string was json... special prefix character?
return JS("Object.keys( ob )")
else: ## PythonJS object instance ##
## this works because instances from PythonJS are created using Object.create(null) ##
@@ -752,22 +806,28 @@ def int16(a): ## used by glsljit when packing structs.
def float(a):
with javascript:
- a = Number(a)
- if isNaN(a):
- raise ValueError('not a number')
- return a
-
-def round(a, places):
+ if typeof(a)=='string':
+ if a.lower()=='nan':
+ return NaN
+ elif a.lower()=='inf':
+ return Infinity
+
+ b = Number(a)
+ if isNaN(b):
+ ## invalid strings also convert to NaN, throw error ##
+ raise ValueError('can not convert to float: '+a)
+ return b
+
+def round(a, places=0):
with javascript:
b = '' + a
if b.indexOf('.') == -1:
return a
else:
- c = b.split('.')
- x = c[0]
- y = c[1].substring(0, places)
- return parseFloat( x+'.'+y )
-
+ ## this could return NaN with large numbers and large places,
+ ## TODO check for NaN and instead fallback to `a.toFixed(places)`
+ p = Math.pow(10, places)
+ return Math.round(a * p) / p
def str(s):
return ''+s
@@ -970,10 +1030,11 @@ def func():
@Array.prototype.__getslice__
def func(start, stop, step):
- arr = [] #new(Array(this.length))
+ arr = []
start = start | 0
- stop = stop | this.length
+ if stop is undefined:
+ stop = this.length
if start < 0:
start = this.length + start
@@ -1323,7 +1384,25 @@ def list(a):
raise TypeError
-
+with javascript:
+ def __tuple_key__(arr):
+ r = []
+ i = 0
+ while i < arr.length:
+ item = arr[i]
+ t = typeof(item)
+ if t=='string':
+ r.append( "'"+item+"'")
+ elif instanceof(item, Array):
+ r.append( __tuple_key__(item) )
+ elif t=='object':
+ if item.__uid__ is undefined:
+ raise KeyError(item)
+ r.append( item.__uid__ )
+ else:
+ r.append( item )
+ i += 1
+ return r.join(',')
class dict:
# http://stackoverflow.com/questions/10892322/javascript-hashtable-use-object-key
@@ -1340,10 +1419,17 @@ def __init__(self, js_object=None, pointer=None):
ob = js_object
if instanceof(ob, Array):
for o in ob:
- if instanceof(o, Array):
- self.__setitem__( o[0], o[1] )
- else:
- self.__setitem__( o['key'], o['value'] )
+ with lowlevel:
+ if instanceof(o, Array):
+ k= o[0]; v= o[1]
+ else:
+ k= o['key']; v= o['value']
+
+ try:
+ self.__setitem__( k,v )
+ except KeyError:
+ raise KeyError('error in dict init, bad key')
+
elif isinstance(ob, dict):
for key in ob.keys():
value = ob[ key ]
@@ -1407,38 +1493,55 @@ def __len__(self):
def __getitem__(self, key):
'''
- notes:
- . '4' and 4 are the same key
- . it is possible that the translator mistakes a javascript-object for a dict and inlines this function,
- that is why below we return the key in self if __dict is undefined.
+ note: `"4"` and `4` are the same key in javascript, is there a sane way to workaround this,
+ that can remain compatible with external javascript?
'''
- __dict = self[...]
- if JS("typeof(key) === 'object' || typeof(key) === 'function'"):
- # Test undefined because it can be in the dict
- if JS("key.__uid__ && key.__uid__ in __dict"):
- return JS('__dict[key.__uid__]')
- raise KeyError(key)
+ with javascript:
+ __dict = self[...]
+ err = False
+ if instanceof(key, Array):
+ #key = JSON.stringify( key ) ## fails on objects with circular references ##
+ key = __tuple_key__(key)
+ elif JS("typeof(key) === 'object' || typeof(key) === 'function'"):
+ # Test undefined because it can be in the dict
+ if JS("key.__uid__ && key.__uid__ in __dict"):
+ return JS('__dict[key.__uid__]')
+ else:
+ err = True
- # Tested after in order to not convert functions to strings.
- # The slow down is negligible
- if __dict and JS("key in __dict"):
- return JS('__dict[key]')
+ if __dict and JS("key in __dict"):
+ return JS('__dict[key]')
+ else:
+ err = True
- raise KeyError(key)
+ if err:
+ msg = "missing key: %s -\n" %key
+ raise KeyError(__dict.keys())
def __setitem__(self, key, value):
- __dict = self[...]
- if JS("typeof(key) === 'object' || typeof(key) === 'function'"):
- if JS("key.__uid__ === undefined"):
- # "" is needed so that integers can also be
- # used as keys
- JS(u"key.__uid__ = '' + _PythonJS_UID++")
- JS('__dict[key.__uid__] = value')
- else:
- JS('__dict[key] = value')
+ with javascript:
+ if key is undefined:
+ raise KeyError('undefined is invalid key type')
+ if key is null:
+ raise KeyError('null is invalid key type')
+
+ __dict = self[...]
+ if instanceof(key, Array):
+ #key = JSON.stringify( key ) ## fails on objects with circular references ##
+ key = __tuple_key__(key)
+ if key is undefined:
+ raise KeyError('undefined is invalid key type (tuple)')
+ inline( '__dict[key] = value')
+ elif JS("typeof(key) === 'object' || typeof(key) === 'function'"):
+ if JS("key.__uid__ === undefined"):
+ # "" is needed so that integers can also be used as keys #
+ JS(u"key.__uid__ = '' + _PythonJS_UID++")
+ JS('__dict[key.__uid__] = value')
+ else:
+ JS('__dict[key] = value')
def keys(self):
- with javascript:
+ with lowlevel:
return Object.keys( self[...] )
def pop(self, key, d=None):
@@ -1776,7 +1879,7 @@ def read(self, binary=False):
path = self.path
with javascript:
if binary or self.binary:
- return _fs.readFileSync( path )
+ return _fs.readFileSync( path, encoding=None )
else:
return _fs.readFileSync( path, {'encoding':'utf8'} )
@@ -1785,8 +1888,18 @@ def write(self, data, binary=False):
path = self.path
with javascript:
if binary or self.binary:
- _fs.writeFileSync( path, data )
+ binary = binary or self.binary
+ if binary == 'base64': ## TODO: fixme, something bad in this if test
+ #print('write base64 data')
+ buff = new Buffer(data, 'base64')
+ _fs.writeFileSync( path, buff, {'encoding':None})
+
+ else:
+ #print('write binary data')
+ #print(binary)
+ _fs.writeFileSync( path, data, {'encoding':None})
else:
+ #print('write utf8 data')
_fs.writeFileSync( path, data, {'encoding':'utf8'} )
def close(self):
diff --git a/pythonjs/runtime/go_builtins.py b/pythonjs/runtime/go_builtins.py
new file mode 100644
index 0000000..0cb2019
--- /dev/null
+++ b/pythonjs/runtime/go_builtins.py
@@ -0,0 +1,57 @@
+# PythonJS Go builtins
+# by Brett Hartshorn - copyright 2014
+# License: "New BSD"
+
+import strconv
+
+inline("""
+
+func str(v interface{}) string {
+ switch v.(type) {
+ case nil:
+ return "None"
+ case int:
+ i,_ := v.(int)
+ return strconv.Itoa(i)
+ case float64:
+ return "TODO float"
+ case bool:
+ b,_ := v.(bool)
+ if b { return "True"
+ } else { return "False" }
+ case string:
+ s,_ := v.(string)
+ return s
+ default:
+ return "TODO unknown type"
+
+ }
+}
+
+func range1( x int ) []int {
+ arr := make([]int, x)
+ for i := 0; i < x; i++ {
+ arr[i]=i
+ }
+ return arr
+}
+
+func range2( start int, stop int ) []int {
+ arr := make([]int, stop-start)
+ for i := start; i < stop; i++ {
+ arr[i]=i
+ }
+ return arr
+}
+
+func range3( start int, stop int, step int ) []int {
+ arr := make([]int, stop-start)
+ for i := start; i < stop; i+=step {
+ arr[i]=i
+ }
+ return arr
+}
+
+""")
+
+
diff --git a/pythonjs/runtime/pythonpythonjs.py b/pythonjs/runtime/pythonpythonjs.py
index 438bbad..70bbf09 100644
--- a/pythonjs/runtime/pythonpythonjs.py
+++ b/pythonjs/runtime/pythonpythonjs.py
@@ -333,7 +333,14 @@ def method(args,kwargs):
## getting/setting from a normal JavaScript Object ##
if attribute == '__getitem__':
- def wrapper(args,kwargs): return object[ args[0] ]
+ ## TODO, should object be checked if it really is an object here?
+ ## new rule: if value to return is `undefined` throw KeyError,
+ ## this could be a problem with some external js libraries but should be rare,
+ ## because most libraries will initalize keys to `null`
+ def wrapper(args,kwargs):
+ v = object[ args[0] ]
+ if v is undefined:
+ raise KeyError( args[0] )
wrapper.is_wrapper = True
return wrapper
elif attribute == '__setitem__':
diff --git a/pythonjs/translator.py b/pythonjs/translator.py
index 7639639..0b772f9 100755
--- a/pythonjs/translator.py
+++ b/pythonjs/translator.py
@@ -7,83 +7,132 @@
from pythonjs_to_coffee import main as pythonjs_to_coffee
from pythonjs_to_lua import main as pythonjs_to_lua
from pythonjs_to_luajs import main as pythonjs_to_luajs
+from pythonjs_to_go import main as pythonjs_to_go
cmdhelp = """\
-usage: translator.py [--dart|--coffee|--lua] file.py
- translator.py --visjs file.py\
+usage: translator.py [--dart|--coffee|--lua|--go|--visjs|--no-wrapper|--analyze] file.py
+
+example:
+ translator.py --no-wrapper myscript.py > myscript.js
"""
+
def main(script, module_path=None):
- if '--visjs' in sys.argv:
- import python_to_visjs
- return python_to_visjs.main( script )
- else:
- code = ''
- if '--dart' in sys.argv:
- a = python_to_pythonjs(script, dart=True, module_path=module_path)
- code = pythonjs_to_dart( a )
- elif '--coffee' in sys.argv:
- a = python_to_pythonjs(script, coffee=True, module_path=module_path)
- code = pythonjs_to_coffee( a )
- elif '--lua' in sys.argv:
- a = python_to_pythonjs(script, lua=True, module_path=module_path)
- try: code = pythonjs_to_lua( a )
- except SyntaxError:
- err = traceback.format_exc()
- lineno = 0
- for line in err.splitlines():
- if "" in line:
- lineno = int(line.split()[-1])
-
- b = a.splitlines()[ lineno ]
- sys.stderr.write( '\n'.join([err,b]) )
-
- elif '--luajs' in sys.argv: ## converts back to javascript
- a = python_to_pythonjs(script, lua=True, module_path=module_path)
- code = pythonjs_to_luajs( a )
- else:
- a = python_to_pythonjs(script, module_path=module_path)
- if isinstance(a, dict):
- res = {}
- for jsfile in a:
- res[ jsfile ] = pythonjs_to_javascript( a[jsfile], webworker=jsfile != 'main' )
- return res
- else:
- ## requirejs module is on by default, this wraps the code in a `define` function
- ## and returns `__module__`
- ## if --no-wrapper is used, then the raw javascript is returned.
- code = pythonjs_to_javascript( a, requirejs='--no-wrapper' not in sys.argv )
-
- return code
+ if '--visjs' in sys.argv:
+ import python_to_visjs
+ return python_to_visjs.main( script )
+ else:
+ code = ''
+ res = None
+ if '--go' in sys.argv:
+ a = python_to_pythonjs(script, go=True, module_path=module_path)
+ code = pythonjs_to_go( a )
+ elif '--gopherjs' in sys.argv:
+ a = python_to_pythonjs(script, go=True, module_path=module_path)
+ code = pythonjs_to_go( a )
+
+ exe = os.path.expanduser('~/go/bin/gopherjs')
+ if not os.path.isfile(exe):
+ raise RuntimeError('gopherjs not installed to ~/go/bin/gopherjs')
+ import subprocess
+ path = '/tmp/gopherjs-input.go'
+ open(path, 'wb').write(code)
+ subprocess.check_call([exe, 'build', path], cwd='/tmp')
+ code = open('/tmp/gopherjs-input.js', 'rb').read()
+
+ elif '--dart' in sys.argv:
+ a = python_to_pythonjs(script, dart=True, module_path=module_path)
+ code = pythonjs_to_dart( a )
+ elif '--coffee' in sys.argv:
+ a = python_to_pythonjs(script, coffee=True, module_path=module_path)
+ code = pythonjs_to_coffee( a )
+ elif '--lua' in sys.argv:
+ a = python_to_pythonjs(script, lua=True, module_path=module_path)
+ try: code = pythonjs_to_lua( a )
+ except SyntaxError:
+ err = traceback.format_exc()
+ lineno = 0
+ for line in err.splitlines():
+ if "" in line:
+ lineno = int(line.split()[-1])
+
+ b = a.splitlines()[ lineno ]
+ sys.stderr.write( '\n'.join([err,b]) )
+
+ elif '--luajs' in sys.argv: ## converts back to javascript
+ a = python_to_pythonjs(script, lua=True, module_path=module_path)
+ code = pythonjs_to_luajs( a )
+ else:
+ a = python_to_pythonjs(script, module_path=module_path)
+
+ if isinstance(a, dict):
+ res = {}
+ for jsfile in a:
+ res[ jsfile ] = pythonjs_to_javascript( a[jsfile], webworker=jsfile != 'main' )
+ return res
+ else:
+ ## requirejs module is on by default, this wraps the code in a `define` function
+ ## and returns `__module__`
+ ## if --no-wrapper is used, then the raw javascript is returned.
+ code = pythonjs_to_javascript( a, requirejs='--no-wrapper' not in sys.argv )
+
+ if '--analyze' in sys.argv:
+ dartanalyzer = os.path.expanduser('~/dart-sdk/bin/dartanalyzer')
+ #dart2js = os.path.expanduser('~/dart-sdk/bin/dart2js')
+ assert os.path.isfile( dartanalyzer )
+
+ x = python_to_pythonjs(script, dart=True, module_path=module_path)
+ dartcode = pythonjs_to_dart( x )
+ path = '/tmp/debug.dart'
+ open(path, 'wb').write( dartcode )
+ import subprocess
+ try:
+ subprocess.check_output( [dartanalyzer, path] )
+ except subprocess.CalledProcessError as err:
+ dartcodelines = dartcode.splitlines()
+ for line in err.output.splitlines():
+ if line.startswith('[error]'):
+ a,b = line.split( path )
+ a = a[:-1]
+ print( '\x1B[0;31m' + a + '\x1B[0m' )
+ lineno = int( b.split('line ')[-1].split(',')[0] )
+ print('line: %s' %lineno)
+ print( dartcodelines[lineno-1] )
+ sys.exit(1)
+
+ if res: ## dict return
+ return res
+ else:
+ return code
def command():
- if '-h' in sys.argv or '--help' in sys.argv:
- print(cmdhelp)
- return
-
- mpath = None
- scripts = []
- if len(sys.argv) > 1:
- for arg in sys.argv[1:]:
- if arg.endswith('.py'):
- scripts.append( arg )
- if mpath is None:
- mpath = os.path.split(arg)[0]
-
- if len(scripts):
- a = []
- for script in scripts:
- a.append( open(script, 'rb').read() )
- data = '\n'.join( a )
- else:
- data = sys.stdin.read()
-
- js = main(data, module_path=mpath)
- if isinstance(js, dict):
- print( json.dumps(js) )
- else:
- print(js)
+ if '-h' in sys.argv or '--help' in sys.argv:
+ print(cmdhelp)
+ return
+
+ mpath = None
+ scripts = []
+ if len(sys.argv) > 1:
+ for arg in sys.argv[1:]:
+ if arg.endswith('.py') or arg.endswith('.html'):
+ scripts.append( arg )
+ if mpath is None:
+ mpath = os.path.split(arg)[0]
+
+ if len(scripts):
+ a = []
+ for script in scripts:
+ a.append( open(script, 'rb').read() )
+ data = '\n'.join( a )
+ else:
+ data = sys.stdin.read()
+
+ js = main(data, module_path=mpath)
+ if isinstance(js, dict):
+ print( json.dumps(js) )
+ else:
+ print(js)
if __name__ == '__main__':
- command()
+ command()
diff --git a/pythonjs/typedpython.py b/pythonjs/typedpython.py
index 8e1b80a..f5bf3f3 100644
--- a/pythonjs/typedpython.py
+++ b/pythonjs/typedpython.py
@@ -21,10 +21,22 @@
__whitespace = [' ', '\t']
+GO_SPECIAL_CALLS = {
+ 'go' : '__go__',
+ 'go.channel' : '__go_make_chan__',
+ 'go.array' : '__go__array__',
+ 'go.make' : '__go_make__'
+}
+
def transform_source( source, strip=False ):
output = []
+ output_post = None
+
for line in source.splitlines():
a = []
+ hit_go_typedef = False
+ gotype = None
+
for i,char in enumerate(line):
nextchar = None
j = i+1
@@ -33,7 +45,41 @@ def transform_source( source, strip=False ):
if nextchar.strip(): break
j += 1
- if a and char in __whitespace:
+ if a and char==']' and j==i+1 and nextchar!=None and nextchar in '[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
+ assert '[' in a
+ gotype = []
+ b = a.pop()
+ while b != '[':
+ gotype.append(b)
+ b = a.pop()
+ gotype.reverse()
+ gotype = ''.join(gotype)
+ if not gotype:
+ if nextchar=='[':
+ a.append('__go__array__<<')
+ else:
+ a.append('__go__array__(')
+ elif gotype.isdigit():
+ a.append('__go__arrayfixed__(%s,' %gotype)
+ else:
+ assert ''.join(a[-3:])=='map'
+ a.pop(); a.pop(); a.pop()
+ a.append('__go__map__(%s,' %gotype)
+ hit_go_typedef = True
+
+ elif hit_go_typedef and char=='(':
+ a.append(')<<(')
+ hit_go_typedef = False
+ elif hit_go_typedef and char=='{':
+ a.append(')<<{')
+ hit_go_typedef = False
+ elif hit_go_typedef and char==',':
+ #a.append(', type=True),') ## this breaks function annotations that splits on ','
+ a.append('<>')
+ if '\tnew ' in c:
+ c = c.replace('\tnew ', ' __new__>>')
+
+
+ ## golang
+
+ if c.strip().startswith('switch '):
+ c = c.replace('switch ', 'with __switch__(').replace(':', '):')
+
+ if c.strip().startswith('default:'):
+ c = c.replace('default:', 'with __default__:')
+
+ if c.strip().startswith('select:'):
+ c = c.replace('select:', 'with __select__:')
+
+ if c.strip().startswith('case ') and c.strip().endswith(':'):
+ c = c.replace('case ', 'with __case__(').replace(':', '):')
+
+ if '<-' in c:
+ if '=' in c:
+ c = c.replace('<-', '__go__receive__<<')
+ else:
+ ## keeping `=` allows for compatible transform to stacklessPython API,
+ ## this is not used now because it is not required by the Go backend.
+ c = c.replace('<-', '= __go__send__<<')
+ #c = c.replace('<-', '<<__go__send__<<')
+
+
+ ## X.method.bind(X) shortcut `->`
+ if '->' in c:
+ a,b = c.split('->')
+ this_name = a.split()[-1].split('=')[-1].split(':')[-1].split(',')[-1]
+ method_name = b.split()[0].split('(')[0]
+ c = c.replace('->'+method_name, '.'+method_name+'.bind(%s)'%this_name)
+
+ ## callback=def .. inline function ##
+ if '=def ' in c or '= def ' in c or ': def ' in c or ':def ' in c:
+ if '=def ' in c:
+ d = '=def '
+ elif '= def ' in c:
+ d = '= def '
+ elif ': def ' in c:
+ d = ': def '
+ elif ':def ' in c:
+ d = ':def '
+
+ if 'def (' in c:
+ c = c.replace('def (', 'def __NAMELESS__(')
+ c, tail = c.split(d)
+
+ #if d.startswith('='):
+ # if '(' in c:
+ # c += '=lambda __INLINE_FUNCTION__: %s )' %tail.strip().split(':')[0]
+ # else:
+ # c += '=lambda __INLINE_FUNCTION__: %s' %tail.strip().split(':')[0]
+ # output_post = 'def %s'%tail
+
+ if d.startswith('='):
+ c += '=lambda __INLINE_FUNCTION__: %s' %tail.strip().split(':')[0]
+
+ if output_post:
+ if output_post[-1][-1]==',':
+ output_post[-1] = output_post[-1][:-1]
+ output[-1] += ','
+ else: output_post = list()
+
+ output.append( c )
+
+ c = 'def %s'%tail
+
+ else:
+ c += ':lambda __INLINE_FUNCTION__: %s,' %tail.strip().split(':')[0]
+ output.append( c )
+ if output_post:
+ if output_post[-1][-1]==',':
+ output_post[-1] = output_post[-1][:-1]
+ else: output_post = list()
+ c = 'def %s'%tail
+
+
+ ## python3 annotations
+ if 'def ' in c and c.count(':') > 1:
+ indent = 0
+ for u in c:
+ if u == ' ' or u == '\t':
+ indent += 1
+ else:
+ break
+ indent = '\t'*indent
+
+ #head, tail = c.split('(')
+ head = c[ : c.index('(') ]
+ tail = c[ c.index('(')+1 : ]
+ args = []
+ #tail, tailend = tail.split(')')
+ tailend = tail[ tail.rindex(')')+1 : ]
+ tail = tail[ : tail.rindex(')') ]
+
+
+ for x in tail.split(','):
+ y = x
+ if ':' in y:
+ kw = None
+ if '=' in y:
+ y, kw = y.split('=')
+ arg, typedef = y.split(':')
+ chan = False
+ if len(typedef.strip().split()) == 2:
+ chan = True
+ typedef = typedef.strip().split()[-1]
+ if '*' in arg:
+ arg_name = arg.split('*')[-1]
+ else:
+ arg_name = arg
+
+ if chan:
+ output.append('%s@typedef_chan(%s=%s)' %(indent, arg_name, typedef))
+ else:
+ output.append('%s@typedef(%s=%s)' %(indent, arg_name, typedef))
+ if kw:
+ arg += '=' + kw
+ args.append(arg)
+ else:
+ args.append(x)
+ c = head +'(' + ','.join(args) + ')'+tailend
+
## jquery ##
## TODO ensure this is not inside quoted text
@@ -103,9 +313,41 @@ def transform_source( source, strip=False ):
if c.strip().startswith('nonlocal '): ## Python3 syntax
c = c.replace('nonlocal ', 'global ') ## fake nonlocal with global
- output.append( c )
+ if type(output_post) is list:
+ output_post.append( c )
+ else:
+ output.append( c )
+
+ if type(output_post) is str: ## DEPRECATED
+ indent = 0
+ for u in output[-1]:
+ if u == ' ' or u == '\t':
+ indent += 1
+ else:
+ break
+ output.append( ('\t'*indent)+output_post)
+ output_post = True
+ elif output_post == True: ## DEPRECATED
+ if output[-1].strip()==')':
+ output.pop()
+ output_post = None
+
+ elif type(output_post) is list:
+ if output_post[-1].strip().endswith( ('}',')') ):
+ output.append( output_post.pop() )
+ indent = 0
+ for u in output[-1]:
+ if u == ' ' or u == '\t':
+ indent += 1
+ else:
+ break
+ for ln in output_post:
+ output.append( ('\t'*indent)+ln )
+
+ output_post = None
- return '\n'.join(output)
+ r = '\n'.join(output)
+ return r
test = '''
@@ -117,6 +359,95 @@ def transform_source( source, strip=False ):
if True:
float* def Y():
pass
+
+A.callback = B->method
+A.do_something( x,y,z, B->method )
+A.do_something( x,y,z, callback=B->method )
+A.do_something( x,y,z, callback=def cb(x):
+ return x+y
+)
+A.do_something( x,y,z, callback=def (x,y,z):
+ return x+y
+)
+a = {
+ 'cb1': def (x,y):
+ return x+y
+}
+def xxx():
+ b = {
+ 'cb1': def (x,y):
+ return x+y,
+ 'cb2': def (x,y):
+ return x+y
+ }
+
+X.func( cb1=def ():
+ return 1,
+ cb2=def ():
+ return 2
+)
+
+c = function(x,y):
+ return x+y
+if True:
+ d = a[ 'somekey' ] except KeyError: 'mydefault'
+
+## <- becomes __go__send__<int:
+ return cb(3)
+
+def wrapper(a:int, c:chan int):
+ result = longCalculation(a)
+ c <- result
+
+switch a.f():
+ case 1:
+ print(x)
+ case 2:
+ print(y)
+ default:
+ break
+
+select:
+ case x = <- a:
+ y += x
+ case x = <- b:
+ y += x
+
+## in go becomes: []string{x,y,z}
+## becomes: __go__array__(string) << (x,y,z)
+a = []string(x,y,z)
+
+## in go becomes: [3]int{x,y,z}
+## becomes: __go__arrayfixed__(3, string) << (x,y,z)
+a = [3]int(x,y,z)
+
+## in go becomes: map[string]int{x,y,z}
+## becomes: __go__map__(string, int) << {'x':x, 'y':y, 'z':z}
+a = map[string]int{
+ "x":x, "y":y, "z":z
+}
+
+def f(a:int, b:int, c:int) ->int:
+ return a+b+c
+
+def f(a:int=100, b:int=100) ->int:
+ return a+b
+
+def f(*args:int, **kwargs:int) ->int:
+ return a+b
+
+a = []int(x for x in range(3))
+
+y = go.make([]float64, 1000)
+
+def plot(id:string, latency:[]float64, xlabel:string, title:string ):
+ pass
+
'''
if __name__ == '__main__':
diff --git a/regtests/bench/webclgl_array_mult.py b/regtests/bench/webclgl_array_mult.py
index ff57deb..868b5fc 100644
--- a/regtests/bench/webclgl_array_mult.py
+++ b/regtests/bench/webclgl_array_mult.py
@@ -2,18 +2,19 @@
from time import time
from random import random
-def main():
- ARRAY_SIZE = 1024*1024*4
+ARRAY_SIZE = 1024*1024*4
- with glsl as myfunc:
- def main(A, B, C, D):
- float* A
- float* B
- float* C
- float* D
- vec2 n = get_global_id() ## WebCL API
- return A[n] * B[n] * C[n] * D[n]
+@returns( array=ARRAY_SIZE )
+@gpu.main
+def myfunc(A, B, C, D):
+ float* A
+ float* B
+ float* C
+ float* D
+ vec2 n = get_global_id() ## WebCL API
+ return A[n] * B[n] * C[n] * D[n]
+def main():
a = [ random() for i in range(ARRAY_SIZE)]
b = [ random() for i in range(ARRAY_SIZE)]
diff --git a/regtests/bench/webclgl_array_mult_vectorize.py b/regtests/bench/webclgl_array_mult_vectorize.py
deleted file mode 100644
index 5b50e9b..0000000
--- a/regtests/bench/webclgl_array_mult_vectorize.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""big array mult"""
-from time import time
-from random import random
-
-@gpu.vectorize
-def array_mult(a,b,c,d):
- a = numpy.array(a, dtype=numpy.float32 )
- b = numpy.array(b, dtype=numpy.float32 )
- c = numpy.array(c, dtype=numpy.float32 )
- d = numpy.array(d, dtype=numpy.float32 )
- return a * b * c * d
-
-
-def main():
- ARRAY_SIZE = 1024*1024*2
-
- a = [ random() for i in range(ARRAY_SIZE)]
- b = [ random() for i in range(ARRAY_SIZE)]
- c = [ random() for i in range(ARRAY_SIZE)]
- d = [ random() for i in range(ARRAY_SIZE)]
-
- start = time()
- res = array_mult( a,b,c,d )
- print( time()-start )
- #print(res)
diff --git a/regtests/calling/function_expression.py b/regtests/calling/function_expression.py
new file mode 100644
index 0000000..9c12bc7
--- /dev/null
+++ b/regtests/calling/function_expression.py
@@ -0,0 +1,8 @@
+"""func expr"""
+
+F = function( x,y ):
+ return x+y
+
+def main():
+ TestError( F(1,2) == 3 )
+
diff --git a/regtests/calling/inline_def.py b/regtests/calling/inline_def.py
new file mode 100644
index 0000000..431ffca
--- /dev/null
+++ b/regtests/calling/inline_def.py
@@ -0,0 +1,14 @@
+"""inline def"""
+
+def test( callback1=None, callback2=None ):
+ return {'cb1': callback1, 'cb2': callback2 }
+
+def main():
+ o = test( callback1=def (x,y):
+ return x+y,
+ callback2 = def (x):
+ return x*2
+ )
+ TestError( o['cb1'](1,2) == 3 )
+ TestError( o['cb2'](100) == 200 )
+
diff --git a/regtests/calling/variable_kwargs_class.py b/regtests/calling/variable_kwargs_class.py
new file mode 100644
index 0000000..dff64f9
--- /dev/null
+++ b/regtests/calling/variable_kwargs_class.py
@@ -0,0 +1,11 @@
+"""variable keywords"""
+class A:
+ def f2(self, **kw):
+ a = 0
+ for key in kw:
+ a += kw[key]
+ return a
+
+def main():
+ a = A()
+ TestError( a.f2(x=1,y=2) == 3 )
\ No newline at end of file
diff --git a/regtests/calling/variable_kwargs_class_init.py b/regtests/calling/variable_kwargs_class_init.py
new file mode 100644
index 0000000..8086762
--- /dev/null
+++ b/regtests/calling/variable_kwargs_class_init.py
@@ -0,0 +1,11 @@
+"""variable keywords"""
+class A:
+ def __init__(self, **kw):
+ a = 0
+ for key in kw:
+ a += kw[key]
+ self.value = a
+
+def main():
+ a = A(x=1,y=2)
+ TestError( a.value == 3 )
\ No newline at end of file
diff --git a/regtests/class/init_keyword.py b/regtests/class/init_keyword.py
new file mode 100644
index 0000000..3a01559
--- /dev/null
+++ b/regtests/class/init_keyword.py
@@ -0,0 +1,11 @@
+'''
+test __init__ with keyword arg
+'''
+
+def main():
+ class Cell:
+ def __init__(self, x=1):
+ self.x = x
+
+ a = Cell(x=2)
+ TestError(a.x == 2)
\ No newline at end of file
diff --git a/regtests/class/mi.py b/regtests/class/mi.py
index 0b96290..5c1a591 100644
--- a/regtests/class/mi.py
+++ b/regtests/class/mi.py
@@ -2,21 +2,21 @@
multiple inheritance
'''
class A:
- def foo(self):
+ def foo(self) -> int:
return 1
class B:
- def bar(self):
+ def bar(self) -> int:
return 2
class C( A, B ):
- def call_foo_bar(self):
+ def call_foo_bar(self) -> int:
a = self.foo()
a += self.bar()
return a
## extend foo ##
- def foo(self):
+ def foo(self) -> int:
a = A.foo(self)
a += 100
return a
diff --git a/regtests/class/mi_override.py b/regtests/class/mi_override.py
new file mode 100644
index 0000000..d36fb6f
--- /dev/null
+++ b/regtests/class/mi_override.py
@@ -0,0 +1,32 @@
+'''
+multiple inheritance
+'''
+class A:
+ def foo(self) -> int:
+ return 1
+
+class B:
+ def bar(self) -> int:
+ return 2
+
+class C( A, B ):
+ def call_foo_bar(self) -> int:
+ a = self.foo()
+ a += self.bar()
+ return a
+
+ ## override foo ##
+ def foo(self) -> int:
+ return 100
+
+def main():
+ a = A()
+ TestError( a.foo()==1 )
+ b = B()
+ TestError( b.bar()==2 )
+
+ c = C()
+ TestError( c.foo()==100 )
+ TestError( c.bar()==2 )
+
+ TestError( c.call_foo_bar()==102 )
diff --git a/regtests/dict/dict_inline_def.py b/regtests/dict/dict_inline_def.py
new file mode 100644
index 0000000..e4ad9cb
--- /dev/null
+++ b/regtests/dict/dict_inline_def.py
@@ -0,0 +1,17 @@
+"""dict inline def"""
+
+
+def main():
+
+ d = { 'callback': def (x,y):
+ return x+y
+ }
+ TestError( d['callback'](1,2) == 3 )
+
+ a = { 'cb1': def (x,y):
+ return x+y,
+ 'cb2' : def (x):
+ return x*2
+ }
+ TestError( a['cb1'](1,2) == 3 )
+ TestError( a['cb2'](100) == 200 )
diff --git a/regtests/dict/keys.py b/regtests/dict/keys.py
index d47bca9..c7ccdf6 100644
--- a/regtests/dict/keys.py
+++ b/regtests/dict/keys.py
@@ -4,4 +4,3 @@ def main():
a = {'foo':'bar'}
keys = a.keys()
TestError( 'foo' in keys )
-
diff --git a/regtests/dict/tuple_keys.py b/regtests/dict/tuple_keys.py
new file mode 100644
index 0000000..7d3dea0
--- /dev/null
+++ b/regtests/dict/tuple_keys.py
@@ -0,0 +1,34 @@
+"""dict tuple key"""
+
+class A: pass
+class B:
+ def __init__(self):
+ pass
+
+def main():
+ s = ("1", "2", "3")
+ a = (1,2,3)
+ b = (1,2,3)
+ c = ( a, b, 'XXX' )
+ d = ('1', 2, 3)
+
+ D = { d:100, s: 11, a: 22, c:44 }
+ TestError( D[ d ] == 100)
+ TestError( D[ s ] == 11)
+ TestError( D[ a ] == 22)
+ TestError( D[ b ] == 22)
+ TestError( D[ c ] == 44)
+
+ aa = A()
+ bb = B()
+ ab = ( A(), B() )
+ D2 = { aa: 'hello', bb: 'world', ab:'XXX' }
+ TestError( D2[aa]=='hello' )
+ TestError( D2[bb]=='world' )
+ TestError( D2[ab]=='XXX')
+
+ r = { s:1, a:aa }
+ r2 = {}
+ for x in [ s, a ]:
+ r2[ x ] = r[ x ]
+ TestError( r[s] is r2[s] )
\ No newline at end of file
diff --git a/regtests/exceptions/AttributeError.py b/regtests/exceptions/AttributeError.py
new file mode 100644
index 0000000..bb302ae
--- /dev/null
+++ b/regtests/exceptions/AttributeError.py
@@ -0,0 +1,13 @@
+"""catch AttributeError"""
+
+class A: pass
+
+def main():
+ a = A()
+ b = False
+ try:
+ b = a.xxx
+ except AttributeError:
+ b = True
+
+ TestError( b == True )
diff --git a/regtests/exceptions/KeyError.py b/regtests/exceptions/KeyError.py
new file mode 100644
index 0000000..f48ec0d
--- /dev/null
+++ b/regtests/exceptions/KeyError.py
@@ -0,0 +1,11 @@
+"""catch KeyError"""
+
+def main():
+ D = {}
+ a = False
+ try:
+ a = D['XXX']
+ except KeyError:
+ a = True
+
+ TestError( a == True )
diff --git a/regtests/go/arrays.py b/regtests/go/arrays.py
new file mode 100644
index 0000000..76d84e5
--- /dev/null
+++ b/regtests/go/arrays.py
@@ -0,0 +1,22 @@
+"""array types"""
+
+def main():
+ a = []int(1,2,3)
+ TestError( a[0]==1 )
+ TestError( len(a)==3 )
+
+ b = [2]int(100,200)
+ TestError( b[0]==100 )
+ TestError( b[1]==200 )
+
+ c = a[:2]
+ TestError( len(c)==2 )
+
+ d = range(10)
+ TestError(len(d)==10)
+
+ #e = range(2,10)
+ #TestError(len(e)==8)
+
+ #f = range(2,10, 2)
+ #TestError(len(f)==4)
diff --git a/regtests/go/chan-transfer-speed.py b/regtests/go/chan-transfer-speed.py
new file mode 100644
index 0000000..9b0c7fb
--- /dev/null
+++ b/regtests/go/chan-transfer-speed.py
@@ -0,0 +1,107 @@
+# based on the go test by Dennis Francis
+# https://github.com/dennisfrancis/gopherjs-channeltransfer-speed
+
+
+import "github.com/gopherjs/gopherjs/js"
+
+
+data_chan = go.channel(int)
+
+document = js.Global.Get("document")
+
+def main():
+ js.Global.Get("window").Set("onload", setup)
+
+def setup():
+
+ go( receive() )
+ bt = document.Call("getElementById", "startbt")
+ bt.Set("onclick", runtests)
+
+
+def runtests():
+ var bt = document.Call("getElementById", "startbt")
+ bt.Set("disabled", true)
+
+ #go func() {
+ # test_calldepth()
+ # test_localmem()
+ #}()
+
+ go( test_calldepth() )
+ go( test_localmem() )
+
+
+def test_calldepth():
+
+ latency = go.make([]float64, 1000)
+ perf = js.Global.Get("performance")
+ #for cd := 1; cd <= 1000; cd++ {
+ for cd in range(1, 1000):
+ t0 = perf.Call("now").Float()
+ #for ii:=0; ii<50; ii++ {
+ for ii in range(50):
+ send_func(cd, 1, ii)
+ t1 = perf.Call("now").Float()
+ latency[cd-1] = (t1 - t0)/50.0
+ print("test1 calldepth =", cd)
+ plot("ctsgraph1", latency, "Call depth", "Variation of Kilo Channel Transfers per second (KCTps) with call depth")
+
+def test_localmem():
+
+ latency = go.make([]float64, 1000)
+ perf = js.Global.Get("performance")
+ #for varsz := 1; varsz <= 1000; varsz++ {
+ for varsz in range(1, 1000):
+ t0 = perf.Call("now").Float()
+ #for ii:=0; ii<50; ii++ {
+ for ii in range(50):
+ send_func(1, varsz, ii)
+
+ t1 = perf.Call("now").Float()
+ latency[varsz-1] = (t1 - t0)/50.0
+ plot("ctsgraph2", latency, "Local variable size", "Variation of Kilo Channel Transfers per second (KCTps) with local variable size")
+
+
+def plot(id:string, latency:[]float64, xlabel:string, title:string ):
+
+ div = document.Call("getElementById", id)
+ #options = map[string]interface{}{
+ options = map[string]interface{
+ #"legend" : "always",
+ "title" : title,
+ "showRoller" : true,
+ "rollPeriod" : 1,
+ "ylabel" : "KCTps",
+ "labels" : []string("x", "CTS"),
+ }
+
+ data = go.make([][]float64, len(latency))
+
+ #for rowid := 0; rowid < len(latency); rowid++ {
+ for rowid in range(len(latency)):
+ data[rowid] = []float64(
+ float64(rowid + 1),
+ 1.0/latency[rowid]
+ )
+
+
+ js.Global.Get("Dygraph").New(div, data, options)
+
+
+def send_func(call_depth:int, varsize:int, data:int ):
+ locvar = go.make([]int, varsize)
+
+ if call_depth <= 1:
+ data_chan <- data
+ return
+
+ send_func(call_depth-1, varsize, data)
+
+ print(locvar)
+
+def receive():
+ int data = 0
+ while True:
+ data = <-data_chan
+ print("Received data =", data)
diff --git a/regtests/go/chan.py b/regtests/go/chan.py
new file mode 100644
index 0000000..fdf6e02
--- /dev/null
+++ b/regtests/go/chan.py
@@ -0,0 +1,16 @@
+"""send int over channel"""
+
+def wrapper(a:int, c: chan int):
+ result = 100
+ c <- result
+
+def main():
+ c = go.channel(int)
+
+ go( wrapper(17, c) )
+
+ # Do other work in the current goroutine until the channel has a result.
+
+ x = <-c
+ print(x)
+ TestError(x==100)
diff --git a/regtests/go/class.py b/regtests/go/class.py
new file mode 100644
index 0000000..316ca2f
--- /dev/null
+++ b/regtests/go/class.py
@@ -0,0 +1,31 @@
+'''
+simple class
+'''
+class A:
+ {
+ x:int,
+ y:int,
+ z:int,
+ }
+ def __init__(self, x:int, y:int, z:int=1):
+ self.x = x
+ self.y = y
+ self.z = z
+
+ def mymethod(self, m:int) -> int:
+ return self.x * m
+
+def call_method( cb:func(int)(int), mx:int ) ->int:
+ return cb(mx)
+
+def main():
+ a = A( 100, 200, z=9999 )
+ print( a.x )
+ print( a.y )
+ print( a.z )
+
+ b = a.mymethod(3)
+ print( b )
+
+ c = call_method( a.mymethod, 4 )
+ print( c )
\ No newline at end of file
diff --git a/regtests/go/func_calls.py b/regtests/go/func_calls.py
new file mode 100644
index 0000000..bfcd797
--- /dev/null
+++ b/regtests/go/func_calls.py
@@ -0,0 +1,20 @@
+"""function call"""
+def f(a:int, b:int, c:int) ->int:
+ return a+b+c
+
+def f2(a:int=1, b:int=2, c:int=3) ->int:
+ return a+b+c
+
+def f3( *args:int ) ->int:
+ return args[0] + args[1] + args[2]
+
+
+def main():
+ TestError( f(1,2,3) == 6)
+
+ x = f2( b=100 )
+ TestError(x==104)
+
+ arr = [1,2,3]
+ y = f3( *arr )
+ TestError( y==6 )
\ No newline at end of file
diff --git a/regtests/go/list_comprehension.py b/regtests/go/list_comprehension.py
new file mode 100644
index 0000000..75c7f7a
--- /dev/null
+++ b/regtests/go/list_comprehension.py
@@ -0,0 +1,11 @@
+'''
+go list comprehensions
+'''
+
+def main():
+ a = []int(x for x in range(3))
+
+ TestError( len(a)==3 )
+ TestError( a[0]==0 )
+ TestError( a[1]==1 )
+ TestError( a[2]==2 )
diff --git a/regtests/go/loop_arrays.py b/regtests/go/loop_arrays.py
new file mode 100644
index 0000000..b1ec850
--- /dev/null
+++ b/regtests/go/loop_arrays.py
@@ -0,0 +1,34 @@
+'''
+array loop
+'''
+
+def main():
+
+ a = [1,2,3]
+ y = 0
+ for x in a:
+ y += x
+ TestError( y==6 )
+
+ z = ''
+ arr = ['a', 'b', 'c']
+ for v in arr:
+ z += v
+ TestError( z == 'abc' )
+
+ b = 0
+ for i in range(10):
+ b += 1
+ TestError( b == 10 )
+
+ c = ''
+ d = 0
+ for i,v in enumerate(arr):
+ c += v
+ d += i
+ TestError( c == 'abc' )
+
+ e = 0
+ for i in range( len(arr) ):
+ e += 1
+ TestError( e == 3 )
diff --git a/regtests/go/loop_map.py b/regtests/go/loop_map.py
new file mode 100644
index 0000000..403647d
--- /dev/null
+++ b/regtests/go/loop_map.py
@@ -0,0 +1,14 @@
+'''
+map loop
+'''
+
+def main():
+ a = {'x':100, 'y':200}
+ b = ''
+ c = 0
+ for key,value in a:
+ b += key
+ c += value
+
+ print( b )
+ print( c )
\ No newline at end of file
diff --git a/regtests/go/maps.py b/regtests/go/maps.py
new file mode 100644
index 0000000..23248a3
--- /dev/null
+++ b/regtests/go/maps.py
@@ -0,0 +1,24 @@
+"""map types"""
+
+def main():
+ a = map[string]int{
+ 'x': 1,
+ 'y': 2,
+ 'z': 3,
+ }
+
+ #print( a['x'] )
+ TestError( a['x']==1 )
+
+ b = map[int]string{ 0:'a', 1:'b' }
+ #print( b[0] )
+ #print( b[1] )
+ TestError( b[0]=='a' )
+ TestError( b[1]=='b' )
+
+ c = {'x':100, 'y':200}
+ #print( c['x'] )
+ #print( c['y'] )
+
+ TestError( c['x']==100 )
+ TestError( c['y']==200 )
diff --git a/regtests/go/print.py b/regtests/go/print.py
new file mode 100644
index 0000000..363f081
--- /dev/null
+++ b/regtests/go/print.py
@@ -0,0 +1,4 @@
+"""hello world"""
+
+def main():
+ print "hi"
diff --git a/regtests/go/select.py b/regtests/go/select.py
new file mode 100644
index 0000000..6bcb8fe
--- /dev/null
+++ b/regtests/go/select.py
@@ -0,0 +1,43 @@
+"""go select"""
+
+def send_data( A:chan int, B:chan int, X:int, Y:int):
+ while True:
+ print('sending data..')
+ A <- X
+ B <- Y
+
+def select_loop(A:chan int, B:chan int, W:chan int) -> int:
+ print('starting select loop')
+ y = 0
+ while True:
+ print('select loop:',y)
+ select:
+ case x = <- A:
+ y += x
+ W <- y
+ case x = <- B:
+ y += x
+ W <- y
+ print('end select loop', y)
+ return y
+
+def main():
+ a = go.channel(int)
+ b = go.channel(int)
+ w = go.channel(int)
+
+ go(
+ select_loop(a,b, w)
+ )
+
+
+ go(
+ send_data(a,b, 5, 10)
+ )
+
+ z = 0
+ while z < 100:
+ z = <- w
+ print('main loop', z)
+
+ print('end test')
\ No newline at end of file
diff --git a/regtests/go/subclass.py b/regtests/go/subclass.py
new file mode 100644
index 0000000..69e87b9
--- /dev/null
+++ b/regtests/go/subclass.py
@@ -0,0 +1,43 @@
+'''
+simple class
+'''
+class A:
+ {
+ x:int,
+ y:int,
+ z:int,
+ }
+ def __init__(self, x:int, y:int, z:int=1):
+ self.x = x
+ self.y = y
+ self.z = z
+
+ def mymethod(self, m:int) -> int:
+ return self.x * m
+
+class B(A):
+ {
+ w:string
+ }
+
+ def method2(self, v:string) ->string:
+ self.w = v
+ return self.w
+
+def call_method( cb:func(int)(int), mx:int ) ->int:
+ return cb(mx)
+
+def main():
+ a = A( 100, 200, z=9999 )
+ print( a.x )
+ print( a.y )
+ print( a.z )
+
+ b = a.mymethod(3)
+ print( b )
+
+ c = call_method( a.mymethod, 4 )
+ print( c )
+
+ x = B(1,2,z=3)
+ print( x.method2('hello world') )
\ No newline at end of file
diff --git a/regtests/go/vars.py b/regtests/go/vars.py
new file mode 100644
index 0000000..86c1722
--- /dev/null
+++ b/regtests/go/vars.py
@@ -0,0 +1,6 @@
+"""var assignment :=, and reassignment ="""
+
+def main():
+ a = 1
+ a = 2
+ TestError( a==2 )
\ No newline at end of file
diff --git a/regtests/html/date.html b/regtests/html/date.html
new file mode 100644
index 0000000..97b3f50
--- /dev/null
+++ b/regtests/html/date.html
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/regtests/html/dddom.py b/regtests/html/dddom.py
index 7d4d7ef..0335b5e 100644
--- a/regtests/html/dddom.py
+++ b/regtests/html/dddom.py
@@ -199,7 +199,7 @@ def create_slider(value, onchange=None, width=200):
div = document.createElement('div') ## a parent container is required
div.appendChild( slider )
- $( slider ).PPSlider( width=300, onInput=onchange, value=value )
+ $( slider ).PPSlider( width=width, onInput=onchange, value=value )
slider.onclick = lambda : slider.focus()
@@ -218,13 +218,37 @@ def func(): ta.focus() ## this allows normal keyboard input
ta.setAttribute('class', 'focused alert alert-info')
return ta
-def create_checkbox( checked ):
+def create_checkbox( checked, onchange=None ):
## no special hacks required for checkboxes ##
c = document.createElement('input')
c.setAttribute('type', 'checkbox')
if checked: c.setAttribute('checked', 'true')
+ if onchange: c.onchange = onchange
return c
+def create_number_input(value, step=1, onchange=None):
+ input = document.createElement('input')
+ input.setAttribute('type', 'number')
+ input.setAttribute('step', step)
+ input.value = value
+ input.style.width = 64
+ input.style.height = 32
+ input.onclick = lambda : this.focus()
+ if onchange: input.onchange = onchange
+ return input
+
+def create_float_input(value, step=0.01, onchange=None):
+ input = document.createElement('input')
+ input.setAttribute('type', 'number')
+ input.setAttribute('step', step)
+ input.value = value
+ input.style.width = 64
+ input.style.height = 32
+ input.onclick = lambda : this.focus()
+ if onchange: input.onchange = onchange
+ return input
+
+
def create_dropdown_button( name, options ):
div = document.createElement('div')
div.setAttribute('class', 'btn-group')
@@ -254,24 +278,28 @@ def create_dropdown_button( name, options ):
CLICKABLES = []
-def _on_mouse_up(evt):
- x = ( event.clientX / window.innerWidth ) * 2 - 1;
- y = - ( event.clientY / window.innerHeight ) * 2 + 1;
- vector = new THREE.Vector3( x, y, 0.5 );
- projector = new THREE.Projector();
- projector.unprojectVector( vector, camera );
- raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
- intersects = raycaster.intersectObjects( CLICKABLES );
- #if intersects.length > 0:
- # ob = intersects[0].object
- for inter in intersects:
- ob = inter.object
- print(ob)
- if hasattr(ob, 'onclick'):
- ob.onclick( inter )
-
-
-document.addEventListener('mouseup', _on_mouse_up, false)
+class SelectManager:
+ def __init__(self, camera):
+ self.camera = camera
+ document.addEventListener('mouseup', self.on_mouse_up.bind(self), false)
+
+ def on_mouse_up(self, evt):
+ x = ( event.clientX / window.innerWidth ) * 2 - 1;
+ y = - ( event.clientY / window.innerHeight ) * 2 + 1;
+ vector = new THREE.Vector3( x, y, 0.5 );
+ projector = new THREE.Projector();
+ projector.unprojectVector( vector, self.camera );
+ raycaster = new THREE.Raycaster( self.camera.position, vector.sub( self.camera.position ).normalize() );
+ intersects = raycaster.intersectObjects( CLICKABLES );
+ #if intersects.length > 0:
+ # ob = intersects[0].object
+ for inter in intersects:
+ ob = inter.object
+ print(ob)
+ if hasattr(ob, 'onclick'):
+ ob.onclick( inter )
+
+
class Window3D:
def __init__(self, element, scene, shadow_scene, interact_scene, position, scale ):
@@ -327,7 +355,7 @@ def create_tab_menu(self):
def create_iframe( self, url, element ):
## this currently only renders on the top layer transparent layer,
- ## to make iframes visible the top layer needs to become semi-transparent of opaque.
+ ## to make iframes visible the top layer needs to become semi-transparent or opaque.
## `element` is the DOM element that will have its opacity adjusted on mouse enter/leave
iframe = document.createElement('iframe')
iframe.setAttribute('src', url)
@@ -469,7 +497,7 @@ def create_dropdown(self, e, options):
## this needs to be done anyways because `sel` must be given a height in pixels,
## to force it to display all the options, and not display a scroll bar (which are not synced).
H = 12 * options.length
- #if H < 150: H = 150
+ if H < 100: H = 100
sel.style.height = int(H * 0.95)
X = e.offsetLeft / 2
Y = ((self.element.clientHeight-H) / 2) - (e.offsetHeight + e.offsetTop)
@@ -490,10 +518,19 @@ def create_dropdown(self, e, options):
sel.focus() # required?
+ ## this is used to capture a click on the dropdown popup, and copy selectedIndex
+ ## from the clone to the source, and if the source has an onchange callback, call it.
def onclick(evt):
#sel.focus() ## this triggers a bug that offsets the interactive layer
print(evt.toElement.getAttribute('index'))
e.selectedIndex = sel.selectedIndex = int(evt.toElement.getAttribute('index'))
+ ## setting `selectedIndex` on the source e will not trigger its `onchange` callback to fire,
+ ## so call onchange directly. Note that the event `evt` from the clone is passed the source
+ ## as the first argument. end-user code inside e.onchange should not modify elements referenced in the event.
+ ## note that the calling context is set to the source by `e.onchange(evt)` so it is safe to use `this`
+ ## inside of onchange.
+ if e.onchange:
+ e.onchange( evt )
sel.onclick = onclick
def onscroll(evt): ## this hack is required to capture the scroll position
@@ -597,13 +634,11 @@ def expand(inter):
m.castShadow = true;
CLICKABLES.append( m )
- def spin(inter):
+ def clickfooter(inter):
+ self.active = True
if self.collasped:
self.expand()
- else:
- self.spin90()
- self.object.position.x = -200
- m.onclick = spin.bind(self)
+ m.onclick = clickfooter.bind(self)
geo = new THREE.BoxGeometry( 0.2, 0.1, 10 );
mat = new THREE.MeshPhongMaterial( {'color': 0xffff00 } );
@@ -651,7 +686,8 @@ def update(self):
self.mask.scale.x = w*99
self.mask.scale.y = h*99
- self.shadow.element = self.element.cloneNode() ## this is just to display content
+ ## this is just to display content, cloneNode(true) ensures deep copy
+ self.shadow.element = self.element.cloneNode(true)
## sync scrollbars of any div with an id,
## note: this will not work with tab-content div's.
diff --git a/regtests/html/three_catmull_clark.html b/regtests/html/three_catmull_clark.html
new file mode 100644
index 0000000..3b5a5a4
--- /dev/null
+++ b/regtests/html/three_catmull_clark.html
@@ -0,0 +1,216 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/regtests/html/threepy.py b/regtests/html/threepy.py
new file mode 100644
index 0000000..18de547
--- /dev/null
+++ b/regtests/html/threepy.py
@@ -0,0 +1,504 @@
+# Three.js HTML UI Generator
+# by Brett Hartshorn - copyright 2014
+# You may destribute this file using the "New BSD" or MIT license
+
+pythonjs.configure(javascript=True)
+from dddom import * ## provides Window3D and SelectManager
+
+
+class Editor( Window3D ):
+ def __init__(self, engine, position=None):
+ element = document.createElement( 'div' )
+ Window3D.__init__(self, element, engine.scene, engine.scene2, engine.scene3, position, [1,1,1] )
+ element.setAttribute('class', 'well')
+ self.engine = engine
+
+ b = document.createElement('button')
+ b.appendChild(document.createTextNode('run script'))
+ b.setAttribute('class', 'btn btn-inverse btn-small')
+ element.appendChild(b)
+
+ opts = ['javascript', 'python']
+ element.appendChild(document.createTextNode(' mode:'))
+ element.appendChild( self.create_select_dropdown(opts) )
+
+ element.appendChild(document.createElement('br'))
+
+ con = document.createElement('div')
+ element.appendChild(con)
+ ta = create_textarea()
+ con.appendChild( ta )
+
+ def ondrop(evt):
+ print(evt)
+ evt.preventDefault()
+ if evt.dataTransfer.files.length==0:
+ url = evt.dataTransfer.getData("text/plain")
+ self.open_iframe(url)
+ else:
+ self.handle_drop_event(evt.dataTransfer.files)
+
+ element.ondrop = ondrop.bind( self )
+ element.ondragover = lambda evt: evt.preventDefault()
+
+
+ def onclick(evt):
+ eval( ta.value )
+ b.onclick = onclick.bind(self)
+
+ def open_iframe(self, url):
+ iframe = self.create_iframe( url, self.engine.renderer3.domElement )
+ self.element.appendChild(iframe)
+
+ def _gen_material_ui(self, model):
+ print(model.material)
+ div = document.createElement('div')
+
+ ## Material.js
+ faceopts = ['FrontSide', 'BackSide', 'DoubleSide']
+ div.appendChild(document.createTextNode(' face direction:'))
+ dd = self.create_select_dropdown(faceopts)
+ div.appendChild( dd )
+ div.appendChild( document.createElement('br') )
+ def onchange(evt):
+ opt = faceopts[this.selectedIndex]
+ print(opt)
+ model.material.side = eval('THREE.'+opt)
+ dd.onchange = onchange
+
+ blendopts = ['NormalBlending', 'AdditiveBlending', 'SubtractiveBlending', 'NoBlending']
+ div.appendChild(document.createTextNode(' blending:'))
+ dd = self.create_select_dropdown(blendopts)
+ div.appendChild( dd )
+ div.appendChild( document.createElement('br') )
+ def change_blending(evt):
+ opt = blendopts[this.selectedIndex]
+ print(opt)
+ model.material.blending = eval('THREE.'+opt)
+ dd.onchange = change_blending
+
+ def change_wireframe(evt): model.material.wireframe = this.checked
+ div.appendChild(document.createTextNode(' wireframe:'))
+ checkbox = create_checkbox( model.material.wireframe, onchange=change_wireframe )
+ div.appendChild( checkbox )
+
+ def change_wireframe_width(val): model.material.wireframeLinewidth = val * 10
+ slider = create_slider( model.material.wireframeLinewidth*0.1, onchange=change_wireframe_width )
+ div.appendChild( slider )
+
+ div.appendChild( document.createElement('br') )
+
+
+ def change_opacity(val):
+ model.material.opacity = val
+ slider = create_slider( model.material.opacity, onchange=change_opacity )
+ div.appendChild( document.createTextNode('opacity:') )
+ div.appendChild( slider )
+
+ div.appendChild( document.createElement('br') )
+
+
+ well = document.createElement('div')
+ well.setAttribute('class', 'well')
+ div.appendChild( well )
+
+ ## MeshBasicMaterial.js
+ well.appendChild(document.createTextNode(' diffuse:'))
+ input = document.createElement('input')
+ input.setAttribute('type', 'color')
+ input.style.width=64; input.style.height=32
+ well.appendChild( input )
+ def change_diffuse(evt):
+ hex = int( '0x'+this.value[1:] )
+ model.material.color.setHex( hex )
+ print(model.material.color)
+ ## oninput fails, can only get update after use has picked color
+ input.onchange = change_diffuse
+
+
+ ## MeshPhongMaterial.js
+ if hasattr(model.material, 'ambient'):
+ well.appendChild(document.createTextNode(' ambient:'))
+ input = document.createElement('input')
+ input.setAttribute('type', 'color')
+ input.style.width=64; input.style.height=32
+ well.appendChild( input )
+ def change_ambient(evt):
+ hex = int( '0x'+this.value[1:] )
+ model.material.ambient.setHex( hex )
+ print(model.material.ambient)
+ input.onchange = change_ambient
+
+ if hasattr(model.material, 'emissive'):
+ well.appendChild(document.createTextNode(' emissive:'))
+ input = document.createElement('input')
+ input.setAttribute('type', 'color')
+ input.style.width=64; input.style.height=32
+ well.appendChild( input )
+ def change_emissive(evt):
+ hex = int( '0x'+this.value[1:] )
+ model.material.emissive.setHex( hex )
+ print(model.material.emissive)
+ input.onchange = change_emissive
+
+ if hasattr(model.material, 'specular'):
+ #div.appendChild( document.createElement('br') )
+
+ div.appendChild(document.createTextNode(' specular:'))
+
+ def change_shininess(val):
+ model.material.shininess = val * 100
+ slider = create_slider( model.material.shininess*0.01, onchange=change_shininess )
+ #div.appendChild( document.createTextNode(' shininess:') )
+ div.appendChild( slider )
+
+ input = document.createElement('input')
+ input.setAttribute('type', 'color')
+ input.style.width=64; input.style.height=32
+ div.appendChild( input )
+ def change_specular(evt):
+ hex = int( '0x'+this.value[1:] )
+ model.material.specular.setHex( hex )
+ print(model.material.specular)
+ input.onchange = change_specular
+
+
+
+ return div
+
+
+ def _gen_ui_single(self, model):
+ div = document.createElement('div')
+ div.setAttribute('class', 'well')
+ #h3 = document.createElement('h3')
+ #h3.appendChild( document.createTextNode(model.name) )
+ #div.appendChild( h3 )
+
+ div.appendChild( document.createTextNode(' position:') )
+
+ def set_pos_x(evt): model.position.x = this.value
+ input = create_float_input( model.position.x, onchange=set_pos_x)
+ div.appendChild( input )
+
+ def set_pos_y(evt): model.position.y = this.value
+ input = create_float_input( model.position.y, onchange=set_pos_y)
+ div.appendChild( input )
+
+ def set_pos_z(evt): model.position.z = this.value
+ input = create_float_input( model.position.z, onchange=set_pos_z)
+ div.appendChild( input )
+
+ div.appendChild( document.createElement('br') )
+
+ div.appendChild( document.createTextNode(' rotation:') )
+
+ def set_rot_x(evt): model.rotation.x = this.value
+ input = create_float_input( model.rotation.x, onchange=set_rot_x)
+ div.appendChild( input )
+
+ def set_rot_y(evt): model.rotation.y = this.value
+ input = create_float_input( model.rotation.y, onchange=set_rot_y)
+ div.appendChild( input )
+
+ def set_rot_z(evt): model.rotation.z = this.value
+ input = create_float_input( model.rotation.z, onchange=set_rot_z)
+ div.appendChild( input )
+
+ div.appendChild( document.createElement('br') )
+
+ div.appendChild( document.createTextNode(' scale:') )
+
+ def set_scale_x(evt): model.scale.x = this.value
+ input = create_float_input( model.scale.x, onchange=set_scale_x)
+ div.appendChild( input )
+
+ def set_scale_y(evt): model.scale.y = this.value
+ input = create_float_input( model.scale.y, onchange=set_scale_y)
+ div.appendChild( input )
+
+ def set_scale_z(evt): model.scale.z = this.value
+ input = create_float_input( model.scale.z, onchange=set_scale_z)
+ div.appendChild( input )
+
+
+
+
+ if hasattr(model, 'material'): ## could be THREE.Mesh or THREE.SkinnedMesh
+ ui = self._gen_material_ui(model)
+ div.appendChild( ui )
+ return div
+
+ def _gen_ui_multi(self, arr):
+ menu = self.create_tab_menu()
+ for i,model in enumerate(arr):
+ page = menu.add_tab( model.name )
+ div = self._gen_ui_single( model )
+ page.appendChild( div )
+ return menu.root
+
+ def _gen_ui(self, o):
+
+ if instanceof(o, Array):
+ return self._gen_ui_multi(o)
+ elif instanceof(o, THREE.Object3D):
+ return self._gen_ui_single(o)
+ else:
+ raise RuntimeError('can not generate ui for type:'+o)
+
+
+
+ def handle_drop_event(self, files):
+ self.engine.pointlight1.position.copy( self.position )
+ self.engine.pointlight1.position.z += 40
+ self.engine.gizmo.attach( self.right_bar )
+
+ images = []
+ videos = []
+ for file in files:
+ ## note: `file.path` is only available in NodeWebkit,
+ ## for simple testing we will fake it here.
+ file.path = '/home/brett/Desktop/'+file.name
+
+ if file.path.endswith('.dae'):
+ loader = new THREE.ColladaLoader();
+ loader.options.convertUpAxis = true;
+ #def on_load(collada):
+ # print(collada)
+ # element3D.root.add( collada.scene )
+ #loader.load( 'http://localhost:8000'+file.path, on_load )
+
+ def onload(evt):
+ parser = new DOMParser()
+ collada = loader.parse( parser.parseFromString(evt.target.result, "application/xml") )
+ print(collada.scene)
+ collada.scene.scale.set(0.25, 0.25, 0.25)
+ collada.scene.position.set(0, -100, 200)
+ self.root.add( collada.scene )
+ self.collada = collada.scene
+
+ self.element.appendChild( self._gen_ui(collada.scene.children) )
+
+ reader = new FileReader()
+ reader.onload = onload.bind(self)
+ reader.readAsText( file )
+
+ elif file.path.endswith('.html'):
+ iframe = element3D.create_iframe( file.path, renderer3.domElement )
+ self.element.appendChild(iframe)
+
+ elif file.path.endswith('.css'):
+ print( 'TODO css' )
+ elif file.path.endswith('.js'):
+ print( 'TODO js' )
+ elif file.path.endswith('.jpg') or file.path.endswith('.png') or file.path.endswith('.gif'):
+
+ li = document.createElement('li')
+ images.append(li)
+ img = document.createElement('img')
+ img.setAttribute('src', file.path)
+ img.setAttribute('class', 'well img-rounded')
+ li.appendChild( img )
+
+
+ elif file.path.endswith('.mp4'):
+ li = document.createElement('li')
+ video = self.create_video( mp4=file.path )
+ li.appendChild( video )
+ videos.append( li )
+
+ ## note, nodewebkit is missing libffmpegsumo, then it only plays ogv videos
+ elif file.path.endswith('.ogv'):
+ #li = document.createElement('li')
+ video = self.create_video( ogv=file.path )
+ self.element.appendChild(video)
+ #li.appendChild( video )
+ #videos.append( li )
+
+ elif file.path.endswith('.py'):
+ def on_load(event):
+ contents = event.target.result
+ py_body_editor.setValue( contents )
+
+ Reader.onload = on_load
+ Reader.readAsText( file )
+
+ if images:
+ print('loading images')
+ ul = document.createElement('ul')
+ self.element.appendChild(ul)
+ for li in images:
+ ul.appendChild(li)
+
+ if videos:
+ print('loading videos')
+ ul = document.createElement('ul')
+ self.element.appendChild(ul)
+ for li in videos:
+ ul.appendChild(li)
+
+
+
+class Engine:
+ def Editor(self, **kw):
+ e = Editor(self, **kw)
+ self.windows.append( e )
+ return e
+
+
+ def __init__(self):
+ self.windows = []
+
+ SCREEN_WIDTH = window.innerWidth
+ SCREEN_HEIGHT = window.innerHeight
+
+ self.camera = camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
+ camera.position.set( 200, 250, 800 );
+
+ self._selectman = SelectManager(self.camera)
+
+ self.controls = controls = new THREE.TrackballControls( camera );
+ camera.smooth_target = controls.target.clone()
+ camera.smooth_target.y = 300
+
+ controls.rotateSpeed = 1.0;
+ controls.zoomSpeed = 1.2;
+ controls.panSpeed = 0.8;
+
+ controls.noZoom = false;
+ controls.noPan = false;
+
+ controls.staticMoving = false;
+ controls.dynamicDampingFactor = 0.3;
+
+ controls.keys = [ 65, 83, 68 ];
+
+ self.scene = scene = new THREE.Scene();
+ self.scene3 = scene3 = new THREE.Scene();
+
+
+ self.renderer = renderer = new THREE.WebGLRenderer(alpha=True);
+ renderer.shadowMapEnabled = true
+ renderer.shadowMapType = THREE.PCFSoftShadowMap
+ renderer.shadowMapSoft = true
+
+
+ renderer.setSize( window.innerWidth, window.innerHeight );
+ renderer.domElement.style.position = 'absolute';
+ renderer.domElement.style.top = 0;
+ renderer.domElement.style.zIndex = 1;
+
+ self.gizmo = new THREE.TransformControls( camera, renderer.domElement )
+ scene.add( self.gizmo )
+
+ self.spotlight = light = new(
+ THREE.SpotLight( 0xffffff, 1, 0, Math.PI / 2, 1 )
+ )
+ light.position.set( 0, 1400, 400 )
+ light.target.position.set( 0, 0, 0 )
+
+ light.castShadow = True
+ light.shadowCameraNear = 400
+ light.shadowCameraFar = 1900
+ light.shadowCameraFov = 64
+ light.shadowCameraVisible = True
+
+ light.shadowBias = 0.0001
+ light.shadowDarkness = 0.4
+
+ light.shadowMapWidth = 512
+ light.shadowMapHeight = 512
+
+ scene.add( light );
+
+ self.pointlight1 = pointlight = new( THREE.PointLight(0xffffff, 2, 500) )
+ pointlight.position.set( 10, 100, 300 )
+ scene.add( pointlight )
+
+ self.pointlight2 = pointlight = new( THREE.PointLight(0xffffff, 2, 500) )
+ pointlight.position.set( -10, -100, 200 )
+ scene.add( pointlight )
+
+ renderer.sortObjects = false
+ renderer.autoClear = false
+
+ renderTarget = new(
+ THREE.WebGLRenderTarget(
+ SCREEN_WIDTH,
+ SCREEN_HEIGHT,
+ minFilter = THREE.LinearFilter,
+ magFilter = THREE.LinearFilter,
+ format = THREE.RGBAFormat, ## RGBA format is required to composite over css3d render
+ stencilBuffer = false
+ )
+ )
+
+
+ hblur = new(THREE.ShaderPass( THREE.HorizontalTiltShiftShader ))
+ vblur = new(THREE.ShaderPass( THREE.VerticalTiltShiftShader ))
+
+ bluriness = 1.7;
+ hblur.uniforms[ 'h' ].value = bluriness / SCREEN_WIDTH;
+ vblur.uniforms[ 'v' ].value = bluriness / SCREEN_HEIGHT;
+
+ hblur.uniforms[ 'r' ].value = 0.1
+ vblur.uniforms[ 'r' ].value = 0.1
+
+
+ self.composer = composer = new(THREE.EffectComposer( renderer, renderTarget ))
+
+ renderModel = new(THREE.RenderPass( scene, camera ))
+
+ vblur.renderToScreen = true;
+ composer.addPass( renderModel );
+ composer.addPass( hblur );
+ composer.addPass( vblur );
+
+
+ self.scene2 = scene2 = new THREE.Scene();
+
+
+ self.renderer2 = renderer2 = new THREE.CSS3DRenderer();
+ renderer2.setSize( window.innerWidth, window.innerHeight );
+ renderer2.domElement.style.position = 'absolute';
+ renderer2.domElement.style.top = 0;
+ renderer2.domElement.style.zIndex = 0;
+ document.body.appendChild( renderer2.domElement );
+
+ self.renderer3 = renderer3 = new THREE.CSS3DRenderer();
+ renderer3.setSize( window.innerWidth, window.innerHeight );
+ renderer3.domElement.style.position = 'absolute';
+ renderer3.domElement.style.top = 0;
+ renderer3.domElement.style.opacity = 0.1;
+ renderer3.domElement.style.zIndex=4;
+
+ document.body.appendChild( renderer2.domElement );
+ document.body.appendChild( renderer.domElement );
+ document.body.appendChild( renderer3.domElement );
+
+
+
+ def animate(self):
+ requestAnimationFrame( self.animate.bind(self) );
+ self.gizmo.update()
+
+ d = self.camera.smooth_target.clone()
+ d.sub(self.controls.target)
+ self.controls.target.add( d.multiplyScalar(0.03) )
+ self.controls.update()
+
+ for win in self.windows: win.update()
+ self.renderer2.render( self.scene2, self.camera )
+ self.renderer.clear()
+ self.composer.render( self.scene, self.camera )
+ self.renderer3.render( self.scene3, self.camera )
+
+ def run(self):
+ #self.animate()
+ setTimeout(self.animate.bind(self), 1000)
+
+threepy = {
+ 'Engine' : lambda : Engine(),
+}
+
+#pythonjs.configure(javascript=False)
+#threepy.Editor = lambda **kw: Engine(**kw)
diff --git a/regtests/html/webgl_css3d_editor.html b/regtests/html/webgl_css3d_editor.html
new file mode 100644
index 0000000..2154bf3
--- /dev/null
+++ b/regtests/html/webgl_css3d_editor.html
@@ -0,0 +1,98 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/regtests/html/webgl_css3d_simple_editor.html b/regtests/html/webgl_css3d_simple_editor.html
index 164f948..f81cbdb 100644
--- a/regtests/html/webgl_css3d_simple_editor.html
+++ b/regtests/html/webgl_css3d_simple_editor.html
@@ -91,6 +91,7 @@
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( 200, 150, 800 );
+ selectman = SelectManager( camera )
controls = new THREE.TrackballControls( camera );
camera.smooth_target = controls.target.clone()
diff --git a/regtests/lang/builtins.py b/regtests/lang/builtins.py
new file mode 100644
index 0000000..61cbd2a
--- /dev/null
+++ b/regtests/lang/builtins.py
@@ -0,0 +1,28 @@
+'''
+builtin functions
+'''
+
+
+def main():
+ n = float('1.1')
+ TestError( n==1.1 )
+
+ n = float('NaN')
+ TestError( isNaN(n)==True )
+
+ r = round( 1.1234, 2)
+ #print(r)
+ TestError( str(r) == '1.12' )
+
+ r = round( 100.001, 2)
+ TestError( r == 100 )
+
+ i = int( 100.1 )
+ TestError( i == 100 )
+
+ r = round( 5.49 )
+ TestError( r == 5 )
+
+ r = round( 5.49, 1 )
+ TestError( r == 5.5 )
+
diff --git a/regtests/lang/equality.py b/regtests/lang/equality.py
new file mode 100644
index 0000000..f5c273d
--- /dev/null
+++ b/regtests/lang/equality.py
@@ -0,0 +1,31 @@
+'''
+==
+'''
+# https://github.com/PythonJS/PythonJS/issues/129
+
+def main():
+ TestError( 0==0 )
+ TestError( 1==1 )
+ TestError( 1.0==1 )
+ TestError('a'=='a')
+
+
+ a = [6]
+ b = [6]
+ t = a==b
+ TestError( t==True )
+
+ a = (6,)
+ b = (6,)
+ t = a==b
+ TestError( t==True )
+
+ t = ''==0 ## javascript gotcha
+ TestError( t==False )
+
+ t = [1,2]==[1,2] ## javascript gotcha
+ TestError( t==True )
+
+ t = ["1","2"] != [1,2] ## javascript gotcha
+ TestError( t==True )
+
diff --git a/regtests/lang/eval.py b/regtests/lang/eval.py
new file mode 100644
index 0000000..f68b971
--- /dev/null
+++ b/regtests/lang/eval.py
@@ -0,0 +1,12 @@
+'''
+eval
+'''
+
+def foo(): return 42
+bar = lambda: 42
+
+def main():
+ eval('a = bar()') # This one works
+ eval('b = foo()') # 'foo' is undefined in normal mode under NodeJS but works in NodeWebkit and Chrome!?
+ TestError( a==42 )
+ TestError( b==42 )
diff --git a/regtests/lang/eval_order.py b/regtests/lang/eval_order.py
new file mode 100644
index 0000000..149ec0e
--- /dev/null
+++ b/regtests/lang/eval_order.py
@@ -0,0 +1,8 @@
+'''
+evaluation order
+'''
+# https://github.com/PythonJS/PythonJS/issues/131
+
+def main():
+ a = False and (False or True)
+ TestError( a==False )
\ No newline at end of file
diff --git a/regtests/lang/inline.py b/regtests/lang/inline.py
new file mode 100644
index 0000000..7a8e3e4
--- /dev/null
+++ b/regtests/lang/inline.py
@@ -0,0 +1,5 @@
+"""inline"""
+
+def main():
+ JS("now = new Date()")
+ inline("now = new Date()")
diff --git a/regtests/lang/new.py b/regtests/lang/new.py
new file mode 100644
index 0000000..b65296b
--- /dev/null
+++ b/regtests/lang/new.py
@@ -0,0 +1,8 @@
+'''
+js new keyword
+'''
+
+def main():
+ #a = new Date() ## this also works
+ a = JS(' new Date()')
+ TestError( a.getFullYear()==2014 )
diff --git a/regtests/lang/switch.py b/regtests/lang/switch.py
new file mode 100644
index 0000000..75aca9f
--- /dev/null
+++ b/regtests/lang/switch.py
@@ -0,0 +1,17 @@
+'''
+switch case default
+'''
+
+def main():
+ x = None
+ a = 2
+ switch a:
+ case 1:
+ x = 'fail'
+ case 2:
+ x = 'ok'
+ default:
+ break
+
+ TestError( x=='ok' )
+
diff --git a/regtests/loop/for_else.py b/regtests/loop/for_else.py
new file mode 100644
index 0000000..f8c0839
--- /dev/null
+++ b/regtests/loop/for_else.py
@@ -0,0 +1,13 @@
+'''
+for else loop (DEPRECATED)
+'''
+
+def main():
+ for i in range(10):
+ if i==0:
+ break
+
+ else:
+ pass
+
+
diff --git a/regtests/loop/while_else.py b/regtests/loop/while_else.py
index 8cb012f..447050f 100644
--- a/regtests/loop/while_else.py
+++ b/regtests/loop/while_else.py
@@ -1,5 +1,5 @@
'''
-while else loop
+while else loop (DEPRECATED)
'''
def main():
diff --git a/regtests/requirejs/import_ripplelib.py b/regtests/requirejs/import_ripplelib.py
deleted file mode 100644
index 30914c3..0000000
--- a/regtests/requirejs/import_ripplelib.py
+++ /dev/null
@@ -1,37 +0,0 @@
-'''test ripple library'''
-# sudo npm install -g ripple-lib
-# https://github.com/ripple/ripple-lib/blob/develop/docs/GUIDES.md
-
-import ripple-lib as ripple
-
-def main():
- R = new(ripple.Remote(
- trusted=True,
- local_signing=True,
- local_fee=True,
- fee_cushion=1.5,
- servers = [
- {'host':'s1.ripple.com', 'port':443, 'secure':True}
- ]
- ))
- def on_connect():
- print('connected!')
- test2(R)
-
- R.connect( on_connect )
-
-def test2(R):
- req = R.request_server_info()
- def on_server_info_ok(r):
- print('info ok')
- print(r)
- def on_server_info_err(e):
- print('info err')
- print(e)
-
- req.on('success', on_server_info_ok)
- req.on('error', on_server_info_err)
-
- req.request()
-
- print('ripple-lib test complete')
diff --git a/regtests/run.py b/regtests/run.py
index d78399f..cf5ff34 100755
--- a/regtests/run.py
+++ b/regtests/run.py
@@ -142,9 +142,13 @@ def run_old_pypy_test_on(filename):
old_pypy_runnable = True
old_pypy_exe = os.path.expanduser('~/pypy-1.9/bin/pypy')
-webclgl = None
-if os.path.isfile( os.path.expanduser('~/webclgl/WebCLGL_2.0.Min.class.js') ):
- webclgl = open( os.path.expanduser('~/webclgl/WebCLGL_2.0.Min.class.js'), 'rb').read().decode('utf-8')
+webclgl = []
+if os.path.isdir( os.path.expanduser('~/webclgl') ):
+ #webclgl.append( open( os.path.expanduser('~/webclgl/WebCLGL_2.0.Min.class.js'), 'rb').read().decode('utf-8') )
+ webclgl.append( open( os.path.expanduser('~/webclgl/WebCLGLUtils.class.js'), 'rb').read().decode('utf-8') )
+ webclgl.append( open( os.path.expanduser('~/webclgl/WebCLGLBuffer.class.js'), 'rb').read().decode('utf-8') )
+ webclgl.append( open( os.path.expanduser('~/webclgl/WebCLGLKernel.class.js'), 'rb').read().decode('utf-8') )
+ webclgl.append( open( os.path.expanduser('~/webclgl/WebCLGL.class.js'), 'rb').read().decode('utf-8') )
## rhino is not run by default because it simply freezes up on maximum callstack errors
rhino_runnable = '--rhino' in sys.argv and runnable("rhino -e 'quit()'")
@@ -158,14 +162,19 @@ def run_old_pypy_test_on(filename):
## download https://github.com/rogerwang/node-webkit/releases/tag/nw-v0.9.2
## and extract to your home directory.
nodewebkit_runnable = False
-nodewebkit = os.path.expanduser('~/node-webkit-v0.9.2-linux-x64/nw')
+
+
+nodewebkit = os.path.expanduser('~/node-webkit-v0.10.0-rc1-linux-x64/nw')
if os.path.isfile( nodewebkit ): nodewebkit_runnable = True
else:
- nodewebkit = os.path.expanduser('~/node-webkit-v0.9.1-linux-x64/nw')
+ nodewebkit = os.path.expanduser('~/node-webkit-v0.9.2-linux-x64/nw')
if os.path.isfile( nodewebkit ): nodewebkit_runnable = True
else:
- nodewebkit = os.path.expanduser('~/node-webkit-v0.8.4-linux-x64/nw')
+ nodewebkit = os.path.expanduser('~/node-webkit-v0.9.1-linux-x64/nw')
if os.path.isfile( nodewebkit ): nodewebkit_runnable = True
+ else:
+ nodewebkit = os.path.expanduser('~/node-webkit-v0.8.4-linux-x64/nw')
+ if os.path.isfile( nodewebkit ): nodewebkit_runnable = True
if not show_details or '--no-nodewebkit' in sys.argv:
nodewebkit_runnable = False
@@ -184,6 +193,9 @@ def run_old_pypy_test_on(filename):
lua2js = os.path.abspath( '../external/lua.js/lua2js' )
luajs_runnable = os.path.isfile( lua2js ) and '--lua2js' in sys.argv
+go_runnable = runnable( 'go version')
+gopherjs_runnable = runnable( 'gopherjs')
+
assert rhino_runnable or node_runnable
if show_details:
@@ -360,10 +372,20 @@ def TestWarning(file, line, result, test):
print(file + ":" + str(line) + " Warning fail " + test)
"""
+_patch_header_go = """# -*- coding: utf-8 -*-
+def TestError(file:string, line:int, result:bool, test:string):
+ if result == False:
+ print(file + ":" + str(line) + " Error fail " + test)
+"""
+
+
_python_only_extra_header = """
-import threading
-threading.start_webworker = lambda f,a: threading._start_new_thread(f,a)
-threading.start_new_thread = threading._start_new_thread
+try:
+ import threading
+ threading.start_webworker = lambda f,a: threading._start_new_thread(f,a)
+ threading.start_new_thread = threading._start_new_thread
+except ImportError:
+ pass
class __faker__(object):
def __enter__(self, *args): pass
@@ -391,8 +413,14 @@ def int16(a): return int(a)
try:
import numpy
-except:
- import numpypy as numpy
+except ImportError:
+ try:
+ import numpypy as numpy
+ except ImportError:
+ pass
+
+from math import isnan as isNaN
+
"""
@@ -416,10 +444,13 @@ def patch_python(filename, dart=False, python='PYTHONJS', backend=None):
# out.append( line )
# code = '\n'.join( out )
a = [
- _patch_header,
'PYTHON="%s"'%python,
'BACKEND="%s"'%backend,
]
+ if backend == 'GO':
+ a.append(_patch_header_go)
+ else:
+ a.append(_patch_header)
if python != 'PYTHONJS':
code = typedpython.transform_source( code, strip=True )
@@ -444,7 +475,7 @@ def run_python3_test_on(filename):
-def translate_js(filename, javascript=False, dart=False, coffee=False, lua=False, luajs=False, multioutput=False, requirejs=True):
+def translate_js(filename, javascript=False, dart=False, coffee=False, lua=False, luajs=False, go=False, gopherjs=False, multioutput=False, requirejs=True):
global tmpname
tmpname = os.path.join(
tempfile.gettempdir(),
@@ -476,6 +507,9 @@ def translate_js(filename, javascript=False, dart=False, coffee=False, lua=False
]
content = '\n'.join( source )
+ elif go or gopherjs:
+ content = patch_python(filename, backend='GO')
+
else:
content = patch_python(filename)
@@ -500,6 +534,10 @@ def translate_js(filename, javascript=False, dart=False, coffee=False, lua=False
cmd.append( '--lua')
elif luajs:
cmd.append( '--luajs')
+ elif go:
+ cmd.append( '--go' )
+ elif gopherjs:
+ cmd.append( '--gopherjs' )
if not requirejs:
cmd.append( '--no-wrapper' )
@@ -672,9 +710,10 @@ def run_js_nodewebkit(content):
html = ['']
if webclgl:
- html.append('')
+ for data in webclgl:
+ html.append('')
html.append('