├── .gitignore ├── MANIFEST.in ├── README.rst ├── convert.py ├── docs ├── logo.png └── logo.svg ├── gen_builtins.py ├── make.pbj ├── pjs ├── __init__.py ├── assign.py ├── atomic.py ├── blocks.py ├── converter.py ├── data │ ├── ast_nodes.txt │ ├── js_reserved.txt │ └── pjslib.js ├── declared.py ├── errors.py ├── expression.py ├── imports.py ├── jslib │ ├── __builtin__.js │ ├── classes.js │ ├── functions.js │ └── modules.js ├── modules.py ├── old_utils.py ├── scoping.py ├── small.py ├── special.py ├── templates.py ├── templates │ ├── template.html │ ├── template.js │ └── template.ss.js └── utils.py ├── requirements.txt ├── runtest.py ├── setup.py ├── strider-custom.json └── test ├── browser ├── ext │ └── layout2.js ├── hello.py ├── jqueryui.html ├── jqueryui.js ├── jqueryui.py ├── json.py ├── json2.js └── makefile ├── js ├── jasmine-0.10.3.js └── lib.js ├── pjs ├── basic.py ├── classes.py └── tojs.py ├── py ├── StringIO.py ├── allimports.py ├── assert.py ├── assign.py ├── class.py ├── cmp.py ├── decorators.py ├── deep_inherit.py ├── dicts.py ├── errno.py ├── exceptions.py ├── funcs.py ├── globals.py ├── imports.py ├── inheritence.py ├── lcomp.py ├── loops.py ├── math.py ├── more_imports.py ├── moreclass.py ├── numbers.py ├── ops.py ├── scope.py ├── several_inherit.py ├── simple.py ├── slice.py ├── small_scope.py ├── strings.py ├── sub │ ├── __init__.py │ └── smod.py ├── toimp.py ├── undef.py └── xrange.py ├── py2js ├── basic │ ├── assign_slice.py │ ├── augassign.py │ ├── augassign2.py │ ├── binaryops.py │ ├── break.py │ ├── class.py │ ├── class2.py │ ├── closure.py │ ├── continue.py │ ├── default.py │ ├── del_array.py │ ├── del_attr.py │ ├── del_dict.py │ ├── del_global.py │ ├── del_local.py │ ├── del_slice.py │ ├── dictionary.py │ ├── dictionary2.py │ ├── docstring.py │ ├── embedding.py │ ├── fib.py │ ├── float2int.py │ ├── for_in.py │ ├── for_step.py │ ├── for_xrange.py │ ├── generator.py │ ├── globalvar.py │ ├── helloworld.py │ ├── ifs.py │ ├── keys.py │ ├── kwargs.py │ ├── kwargs2.py │ ├── lambda.py │ ├── list.py │ ├── list2.py │ ├── listcomp2.py │ ├── literals.py │ ├── logicalops.py │ ├── loops.py │ ├── multiassign.py │ ├── nestedclass.py │ ├── none.py │ ├── oo.py │ ├── oo_attributes.py │ ├── oo_diamond.py │ ├── oo_inherit.py │ ├── oo_inherit2.py │ ├── oo_inherit3.py │ ├── oo_inherit_simple.py │ ├── oo_inherit_simple2.py │ ├── oo_static_inherit.py │ ├── pass.py │ ├── print.py │ ├── raise.py │ ├── scope.py │ ├── str1.py │ ├── sumcomp.py │ ├── super.js │ ├── super.py │ ├── trueorfalse.py │ ├── try.py │ ├── tuple.py │ ├── tuple2.py │ ├── valueerror.py │ ├── vargs.py │ ├── vars.py │ ├── vars2.py │ └── while.py ├── convert_tabs_spaces.js ├── convert_tabs_spaces.py ├── errors │ ├── decorator.py │ ├── modules │ │ └── __init__.py │ └── py_collision.py ├── functions │ ├── and.js │ ├── and.py │ ├── append.py │ ├── aug.js │ ├── aug.py │ ├── bitand.js │ ├── bitand.py │ ├── bitor.js │ ├── bitor.py │ ├── bitxor.js │ ├── bitxor.py │ ├── divfloor.py │ ├── float.js │ ├── float.py │ ├── floatdiv.js │ ├── floatdiv.py │ ├── gtge.py │ ├── in.py │ ├── int.py │ ├── isinstance.js │ ├── isinstance.py │ ├── len.py │ ├── lshift.js │ ├── lshift.py │ ├── ltle.py │ ├── ne.py │ ├── or.js │ ├── or.py │ ├── pop.py │ ├── rshift.js │ ├── rshift.py │ ├── sort.py │ ├── sort23.js │ ├── sort23.py │ ├── sort_cmp.js │ ├── sort_cmp.py │ ├── str.py │ ├── ubitcomp.js │ ├── ubitcomp.py │ ├── uminus.py │ └── uplus.py ├── libraries │ └── xmlwriter.py ├── lists │ ├── extend.py │ ├── filter.py │ ├── in.py │ ├── insert.py │ ├── map.py │ ├── max.py │ ├── min.py │ ├── reduce.py │ ├── reverse.py │ ├── subclass.py │ ├── subclass2.py │ ├── subclass3.py │ ├── sum.py │ ├── sum2.py │ ├── xrange.py │ └── zip.py ├── modules │ ├── classname.py │ ├── from_import.py │ ├── import.py │ ├── import_alias.py │ ├── import_class.py │ ├── import_diamond.py │ ├── import_global.js │ ├── import_global.py │ ├── import_multi.py │ ├── imported │ │ ├── __init__.py │ │ ├── alias_classes.py │ │ ├── alias_fns.py │ │ ├── modulea.py │ │ ├── moduleb.py │ │ ├── modulec.py │ │ ├── moduled.py │ │ └── submodules │ │ │ ├── __init__.py │ │ │ └── submodulea.py │ ├── module_name.py │ ├── modules │ │ ├── __init__.py │ │ ├── diamond1.py │ │ ├── diamond2.py │ │ ├── klasses.py │ │ ├── moda.py │ │ ├── module_name.py │ │ └── submodules │ │ │ ├── __init__.py │ │ │ ├── diamondbase.py │ │ │ └── module_name.py │ └── rng.py ├── strings │ ├── count.js │ ├── count.py │ ├── find.py │ ├── join.py │ ├── lstrip0.js │ ├── lstrip0.py │ ├── lstrip1.js │ ├── lstrip1.py │ ├── replace.js │ ├── replace.py │ ├── rfind.js │ ├── rfind.py │ ├── rstrip0.js │ ├── rstrip0.py │ ├── rstrip1.js │ ├── rstrip1.py │ ├── split.js │ ├── split.py │ ├── splitlines.py │ ├── string_format_d.js │ ├── string_format_d.py │ ├── string_format_efg.js │ ├── string_format_efg.py │ ├── string_format_i.js │ ├── string_format_i.py │ ├── string_format_o.js │ ├── string_format_o.py │ ├── string_format_u.js │ ├── string_format_u.py │ ├── string_format_x.js │ ├── string_format_x.py │ ├── strip.js │ ├── strip.py │ ├── strip1.js │ ├── strip1.py │ ├── ulcase.py │ ├── ulcase1.py │ └── zipstring.py ├── test_builtins.js ├── test_compile_js.js └── test_compile_js.py └── runtests.js /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *~ 3 | *.pyc 4 | *.sess 5 | test/py/*.js 6 | build/ 7 | test/js/jasmine 8 | test/browser/css 9 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include pjs/data/* 2 | include pjs/templates/* 3 | include pjs/jslib/*.js -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | PJs 2 | === 3 | 4 | kinda like pyjamas... 5 | 6 | but shorter. quicker. cleaner. more convenient. Oh, and, *easier*. Takes care 7 | of error handling, so you don't get cryptic error messages that originate from 8 | javascript's lazyness regarding undefined variables. 9 | 10 | PJs has the goal of generating readable, usable *robust* javascript code from 11 | python code, and of providing some libraries to make web development easier. 12 | 13 | Installation 14 | ------------ 15 | 16 | I don't yet have a dist on pypi, so just clone the repo. 17 | 18 | If you want to run the tests, ``pjs`` depends on ``pbj`` so you first need to 19 | ``pip install pbj``. Pbj is a build tool that I wrote, and you can invoke it 20 | (once installed) with ``./make.pbj`` in the ``pjs`` directory. 21 | 22 | Usage 23 | ----- 24 | 25 | The ``convert.py`` should work pretty well for playing around with pjs. 26 | 27 | 28 | Recent Addtions 29 | --------------- 30 | 31 | - nested class support (full namespacing!!) 32 | - operator overloading 33 | - easy javascript embedding 34 | 35 | 36 | To make a javascript function call, prepend ``js.`` to the call (I'm reserving 37 | the name ``js``; I hope you don't mind). Any calls starting with ``window.`` 38 | are treated as javascript calls as well. The difference is that the ``js`` 39 | prefix is removed -- it is assumed that you are working with a local variable. 40 | 41 | :: 42 | 43 | jq = window.jQuery 44 | def make_tabs(id): 45 | js.jq(id).tabs() 46 | 47 | This is necessary because PJs wraps strings, tuples, lists, and dictionarys, 48 | so jQuery wouldn't know what to do with ``jq("hi")`` which 49 | otherwise would be translated to ``jq($b.str("hi"))``. As it is, the above 50 | code becomes:: 51 | 52 | _.jq = window.jQuery; 53 | _.make_tabs = $def(function $_make_tabs(id) { 54 | _.jq($b.js(id)).tabs(); 55 | }); 56 | 57 | Now that might be a bit confusing, but the important thing is that PJs knows 58 | to convert ``id`` to a javascript type (the added builtin function ``js`` converts a 59 | python object to the corresponding javascript type). 60 | 61 | If you want to avoid that kind of magic, that's fine too, but you need to 62 | convert the function arguments yourself. In python, you'd have:: 63 | 64 | jq = window.jQuery 65 | def make_tabs(id): 66 | jq(js(id)).tabs() 67 | 68 | Not much different in this example, but for more complicated expressions such 69 | as ``foo(a, b, c, d).bar(e, f)`` it's much simpler to just put a ``js.`` at 70 | the very beginning. 71 | 72 | One thing for which you must rely on magic (sorry) is subscripting; in PJs, in 73 | order to allow for __get/setitem\__ manipulation, expressions such as 74 | ``people[gender]`` are converted to ``people.__getitem__(gender)``. If you've 75 | got a javascript-style list, the magic ``js.`` prefix will preserve 76 | subscripts (and convert the argument back to javascript). So 77 | ``js.people[gender]`` becomes ``people[$b.js(gender)]``. Slicing is also 78 | handled intelligently; ``js.people[start:end]`` comes out as 79 | ``people.slice(start, end)``. 80 | 81 | 82 | 83 | 84 | 85 | Things you can't do: 86 | 87 | - python attribute magic: 88 | 89 | - __getattr__ 90 | - __setattr__ 91 | 92 | These will have major performance implications; I imagine they might be 93 | enableable via a flag -- for most programs that level of control isn't 94 | absolutely nessecary. 95 | 96 | Things you can do: 97 | 98 | - just about everything else 99 | - classes 100 | - modules! 101 | - functions 102 | - decorators 103 | 104 | - classmethod 105 | - staticmethod 106 | 107 | - operator magic; __add__, __mul__ etc. 108 | 109 | if you find a bug or something you don't like, feel free to file a ticket on 110 | github, or *even better*, fork the repo, fix your problem, and then pull 111 | request. We love pull requests. 112 | 113 | Pythonic Functions 114 | ================== 115 | 116 | Here's a bit from the top of the functions.js, which allows for pythonic function in javascript! 117 | 118 | (pjs provides the function $def for creating pythonic functions) 119 | 120 | How to use: 121 | 122 | - $def([defaults], [aflag], [kflag], fn); 123 | - defaults, aflag, and kflag are all optional, but required to be in that 124 | order to avoid ambiguity. 125 | - defaults = an associative array of key, value pairs; the key is the arg 126 | name, anf the vaule is default value. 127 | - aflag signals that the last (or second-to-last, if kflag is true) is to be 128 | populated with excess positional arguments. (in python, this is the \*args 129 | syntax). 130 | - kflag is like aflag, but for dictionary arguments, e.g. \**kwargs. 131 | - there's also checks happening the whole way, so you won't be stuck debugging 132 | another annoying undefined error. 133 | 134 | Here's an example that uses all of these: 135 | 136 | :: 137 | 138 | var foo = $def({c:null, d:10}, true, true, function foo(a, b, c, d, args, kwargs) { 139 | // only a and b are required, and excess positional and dictionary 140 | // arguments will be captured. 141 | console.log([a, b, c, d, args, kwargs]); 142 | }); 143 | 144 | // and in use... 145 | 146 | > foo(1); 147 | TypeError: foo requires 2 arguments (1 given) 148 | > foo(1,2); 149 | [1, 2, null, 10, [], {}] 150 | > foo(1,2,3); 151 | [1, 2, 3, 10, [], {}] 152 | > foo(1,2,3,4,5,6,7,8,9); 153 | [1, 2, 3, 4, [5, 6, 7, 8, 9], {}] 154 | 155 | now some some real magic; dictionary arguments: 156 | 157 | > foo.args([1], {'b':9, 'd':20, 'man':'hatten'} 158 | [1, 9, null, 20, [], {'man': 'hatten'}] 159 | 160 | !! that looks like python !! well...almost. but it's lovely :) 161 | 162 | python-style classes are also implemented, with full namespacing! 163 | -------------------------------------------------------------------------------- /convert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | import optparse 4 | 5 | import pjs 6 | 7 | def options(): 8 | p = optparse.OptionParser('usage: build.py [options] main_script.py [output-file]') 9 | p.add_option('-d','--debug', help='set the debug level', type='int', default=0, 10 | dest='debug') 11 | p.add_option('-i','--ignore-import-errors', dest='ignore_import_errors', default=False, 12 | action='store_true', help='Ignore import errors; only do this if you expect to handle ImportErrors in your program') 13 | p.add_option('-r', '--rhino', dest='rhino', action='store_true', 14 | help='Compile for Rhino (use load() for pjs library)') 15 | p.add_option('--html', dest='html', action='store_true', 16 | help='Override file extension; output html (default output format is .js)') 17 | p.add_option('-l', '--lib-dir', dest='lib_dir', default='./build', 18 | help='The directory (relative to output file directory) where pjslib.js\ 19 | can be found') 20 | 21 | opts, pos = p.parse_args() 22 | if len(pos) not in (1, 2): 23 | p.print_help() 24 | sys.exit(1) 25 | return pos, opts 26 | 27 | if __name__ == '__main__': 28 | pos, opts = options() 29 | if opts.rhino and opts.html: 30 | print 'cannot specify both --rhino and --html' 31 | 32 | fmt = 'js' 33 | if opts.rhino: 34 | fmt = 'js' 35 | elif opts.html: 36 | fmt = 'html' 37 | elif len(pos) == 2: 38 | fmt = pos[1].split('.')[-1] 39 | 40 | if fmt not in ('html', 'js'): 41 | print 'Invalid format "%s". Defaulting to js' % fmt 42 | fmt = 'js' 43 | 44 | text = pjs.compile(pos[0], fmt, **vars(opts)) 45 | if len(pos) == 2: 46 | open(pos[1], 'w').write(text) 47 | else: 48 | print text 49 | 50 | # vim: et sw=4 sts=4 51 | -------------------------------------------------------------------------------- /docs/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/docs/logo.png -------------------------------------------------------------------------------- /gen_builtins.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env pyth/on 2 | 3 | for k,v in __builtins__.__dict__.iteritems(): 4 | try: 5 | if issubclass(v, Exception): 6 | continue 7 | except:pass 8 | print '__module__.%s = __not_implemented__("%s");' % (k, k) 9 | 10 | 11 | # vim: et sw=4 sts=4 12 | -------------------------------------------------------------------------------- /make.pbj: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from pbj import Builder, cmd, PBJFailed 4 | import os 5 | import glob 6 | import re 7 | import traceback 8 | 9 | import pjs 10 | from pjs import PJsNotImplemented 11 | 12 | build = Builder('PJs') 13 | 14 | def get_lineno(text): 15 | def meta(match): 16 | lno = len(text[:match.start()].split('\n')) 17 | return match.group()[:-1] + ' // %d :builtin:\n' % lno 18 | return meta 19 | 20 | @build.file('pjs/data/pjslib.js', depends='pjs/jslib/*.js') 21 | def lib(): 22 | print 'Javascript Tests' 23 | files = ('pjs/jslib/functions.js', 'pjs/jslib/classes.js', 'pjs/jslib/modules.js', 'pjs/jslib/__builtin__.js') 24 | text = '\n'.join(open(fname).read() for fname in files) 25 | text = re.sub('function(\s+[$\w-]+)?\s*\(([$\w_]+,\s*)*[$\w_]*\s*\)\s*{\s*\n', get_lineno(text), text) 26 | open('pjs/data/pjslib.js', 'w').write(text) 27 | 28 | build.cmd('jstest', ('rhino', 'test/runtests.js'), depends='@lib', always=True) 29 | 30 | build.clean('build', 'test/py/*.js') 31 | 32 | @build.target(depends='@lib', always=True, completion=glob.glob('test/pjs/*.py')) 33 | def pjstest(fname='test/pjs/*.py'): 34 | print 'PJs Tests' 35 | files = glob.glob(fname) 36 | for fname in files: 37 | justjs(fname) 38 | 39 | @build.target(depends='@lib', always=True, completion=glob.glob('test/py/*.py')) 40 | def pytest(one=None, keep=False): 41 | print 'Python Tests' 42 | if one is not None: 43 | files = [one] 44 | else: 45 | files = glob.glob('test/py/*.py') 46 | for fname in files: 47 | compare(fname, keep=keep) 48 | 49 | py2js_files = glob.glob('test/py2js/*.py') + glob.glob('test/py2js/*/*.py') + glob.glob('test/py2js/*/*/*.py') 50 | 51 | @build.target(depends='@lib', always=True, completion=py2js_files) 52 | def py2jstest(one=None, full=True): 53 | if one is not None: 54 | if os.path.isdir(one): 55 | files = glob.glob(os.path.join(one, '*.py')) 56 | else: 57 | files = [one] 58 | else: 59 | files = py2js_files 60 | for fname in files: 61 | compare(fname, full) 62 | 63 | def justjs(fname): 64 | jsname = fname.replace('.py', '.js') 65 | 66 | try: 67 | open(jsname, 'w').write(pjs.compile(fname, 'js', lib_dir='pjs/data', rhino=True)) 68 | except PJsNotImplemented, e: 69 | print 'XFAIL %s :: %s' % (fname, e) 70 | return 71 | except Exception, e: 72 | print 'FAILED %s :: conversion error:' % fname 73 | print traceback.format_exc() 74 | return 75 | 76 | jo, je = cmd('rhino %s' % jsname, shell=True) 77 | if je: 78 | print 'FAILED %s :: javascript error:\n%s' % (fname, je) 79 | print jo 80 | return 81 | print 'PASSED %s' % fname 82 | os.unlink(jsname) 83 | 84 | def compare(fname, full=False, keep=False): 85 | jsname = fname.replace('.py', '.js') 86 | o,e = cmd('python', os.path.basename(fname), cwd = os.path.dirname(fname)) 87 | if e: 88 | print 'FAILED %s :: python error:\n%s' % (fname, e) 89 | return 90 | try: 91 | open(jsname, 'w').write(pjs.compile(fname, 'js', lib_dir='pjs/data', rhino=True)) 92 | except (PJsNotImplemented, SyntaxError), e: 93 | print 'XFAIL %s :: %s' % (fname, e) 94 | return 95 | except Exception, e: 96 | print 'FAILED %s :: conversion error:' % fname 97 | print traceback.format_exc() 98 | return 99 | 100 | jo, je = cmd('rhino %s' % jsname, shell=True) 101 | if je: 102 | if 'NotImplementedError' in je: 103 | print 'XFAIL :: not implemented :: ', je 104 | return 105 | print 'FAILED %s :: javascript error:\n%s' % (fname, je) 106 | print jo 107 | return 108 | if o != jo: 109 | print 'FAILED %s :: different output:\n' % fname 110 | if full: 111 | print o 112 | print '-'*20 113 | print jo 114 | print '-'*20 115 | print diff(o, jo) 116 | return 117 | print 'PASSED %s' % fname 118 | if not keep: 119 | os.unlink(jsname) 120 | 121 | @build.target(depends=('@jstest', '@pytest', '@pjstest'), always=True) 122 | def test(): 123 | pass 124 | 125 | from tempfile import NamedTemporaryFile as ntf 126 | 127 | def diff(a, b): 128 | af = ntf(delete=False) 129 | af.write(a) 130 | af.close() 131 | bf = ntf(delete=False) 132 | bf.write(b) 133 | bf.close() 134 | o, e = cmd('diff', af.name, bf.name) 135 | os.unlink(af.name) 136 | os.unlink(bf.name) 137 | return o 138 | 139 | if __name__ == '__main__': 140 | build.run() 141 | 142 | 143 | # vim: et sw=4 sts=4 144 | -------------------------------------------------------------------------------- /pjs/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | import converter 3 | from converter import PJsNotImplemented 4 | 5 | import utils 6 | 7 | import assign 8 | import atomic 9 | import blocks 10 | import declared 11 | import expression 12 | import imports 13 | import scoping 14 | import small 15 | import special 16 | 17 | import os 18 | import sys 19 | localfile = lambda *a: os.path.join(os.path.dirname(__file__), *a) 20 | 21 | html_out = open(localfile('templates/template.html')).read() 22 | js_out = open(localfile('templates/template.js')).read() 23 | rhino_out = open(localfile('templates/template.ss.js')).read() 24 | 25 | def compile(filename, format, **options): 26 | conv = converter.Converter(filename, **options) 27 | modules = conv.parse() 28 | 29 | text = '\n'.join(modules[fname] for fname in sorted(modules.keys())) 30 | lib = os.path.join(options.get('lib_dir', '.'), 'pjslib.js') 31 | data = {'file':os.path.abspath(filename), 'text':text, 'lib':lib} 32 | data['path'] = sys.path 33 | 34 | if options.get('rhino', False): 35 | template = rhino_out 36 | elif options.get('html', False): 37 | template = html_out 38 | else: 39 | template = js_out 40 | 41 | return template % data 42 | 43 | -------------------------------------------------------------------------------- /pjs/assign.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts, PJsNotImplemented 3 | import utils 4 | 5 | @converts(ast.Assign) 6 | def assign(conv, node, scope): 7 | rest = '' 8 | target = node.targets[0] 9 | if isinstance(target, ast.Tuple): 10 | left = 'var __pjs_tmp' 11 | rest = utils.deepleft(conv, target, [], scope) 12 | elif isinstance(target, ast.Subscript): 13 | left = conv.get_converter(target)(conv, target, scope, True) 14 | if left.endswith(' '): 15 | return left + conv.convert_node(node.value, scope) + ');\n' 16 | elif isinstance(target, ast.Name): 17 | left = utils.lhand_assign(target.id, scope) 18 | else: 19 | left = conv.convert_node(target, scope) 20 | 21 | for targ in node.targets[1:]: 22 | var = left 23 | if var.startswith('var '): 24 | var = var[len('var '):] 25 | if isinstance(targ, ast.Tuple): 26 | rest += utils.deepleft(conv, targ, [], scope, var) 27 | elif isinstance(targ, ast.Name): 28 | mr = utils.lhand_assign(targ.id, scope) 29 | rest += mr + ' = ' + var + ';\n' 30 | else: 31 | rest += '%s = %s;\n' % (conv.convert_node(targ, scope), var) 32 | js = conv.convert_node(node.value, scope) 33 | line = '%s = %s;\n' % (left, js) 34 | return line + rest 35 | 36 | @converts(ast.AugAssign) 37 | def _augassign(conv, node, scope): 38 | tpl = '%s = $b.%s(%s, %s);\n' 39 | op = node.op.__class__.__name__.lower() 40 | ljs = conv.convert_node(node.target, scope) 41 | rjs = conv.convert_node(node.value, scope) 42 | if isinstance(node.target, ast.Subscript): 43 | left = conv.get_converter(node.target)(conv, node.target, scope, True) 44 | if left.endswith(' '): 45 | return left + conv.convert_node(node.value, scope) + ');\n' 46 | elif isinstance(node.target, ast.Name): 47 | left = utils.lhand_assign(node.target.id, scope) 48 | else: 49 | left = conv.convert_node(node.target, scope) 50 | return tpl % (left, op, ljs, rjs) 51 | 52 | @converts(ast.AugLoad) 53 | def _augload(node, scope): 54 | raise PJsNotImplemented('i don\'t know what "AugLoad" is. if you see this, please email jared@jaredforsyth.com w/ code...') 55 | 56 | @converts(ast.AugStore) 57 | def _augstore(node, scope): 58 | raise PJsNotImplemented('i don\'t know what "AugStore" is. if you see this, please email jared@jaredforsyth.com w/ code...') 59 | 60 | # vim: et sw=4 sts=4 61 | -------------------------------------------------------------------------------- /pjs/atomic.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts, PJsNotImplemented 3 | import utils 4 | 5 | def atomic(fn): 6 | def meta(conv, node, scope, *args, **kwargs): 7 | aflag = False 8 | if not scope.atomic: 9 | aflag = True 10 | scope.atomic = True 11 | text = fn(conv, node, scope, *args, **kwargs) 12 | if aflag: 13 | scope.atomic = False 14 | if text.startswith('js.'): 15 | text = text[3:] 16 | return text 17 | return meta 18 | 19 | @converts(ast.Attribute) 20 | @atomic 21 | def attribute(conv, node, scope): 22 | if node.attr in utils.reserved_words: 23 | raise SyntaxError("Sorry, '%s' is a reserved word in javascript." % node.attr) 24 | js = conv.convert_node(node.value, scope) 25 | if js == 'js': 26 | return 'js.%s' % (utils.resolve(node.attr, scope)) 27 | return "%s.%s" % (js, node.attr) 28 | 29 | @converts(ast.Call) 30 | @atomic 31 | def call(conv, node, scope): 32 | if isinstance(node.func, ast.Name) and node.func.id == 'new': 33 | if node.starargs or node.kwargs or node.keywords or len(node.args) != 1: 34 | raise SyntaxError('the "new" function is reserved, and takes one argument') 35 | return 'new ' + conv.convert_node(node.args[0], scope) 36 | 37 | left = conv.convert_node(node.func, scope) 38 | raw_js = left.startswith('js.') or left.startswith('window.') 39 | 40 | if left == 'js': # e.g. js(some_tuff) 41 | left = '$b.js' 42 | 43 | if node.starargs or node.kwargs or node.keywords: 44 | if raw_js: 45 | raise SyntaxError('cannot use *args, **kwds, or a=b in javascript functions') 46 | right = call_pythonic(conv, node, scope) 47 | else: 48 | right = call_args(conv, node, scope, raw_js) 49 | return left + right 50 | 51 | def call_args(conv, node, scope, raw_js=False): 52 | args = [] 53 | for n in node.args: 54 | js = conv.convert_node(n, scope) 55 | if js.startswith('js.'): 56 | js = js[3:] 57 | if raw_js: 58 | ## in a javascript call 59 | js = '$b.js(%s)' % js 60 | args.append(js) 61 | return '(%s)' % ', '.join(args) 62 | 63 | def call_pythonic(conv, node, scope): 64 | args = call_pythonic_args(conv, node, scope) 65 | kwds = call_pythonic_keywords(conv, node, scope) 66 | return '.args(%s, %s)' % (args, kwds) 67 | 68 | def call_pythonic_args(conv, node, scope): 69 | if node.args: 70 | args = [] 71 | for n in node.args: 72 | args.append(conv.convert_node(n, scope)) 73 | ret = '$b.tuple([%s])' % ', '.join(args) 74 | if node.starargs: 75 | ret += '.__add__($b.tuple(%s))' % conv.convert_node(node.starargs, scope) 76 | return ret 77 | 78 | elif node.starargs: 79 | return conv.convert_node(node.starargs, scope) 80 | 81 | else: 82 | return '$b.tuple([])' 83 | 84 | def call_pythonic_keywords(conv, node, scope): 85 | if node.keywords: 86 | kargs = [] 87 | for kw in node.keywords: 88 | kargs.append("'%s': %s" % (kw.arg, conv.convert_node(kw.value, scope))) 89 | kwds = '{%s}' % ', '.join(kargs) 90 | if node.kwargs: 91 | ## duplicates get overridden by kwargs 92 | kwds += '.extend(%s)' % conv.convert_node(node.kwargs, scope) 93 | return kwds 94 | 95 | elif node.kwargs: 96 | return conv.convert_node(node.kwargs, scope) 97 | 98 | else: 99 | return '{}' 100 | 101 | @converts(ast.Subscript) 102 | @atomic 103 | def subscript(conv, node, scope, onleft=False): 104 | left = conv.convert_node(node.value, scope) 105 | raw_js = left.startswith('js.') or left.startswith('window.') 106 | 107 | if isinstance(node.slice, ast.Slice) and node.slice.step is None: 108 | if raw_js: 109 | if onleft: 110 | raise SyntaxError('Javascript doesn\'t support slice assignment') 111 | return slice_js_nostep(conv, left, node, scope) 112 | 113 | if node.slice.upper is not None: 114 | return slice_nostep(conv, left, node, scope, onleft) 115 | 116 | idex = conv.convert_node(node.slice, scope) 117 | 118 | if raw_js: 119 | if isinstance(node.slice, ast.Slice): 120 | raise SyntaxError('no steps in javascript slices') 121 | # TODO check idex for literal 122 | return '%s[$b.js(%s)]' % (left, idex) 123 | 124 | if onleft == 'delete': 125 | return '%s.__delitem__(%s)' % (left, idex) 126 | elif onleft: 127 | return '%s.__setitem__(%s, ' % (left, idex) 128 | return '%s.__getitem__(%s)' % (left, idex) 129 | 130 | def slice_js_nostep(conv, left, node, scope): 131 | if node.slice.lower: 132 | lower = conv.convert_node(node.slice.lower, scope) 133 | else: 134 | lower = 0 135 | if node.slice.upper is None: 136 | return '%s.slice(%s)' % (left, lower) 137 | else: 138 | upper = conv.convert_node(node.slice.upper, scope) 139 | return '%s.slice(%s, %s)' % (left, lower, upper) 140 | 141 | def slice_nostep(conv, left, node, scope, onleft): 142 | upper = conv.convert_node(node.slice.upper, scope) 143 | if node.slice.lower: 144 | lower = conv.convert_node(node.slice.lower, scope) 145 | else: 146 | lower = 0 147 | if onleft == 'delete': 148 | return '%s.__delslice__(%s, %s)' % (left, lower, upper) 149 | elif onleft: 150 | return '%s.__setslice__(%s, %s, ' % (left, lower, upper) 151 | return '%s.__getslice__(%s, %s)' % (left, lower, upper) 152 | 153 | # vim: et sw=4 sts=4 154 | -------------------------------------------------------------------------------- /pjs/blocks.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts, PJsNotImplemented 3 | import utils 4 | 5 | WHILE_TPL = '''\ 6 | while ($b.bool(%s) === true) { 7 | %s 8 | } 9 | ''' 10 | 11 | @converts(ast.While) 12 | def _while(conv, node, scope): 13 | if node.orelse: 14 | raise PJsNotImplemented('while...else not implemented') 15 | test = conv.convert_node(node.test, scope) 16 | body = conv.convert_block(node.body, scope) 17 | return WHILE_TPL % (test, body) 18 | 19 | FOR_TPL = '''\ 20 | var %s = $b.foriter(%s); 21 | while (%s.trynext()) { 22 | %s 23 | %s 24 | } 25 | ''' 26 | 27 | @converts(ast.For) 28 | def _for(conv, node, scope): 29 | ible = conv.convert_node(node.iter, scope) 30 | temp_iter = conv.get_temp('iter') 31 | if isinstance(node.target, ast.Name): 32 | targ = utils.lhand_assign(node.target.id, scope) 33 | assign = '%s = %s.value;\n' % (targ, temp_iter) 34 | else: 35 | assign = utils.deepleft(conv, node.target, [], scope, '%s.value' % temp_iter).replace('\n', '\n ') 36 | 37 | body = conv.convert_block(node.body, scope) 38 | 39 | conv.kill_temp('iter') 40 | return FOR_TPL % (temp_iter, ible, temp_iter, assign, body) 41 | 42 | LCOMP_TMP = '''\ 43 | $b.%(ctype)scomp(%(iters)s, function (%(names)s) {return %(elt)s;}, %(ifs)s)''' 44 | 45 | @converts(ast.ListComp) 46 | def listComp(conv, node, scope): 47 | return do_comp(conv, node, scope, 'list') 48 | 49 | @converts(ast.GeneratorExp) 50 | def genComp(conv, node, scope): 51 | return do_comp(conv, node, scope, 'gen') 52 | 53 | def do_comp(conv, node, scope, ctype): 54 | iters = [] 55 | names = [] 56 | ifs = [] 57 | dct = {'ctype': ctype} 58 | 59 | for gen in node.generators: 60 | if len(gen.ifs) > 1: 61 | raise PJsNotImplemented('Why would a ListComp generator have multiple ifs? please report this...') 62 | if not isinstance(gen.target, ast.Name): 63 | raise PJsNotImplemented('Tuple listcomp targets not supported') 64 | name = gen.target.id 65 | if not gen.ifs: 66 | ifs.append('null') 67 | else: 68 | fn_scope = scope.copy() 69 | fn_scope.locals.append(name) 70 | ifs.append('function (%s) { return %s; }' % (name, conv.convert_node(gen.ifs[0], fn_scope))) 71 | iters.append(conv.convert_node(gen.iter, scope)) 72 | names.append(name) 73 | 74 | elt_scope = scope.copy() 75 | elt_scope.locals += names 76 | dct['elt'] = conv.convert_node(node.elt, elt_scope) 77 | 78 | dct['iters'] = '[%s]' % ', '.join(iters) 79 | dct['names'] = ', '.join(names) 80 | dct['ifs'] = '[%s]' % ', '.join(ifs) 81 | return LCOMP_TMP % dct 82 | 83 | IF_TPL = '''\ 84 | if ($b.bool(%(test)s) === true) { 85 | %(contents)s 86 | }%(more)s 87 | ''' 88 | 89 | @converts(ast.If) 90 | def _if(conv, node, scope): 91 | dct = {} 92 | dct['test'] = conv.convert_node(node.test, scope) 93 | dct['contents'] = conv.convert_block(node.body, scope) 94 | if node.orelse: 95 | if len(node.orelse) == 1: 96 | js = conv.convert_node(node.orelse[0], scope) 97 | dct['more'] = ' else ' + js 98 | else: 99 | js = conv.convert_block(node.orelse, scope) 100 | dct['more'] = ' else {\n%s\n}' % js 101 | else: 102 | dct['more'] = '' 103 | text = IF_TPL % dct 104 | return text 105 | 106 | TRY_TPL = '''try { 107 | %s 108 | } catch (%s) { 109 | %s 110 | } 111 | ''' 112 | 113 | @converts(ast.TryExcept) 114 | def _tryexcept(conv, node, scope): 115 | single = '''%s{ 116 | %s 117 | }''' 118 | body = conv.convert_block(node.body, scope) 119 | subs = [] 120 | temp = conv.get_temp('err') 121 | for handler in node.handlers: 122 | eb = '' 123 | if handler.name is not None: 124 | name = utils.lhand_assign(handler.name.id, scope) 125 | eb = ' %s = %s;\n ' % (name, temp) 126 | eb_ = conv.convert_block(handler.body, scope) 127 | eb += eb_ 128 | 129 | if handler.type is not None: 130 | t = conv.convert_node(handler.type, scope) 131 | top = 'if (%s.__class__ && $b.isinstance(%s, %s)) ' % (temp, temp, t) 132 | else: 133 | top = '' 134 | 135 | subs.append(single % (top, eb)) 136 | text = TRY_TPL % (body, temp, ' else '.join(subs)) 137 | conv.kill_temp('err') 138 | return text 139 | 140 | TRY_FINALLY = '''%(final_temp)s = false; 141 | try { 142 | %(body)s 143 | } catch (%(err_temp)s) { 144 | try { 145 | %(excepts)s 146 | } catch (%(err2_temp)s) { 147 | %(finally)s 148 | throw %(err2_temp)s; 149 | } 150 | %(final_temp)s = true; 151 | %(finally)s 152 | } 153 | if (!%(final_temp)s) { 154 | %(finally)s 155 | } 156 | ''' 157 | 158 | TRY_FINALLY = '''\ 159 | try { 160 | %(body)s 161 | } catch (%(err_temp)s) { 162 | %(finally)s 163 | throw %(err_temp)s; 164 | } 165 | %(finally)s 166 | ''' 167 | 168 | @converts(ast.TryFinally) 169 | def tryfinally(conv, node, scope): 170 | dct = {} 171 | dct['body'] = conv.convert_block(node.body, scope) 172 | dct['err_temp'] = temp = conv.get_temp('err') 173 | dct['finally'] = conv.convert_block(node.finalbody, scope) 174 | conv.kill_temp('err') 175 | return TRY_FINALLY % dct 176 | 177 | # vim: et sw=4 sts=4 178 | -------------------------------------------------------------------------------- /pjs/converter.py: -------------------------------------------------------------------------------- 1 | 2 | import ast 3 | import os 4 | import sys 5 | import utils 6 | 7 | MODULE_TEMPLATE = '''\ 8 | module('%(filename)s', function (_) { 9 | _.__doc__ = %(doc)s; 10 | %(contents)s 11 | }); 12 | ''' 13 | 14 | class PJsNotImplemented(Exception):pass 15 | class PJsException(Exception):pass 16 | 17 | class Scope: 18 | default_globals = ['__name__', '__doc__', '__file__'] 19 | 20 | def __init__(self, other=None): 21 | self.globals = Scope.default_globals[:] 22 | self.locals = self.globals 23 | self.explicit_globals = [] 24 | self.parent_locals = () 25 | self.explicit_locals = 0 26 | self.num_iters = 0 27 | self.atomic = False 28 | if other and isinstance(other, Scope): 29 | self.__dict__ = other.__dict__.copy() 30 | 31 | def copy(self): 32 | scope = Scope(self) 33 | old_locals = scope.locals 34 | scope.locals = [] 35 | scope.explicit_globals = [] 36 | if scope.explicit_locals: 37 | old_locals.insert(0, '__%d.' % len(scope.parent_locals)) 38 | else: 39 | old_locals.insert(0, '') 40 | if len(old_locals) > 1 and self.locals is not self.globals: 41 | scope.parent_locals += (tuple(old_locals),) 42 | return scope 43 | 44 | def find_import(name, filename): 45 | curdir = os.path.dirname(filename) 46 | cd = os.getcwd() 47 | for dr in sys.path: 48 | if dr == cd: 49 | dr = curdir 50 | fn = os.path.join(curdir, dr) 51 | for sub in name.split('.')[:-1]: 52 | if not os.path.exists(os.path.join(fn, sub, '__init__.py')): 53 | break 54 | else: 55 | yield os.path.join(fn, sub, '__init__.py') 56 | fn = os.path.join(fn, sub) 57 | else: 58 | fn = os.path.join(fn, name.split('.')[-1]) 59 | if os.path.exists(os.path.join(fn, '__init__.py')): 60 | yield os.path.join(fn, '__init__.py') 61 | return 62 | elif os.path.exists(fn + '.py'): 63 | yield fn + '.py' 64 | return 65 | raise PJsException('Import not found: %s from file %s' % (name, filename)) 66 | 67 | class Converter: 68 | handlers = {} 69 | indent = 4 70 | defaults = { 71 | 'indent': 4, 72 | 'ignore_import_errors': False, 73 | } 74 | 75 | @classmethod 76 | def register(cls, nodeType): 77 | '''Decorator helper; returns a decorator for ast.NodeType, which should decorate a callable 78 | that accepts: 79 | @param conv: converter instance 80 | @param node: the current node 81 | @param scope: the current scope 82 | ''' 83 | def meta(fn): 84 | cls.handlers[nodeType] = fn 85 | return meta 86 | 87 | def __init__(self, filename, **kwargs): 88 | self.startfile = os.path.abspath(filename) 89 | self.options = self.defaults.copy() 90 | self.options.update(kwargs) 91 | 92 | self.temps = {} 93 | self.to_import = [self.startfile] 94 | self.current = None 95 | 96 | def parse(self): 97 | modules = {} 98 | while len(self.to_import): 99 | filename = self.to_import.pop() 100 | if filename in modules: 101 | continue 102 | self.current = filename 103 | modules[filename] = self.convert_module(filename) 104 | return modules 105 | 106 | def add_import(self, name): 107 | if name in ('os', 'os.path', 'sys', '__builtin__', '__main__'): 108 | return 109 | self.to_import += list(find_import(name, self.current)) 110 | 111 | ## Deal with temporary variables 112 | def get_temp(self, ttype): 113 | self.temps[ttype] = self.temps.get(ttype, 0) + 1 114 | return '__pjs_%s_%d' % (ttype, self.temps[ttype]) 115 | 116 | def kill_temp(self, ttype): 117 | self.temps[ttype] -= 1 118 | 119 | def current_temp(self, ttype): 120 | return '__pjs_%s_%d' % (ttype, self.temps[ttype]) 121 | 122 | ## Conversion funcs 123 | def convert_module(self, filename): 124 | filename = os.path.abspath(filename) 125 | text = open(filename).read() 126 | node = ast.parse(text, filename) 127 | dct = { 128 | 'filename': filename, 129 | 'doc': utils.multiline(ast.get_docstring(node), False), 130 | } 131 | scope = Scope() 132 | contents = self.convert_block(node.body, scope) 133 | contents = utils.fix_undef(contents, scope, True) 134 | dct['contents'] = contents 135 | return MODULE_TEMPLATE % dct 136 | 137 | def convert_block(self, nodes, scope): 138 | text = ''.join(self.convert_node(child, scope) for child in nodes).strip() 139 | return '\n'.join(' '*self.options['indent'] + line for line in text.split('\n')) 140 | 141 | def convert_node(self, node, scope): 142 | if self.handlers.has_key(node.__class__): 143 | return self.handlers[node.__class__](self, node, scope) 144 | raise PJsNotImplemented("Conversion for node type %s is not yet supported." % node.__class__, vars(node)) 145 | 146 | def get_converter(self, what): 147 | if hasattr(what, '__class__'): 148 | what = what.__class__ 149 | return self.handlers[what] 150 | 151 | register = Converter.register 152 | -------------------------------------------------------------------------------- /pjs/data/ast_nodes.txt: -------------------------------------------------------------------------------- 1 | Add 2 | alias 3 | And 4 | arguments 5 | Assert 6 | Assign 7 | AST 8 | Attribute 9 | AugAssign 10 | AugLoad 11 | AugStore 12 | BinOp 13 | BitAnd 14 | BitOr 15 | BitXor 16 | boolop 17 | BoolOp 18 | Break 19 | Call 20 | ClassDef 21 | cmpop 22 | Compare 23 | comprehension 24 | Continue 25 | Del 26 | Delete 27 | Dict 28 | Div 29 | Ellipsis 30 | Eq 31 | excepthandler 32 | ExceptHandler 33 | Exec 34 | expr 35 | Expr 36 | expr_context 37 | Expression 38 | ExtSlice 39 | FloorDiv 40 | For 41 | FunctionDef 42 | GeneratorExp 43 | Global 44 | Gt 45 | GtE 46 | If 47 | IfExp 48 | Import 49 | ImportFrom 50 | In 51 | Index 52 | Interactive 53 | Invert 54 | Is 55 | IsNot 56 | keyword 57 | Lambda 58 | List 59 | ListComp 60 | Load 61 | LShift 62 | Lt 63 | LtE 64 | mod 65 | Mod 66 | Module 67 | Mult 68 | Name 69 | Not 70 | NotEq 71 | NotIn 72 | Num 73 | operator 74 | Or 75 | Param 76 | Pass 77 | Pow 78 | Print 79 | Raise 80 | Repr 81 | Return 82 | RShift 83 | slice 84 | Slice 85 | stmt 86 | Store 87 | Str 88 | Sub 89 | Subscript 90 | Suite 91 | TryExcept 92 | TryFinally 93 | Tuple 94 | UAdd 95 | unaryop 96 | UnaryOp 97 | USub 98 | While 99 | With 100 | Yield 101 | -------------------------------------------------------------------------------- /pjs/data/js_reserved.txt: -------------------------------------------------------------------------------- 1 | abstract 2 | as 3 | boolean 4 | break 5 | byte 6 | case 7 | catch 8 | char 9 | class 10 | continue 11 | const 12 | debugger 13 | default 14 | delete 15 | do 16 | double 17 | else 18 | enum 19 | export 20 | extends 21 | false 22 | final 23 | finally 24 | float 25 | for 26 | function 27 | goto 28 | if 29 | implements 30 | import 31 | in 32 | instanceof 33 | int 34 | interface 35 | is 36 | long 37 | namespace 38 | native 39 | new 40 | null 41 | package 42 | private 43 | protected 44 | public 45 | return 46 | short 47 | static 48 | super 49 | switch 50 | synchronized 51 | this 52 | throw 53 | throws 54 | transient 55 | true 56 | try 57 | typeof 58 | use 59 | var 60 | void 61 | volatile 62 | while 63 | with 64 | -------------------------------------------------------------------------------- /pjs/declared.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts 3 | import utils 4 | 5 | @converts(ast.Dict) 6 | def _dict(conv, node, scope): 7 | return '$b.dict([%s])' % ', '.join('[%s, %s]' % ( 8 | conv.convert_node(key, scope), 9 | conv.convert_node(value, scope) 10 | ) for key, value in zip(node.keys, node.values)) 11 | 12 | @converts(ast.List) 13 | def _list(conv, node, scope): 14 | return '$b.list([%s])' % ', '.join(conv.convert_node(sub, scope) for sub in node.elts) 15 | 16 | @converts(ast.Num) 17 | def _num(conv, node, scope): 18 | if type(node.n) == float: 19 | return '$b._float(%s)' % node.n 20 | return str(node.n) 21 | 22 | @converts(ast.Str) 23 | def _str(conv, node, scope): 24 | return '$b.str(%s)' % utils.multiline(node.s) 25 | 26 | @converts(ast.Tuple) 27 | def _tuple(conv, node, scope): 28 | return '$b.tuple([%s])' % ', '.join(conv.convert_node(sub, scope) for sub in node.elts) 29 | 30 | # vim: et sw=4 sts=4 31 | -------------------------------------------------------------------------------- /pjs/errors.py: -------------------------------------------------------------------------------- 1 | 2 | class PJsException(Exception):pass 3 | class PJsNameError(PJsException):pass 4 | 5 | # vim: et sw=4 sts=4 6 | -------------------------------------------------------------------------------- /pjs/expression.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts, PJsNotImplemented 3 | 4 | @converts(ast.Expr) 5 | def expr(conv, node, scope): 6 | return conv.convert_node(node.value, scope) + ';\n' 7 | 8 | @converts(ast.BoolOp) 9 | def boolop(conv, node, scope): 10 | bools = { 11 | ast.And:'&&', 12 | ast.Or:'||' 13 | } 14 | if not bools.has_key(node.op.__class__): 15 | raise PJsNotImplemented("Boolean operation %s not supported" % node.op, node) 16 | 17 | op = bools[node.op.__class__] 18 | return (' %s ' % op).join('$b.bool(%s)' % conv.convert_node(value, scope) for value in node.values) 19 | 20 | @converts(ast.BinOp) 21 | def binop(conv, node, scope): 22 | tpl = '$b.%s(%s, %s)' 23 | op = node.op.__class__.__name__.lower() 24 | ljs = conv.convert_node(node.left, scope) 25 | rjs = conv.convert_node(node.right, scope) 26 | return tpl % (op, ljs, rjs) 27 | 28 | @converts(ast.Compare) 29 | def compare(conv, node, scope): 30 | ops = { 31 | ast.In:'in', 32 | ast.NotIn:'not in', 33 | ast.Gt:'>', 34 | ast.GtE:'>=', 35 | ast.Lt:'<', 36 | ast.LtE:'<=', 37 | ast.Eq:'==', 38 | ast.NotEq:'!=', 39 | ast.IsNot:'!==', 40 | ast.Is:'===' 41 | } 42 | items = [conv.convert_node(node.left, scope)] 43 | for op, val in zip(node.ops, node.comparators): 44 | if op.__class__ not in ops: 45 | raise PJsNotImplemented('Comparison operator %s not suported' % op, op) 46 | items.append("'%s'" % ops[op.__class__]) 47 | js = conv.convert_node(val, scope) 48 | items.append(js) 49 | return '$b.do_ops(%s)' % (', '.join(items)) 50 | 51 | @converts(ast.UnaryOp) 52 | def unaryop(conv, node, scope): 53 | subs = { 54 | ast.Not:'!$b.bool(%s)', 55 | ast.UAdd:'+%s', 56 | ast.USub:'-%s' 57 | } 58 | if node.op.__class__ not in subs: 59 | raise PJsNotImplemented("Unary op %s not supported" % node.op, node.op) 60 | return subs[node.op.__class__] % conv.convert_node(node.operand, scope) 61 | 62 | # vim: et sw=4 sts=4 63 | -------------------------------------------------------------------------------- /pjs/imports.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts 3 | import utils 4 | 5 | IMPORT_TEMPLATE = '''if (__pjs_tmp_module%(subs)s.__all__ === undefined) { 6 | for (var __pjs_k in __pjs_tmp_module%(subs)s) { 7 | if (__pjs_k.indexOf('__') !== 0) { 8 | eval('%(prefix)s' + __pjs_k + ' = __pjs_tmp_module%(subs)s.' + __pjs_k + ';'); 9 | } 10 | } 11 | delete __pjs_k; 12 | } else { 13 | var __pjs_a = __pjs_tmp_module%(subs)s.__all__.as_js(); 14 | for (var __pjs_i=0; __pjs_i<__pjs_a.length; __pjs_i++) { 15 | var __pjs_k = __pjs_a[__pjs_i]; 16 | eval('%(prefix)s'+__pjs_k+' = __pjs_tmp_module%(subs)s.'+__pjs_k+';'); 17 | } 18 | delete __pjs_a; 19 | delete __pjs_i; 20 | delete __pjs_k; 21 | } 22 | ''' 23 | 24 | @converts(ast.ImportFrom) 25 | def importfrom(conv, node, scope): 26 | text = 'var __pjs_tmp_module = $b.__import__("%s", _.__name__, _.__file__);\n' % node.module 27 | base_name = node.module.split('.')[0] 28 | subs_name = '.'.join(node.module.split('.')[1:]) 29 | if subs_name: 30 | subs_name = '.' + subs_name 31 | prefix = utils.local_prefix(scope) 32 | for alias in node.names: 33 | if alias.name == '*': 34 | text += IMPORT_TEMPLATE % {'prefix': prefix, 'subs':subs_name} 35 | break 36 | asname = alias.asname or alias.name 37 | left = utils.lhand_assign(asname, scope) 38 | text += '%s = __pjs_tmp_module%s.%s;\n' % (left, subs_name, alias.name) 39 | conv.add_import(node.module) 40 | return text 41 | 42 | @converts(ast.Import) 43 | def _import(conv, node, scope): 44 | tpl = '%s = $b.__import__("%s", _.__name__, _.__file__);\n' 45 | text = '' 46 | for name in node.names: 47 | asname = name.name.split('.')[0] 48 | if name.asname: 49 | raise PJsException('import x as y not yet supported') 50 | asname = name.asname 51 | asname = utils.lhand_assign(asname, scope) 52 | text += tpl % (asname, name.name) 53 | conv.add_import(name.name) 54 | return text 55 | 56 | # vim: et sw=4 sts=4 57 | -------------------------------------------------------------------------------- /pjs/jslib/modules.js: -------------------------------------------------------------------------------- 1 | /** 2 | Copyright 2010 Jared Forsyth 3 | 4 | Permission is hereby granted, free of charge, to any person 5 | obtaining a copy of this software and associated documentation 6 | files (the "Software"), to deal in the Software without 7 | restriction, including without limitation the rights to use, 8 | copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the 10 | Software is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 20 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 21 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 22 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | **/ 26 | 27 | /** general module loading... not spectacular, I know; it gets better when you 28 | * add sys and __builtins__ 29 | **/ 30 | 31 | var __module_cache = {}; 32 | function module(filename, fn) { 33 | var that = {}; 34 | that.__file__ = filename; 35 | that.__init__ = fn; 36 | that.load = $def({'mod':null}, function load_module(name, mod) { 37 | if (mod === null) mod = {}; 38 | mod.__name__ = name; 39 | if (__builtins__) mod.__name__ = __builtins__.str(name); 40 | mod.__file__ = that.__file__; 41 | if (__builtins__) mod.__file__ = __builtins__.str(that.__file__); 42 | mod.__dict__ = mod; 43 | mod.__type__ = 'module'; 44 | that._module = mod; 45 | fn(mod); 46 | return mod; 47 | }); 48 | __module_cache[that.__file__] = that; 49 | } 50 | 51 | -------------------------------------------------------------------------------- /pjs/modules.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # vim: et sw=4 sts=4 4 | -------------------------------------------------------------------------------- /pjs/old_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | from errors import PJsException 6 | 7 | def multiline(text): 8 | if text is None: 9 | return '""'; 10 | lines = text.split('\n') 11 | return (''.join("'%s\\n' +\n" % line.encode('string_escape') for line\ 12 | in lines[:-1]) + "'%s'" % lines[-1].encode('string_escape')).replace('&', '&').replace(':', '&coln;') 13 | 14 | def new_scope(scope): 15 | scope = scope.copy() 16 | old_locals = scope['locals'] 17 | scope['locals'] = [] 18 | scope['exp globals'] = [] 19 | if scope['exp locals']: 20 | old_locals.insert(0, '__%d.' % scope['exp locals']) 21 | else: 22 | old_locals.insert(0, '') 23 | if len(old_locals) > 1: 24 | scope['parent locals'] = scope['parent locals'] + (tuple(old_locals), ) 25 | return scope 26 | 27 | localfile = lambda x:os.path.join(os.path.dirname(__file__), x) 28 | reserved_words = open(localfile('js_reserved.txt')).read().split() 29 | 30 | reserved_words += ['js', 'py'] 31 | 32 | builtin_words = __builtins__.keys() 33 | builtin_words += ['py', 'definedor'] 34 | 35 | def resolve(name, scope): 36 | if name == 'window': 37 | return name 38 | elif name == 'js': 39 | return name 40 | elif name == 'py': 41 | return '$b.py' 42 | elif name in ('float', 'int'): 43 | return '$b._' + name 44 | elif name in reserved_words: 45 | raise PJsException("Sorry, '%s' is a reserved word in javascript." % name) 46 | elif name in scope['exp globals']: 47 | return '_.%s' % name 48 | elif name in scope['locals']: 49 | if scope['locals'] is scope['globals']: 50 | return '_.%s' % name 51 | elif scope['exp locals']: 52 | return '__%d.%s' % (len(scope['parent locals']), name) 53 | return name 54 | elif name in scope['globals']: 55 | return '_.%s' % name 56 | elif name not in scope['globals'] and name in builtin_words: 57 | return '$b.%s' % name 58 | else: 59 | pref = local_prefix(scope) 60 | # TODO: do some checking for import * 61 | return '{:undef:%s:%s:}' % (name, pref) 62 | ## for all we know, it's not defined.... 63 | if scope['locals'] is scope['globals']: 64 | return '$b.assertdefined(_.%s, "%s")' % (name, name) 65 | elif scope['exp locals']: 66 | return '$b.assertdefined(__%d.%s, "%s")' % (len(scope['parent locals']), name, name) 67 | else: 68 | return '$b.assertdefined(%s || _.%s, "%s")' % (name, name, name) 69 | 70 | def local_prefix(scope): 71 | if scope['globals'] is scope['locals']: 72 | return '_.' 73 | if scope['exp locals']: 74 | return '__%d.' % len(scope['parent locals']) 75 | return '' 76 | 77 | def find_import(iname, fname): 78 | base = os.path.dirname(fname) 79 | cd = os.getcwd() 80 | for dr in sys.path: 81 | if dr == cd: 82 | dr = base 83 | fn = os.path.join(base, dr) 84 | bad = False 85 | for part in iname.split('.')[:-1]: 86 | if not os.path.exists(os.path.join(fn, part, '__init__.py')): 87 | bad = True 88 | break 89 | fn = os.path.join(fn, part) 90 | if not bad: 91 | fn = os.path.join(fn, iname.split('.')[-1]) 92 | if os.path.exists(fn + '.py'): 93 | return fn + '.py' 94 | if os.path.exists(os.path.join(fn, '__init__.py')): 95 | return os.path.join(fn, '__init__.py') 96 | raise PJsException('module not found: %s' % iname) 97 | 98 | # vim: et sw=4 sts=4 99 | -------------------------------------------------------------------------------- /pjs/scoping.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts, PJsNotImplemented 3 | import utils 4 | 5 | FUNC_TEMPLATE = '''\ 6 | %(left)s = %(dec_front)s$def(%(special)sfunction $_%(name)s(%(args)s) { // %(lineno)d 7 | %(contents)s 8 | })%(dec_back)s; 9 | %(rname)s.__module__ = _.__name__; 10 | %(rname)s.__name__ = $b.str("%(name)s"); 11 | ''' 12 | 13 | LAMBDA_TEMPLATE = '''\ 14 | $def(%(special)sfunction $_lambda(%(args)s) {return %(contents)s;})''' 15 | 16 | CLASS_TEMPLATE = '''\ 17 | %(left)s = %(dec_front)sClass('%(name)s', [%(bases)s], (function(){ 18 | var __%(lnum)s = {}; 19 | %(contents)s 20 | return __%(lnum)s; 21 | }()))%(dec_back)s; 22 | %(rname)s.__module__ = _.__name__; 23 | ''' 24 | 25 | @converts(ast.FunctionDef) 26 | def functiondef(conv, node, scope): 27 | dct = { 28 | 'name': node.name, 29 | 'lineno': node.lineno, 30 | 31 | 'special': function_special(conv, node, scope), 32 | 'left': utils.lhand_assign(node.name, scope), 33 | 'rname': utils.resolve(node.name, scope), 34 | } 35 | args = function_args(conv, node, scope) 36 | dct['args'] = ', '.join(args) 37 | 38 | dct['dec_front'] = '' 39 | dct['dec_back'] = '' 40 | for dec in node.decorator_list: 41 | dct['dec_front'] += conv.convert_node(dec, scope) + '(' 42 | dct['dec_back'] += ')' 43 | 44 | scope = scope.copy() 45 | scope.explicit_locals = False 46 | scope.locals += args 47 | 48 | dct['contents'] = utils.fix_undef(conv.convert_block(node.body, scope), scope) 49 | return FUNC_TEMPLATE % dct 50 | 51 | def function_args(conv, node, scope): 52 | args = list(arg.id for arg in node.args.args) 53 | if node.args.vararg: 54 | args.append(node.args.vararg) 55 | if node.args.kwarg: 56 | args.append(node.args.kwarg) 57 | return args 58 | 59 | def function_special(conv, node, scope): 60 | defaults = function_defaults(conv, node, scope) 61 | if node.args.kwarg: 62 | return defaults + ', ' + str(bool(node.args.vararg)).lower() + ', true, ' 63 | 64 | elif node.args.vararg: 65 | return defaults + ', true, ' 66 | 67 | elif defaults != '{}': 68 | return defaults + ', ' 69 | 70 | else: 71 | return '' 72 | 73 | def function_defaults(conv, node, scope): 74 | args = list(arg.id for arg in node.args.args) 75 | defaults = [] 76 | for default, name in zip(reversed(node.args.defaults), reversed(args)): 77 | defaults.append("'%s': %s" % (name, conv.convert_node(default, scope))) 78 | return '{' + ', '.join(defaults) + '}' 79 | 80 | @converts(ast.Lambda) 81 | def lambdadef(conv, node, scope): 82 | dct = { 83 | 'special': function_special(conv, node, scope), 84 | } 85 | args = function_args(conv, node, scope) 86 | dct['args'] = ', '.join(args) 87 | scope = scope.copy() 88 | scope.explicit_locals = False 89 | scope.locals += args 90 | dct['contents'] = utils.fix_undef(conv.convert_node(node.body, scope), scope) 91 | return LAMBDA_TEMPLATE % dct 92 | 93 | @converts(ast.ClassDef) 94 | def classdef(conv, node, scope): 95 | imports = [] 96 | dct = { 97 | 'name': node.name, 98 | 99 | 'bases': ', '.join(utils.resolve(base.id, scope) for base in node.bases), 100 | 'left': utils.lhand_assign(node.name, scope), 101 | 'rname': utils.resolve(node.name, scope), 102 | } 103 | 104 | dct['dec_front'] = '' 105 | dct['dec_back'] = '' 106 | for dec in node.decorator_list: 107 | dct['dec_front'] += conv.convert_node(dec, scope) + '(' 108 | dct['dec_back'] += ')' 109 | 110 | scope = scope.copy() 111 | scope.explicit_locals = True 112 | 113 | dct['contents'] = utils.fix_undef(conv.convert_block(node.body, scope), scope) 114 | 115 | dct['lnum'] = len(scope.parent_locals) 116 | 117 | return CLASS_TEMPLATE % dct 118 | 119 | # vim: et sw=4 sts=4 120 | -------------------------------------------------------------------------------- /pjs/small.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts 3 | import utils 4 | 5 | @converts(ast.Name) 6 | def _name(conv, node, scope): 7 | return utils.resolve(node.id, scope) 8 | 9 | @converts(ast.Index) 10 | def _index(conv, node, scope): 11 | return conv.convert_node(node.value, scope) 12 | 13 | @converts(ast.Slice) 14 | def _slice(conv, node, scope): 15 | if node.lower: 16 | lower = conv.convert_node(node.lower, scope) 17 | else: 18 | lower = 'null' 19 | if node.upper: 20 | upper = conv.convert_node(node.upper, scope) 21 | else: 22 | upper = 'null' 23 | if node.step: 24 | step = conv.convert_node(node.step, scope) 25 | else: 26 | step = '1' 27 | return '$b.slice(%s, %s, %s)' % (lower, upper, step) 28 | 29 | # vim: et sw=4 sts=4 30 | -------------------------------------------------------------------------------- /pjs/special.py: -------------------------------------------------------------------------------- 1 | import ast 2 | from converter import register as converts, PJsNotImplemented 3 | 4 | @converts(ast.Assert) 5 | def _assert(conv, node, scope): 6 | js = conv.convert_node(node.test, scope) 7 | if node.msg: 8 | msg = conv.convert_node(node.msg, scope) 9 | else: 10 | msg = "'%s'" % js.encode('string_escape') 11 | return '$b.assert(%s, %s);\n' % (js, msg) 12 | 13 | # @group jumps 14 | 15 | @converts(ast.Break) 16 | def _break(conv, node, scope): 17 | return 'break;\n' 18 | 19 | @converts(ast.Pass) 20 | def _pass(conv, node, scope): 21 | return '' 22 | 23 | @converts(ast.Continue) 24 | def _continue(conv, node, scope): 25 | return 'continue;\n' 26 | 27 | @converts(ast.Return) 28 | def _return(conv, node, scope): 29 | if node.value is None: 30 | return 'return;\n' 31 | return 'return %s;\n' % conv.convert_node(node.value, scope) 32 | 33 | @converts(ast.Raise) 34 | def _raise(conv, node, scope): 35 | if node.type is None: 36 | return 'throw %s' % conv.current_temp('err') 37 | js = conv.convert_node(node.type, scope) 38 | if node.inst is None: 39 | return '$b.raise(%s);\n' % js 40 | inner = conv.convert_node(node.inst, scope) 41 | return '$b.raise(%s(%s));\n' % (js, inner) 42 | 43 | @converts(ast.Yield) 44 | def _yield(conv, node, scope): 45 | raise PJsNotImplemented('Sorry, PJs doesn\'t work with generators, and probably won\'t for the forseeable future...generators are hard.') 46 | 47 | @converts(ast.Delete) 48 | def _delete(conv, node, scope): 49 | t = [] 50 | for tag in node.targets: 51 | if isinstance(tag, ast.Subscript): 52 | ## TODO: doesn't handle "delete js.some[3]" 53 | js = conv.get_converter(tag)(conv, tag, scope, 'delete') 54 | t.append(js) 55 | else: 56 | js = conv.convert_node(tag, scope) 57 | t.append('delete %s' % js) 58 | return '\n'.join(t) + '\n' 59 | 60 | @converts(ast.Global) 61 | def _global(conv, node, scope): 62 | js = '// switching to global scope: [%s]\n' % ', '.join(node.names) 63 | for name in node.names: 64 | scope.explicit_globals.append(name) 65 | return js 66 | 67 | @converts(ast.Print) 68 | def _print(conv, node, scope): 69 | if node.dest: 70 | raise PJsException('print>> is not yet supported') 71 | values = [] 72 | for child in node.values: 73 | js = conv.convert_node(child, scope) 74 | values.append(js) 75 | text = '$b.print(%s);//, %s\n' % (', '.join(values), str(node.nl).lower()) 76 | return text 77 | 78 | # vim: et sw=4 sts=4 79 | -------------------------------------------------------------------------------- /pjs/templates.py: -------------------------------------------------------------------------------- 1 | 2 | TEMPLATES = { 3 | 'module':'''\ 4 | module('%(filename)s', function (%(scope)s) { 5 | %(scope)s.__doc__ = %(doc)s; 6 | %(contents)s 7 | }); 8 | ''', 9 | 'class':'''\ 10 | %(left)s = %(dec_front)sClass('%(name)s', [%(bases)s], (function(){ 11 | var __%(lnum)s = {}; 12 | %(contents)s 13 | return __%(lnum)s; 14 | }()))%(dec_back)s; 15 | %(rname)s.__module__ = _.__name__; 16 | ''', 17 | 'function':'''\ 18 | %(left)s = %(dec_front)s$def(%(special)sfunction $_%(name)s(%(args)s) { // %(lineno)d 19 | %(contents)s 20 | })%(dec_back)s; 21 | %(rname)s.__module__ = _.__name__; 22 | %(rname)s.__name__ = $b.str("%(name)s"); 23 | ''', 24 | 'if':'''\ 25 | if ($b.bool(%(test)s) === true) { 26 | %(contents)s 27 | }%(more)s 28 | ''', 29 | 'while': '''\ 30 | while ($b.bool(%s) === true) { 31 | %s 32 | } 33 | ''', 34 | 'for': '''\ 35 | var __pjs_iter%d = $b.foriter(%s); 36 | while (__pjs_iter%d.trynext()) { 37 | %s 38 | %s 39 | } 40 | ''', 41 | 'try': '''try { 42 | %s 43 | } catch (__pjs_err) { 44 | %s 45 | } 46 | ''', 47 | 'import *': '''if (__pjs_tmp_module.__all__ === undefined) { 48 | for (var __pjs_k in __pjs_tmp_module) { 49 | if (__pjs_k.indexOf('__') !== 0) 50 | eval('%s'+__pjs_k+' = __pjs_tmp_module.'+__pjs_k+';'); 51 | } 52 | delete __pjs_k; 53 | } else { 54 | var __pjs_a = __pjs_tmp_module.__all__.as_js(); 55 | for (var __pjs_i=0; __pjs_i<__pjs_a.length; __pjs_i++) { 56 | var __pjs_k = __pjs_a[__pjs_i]; 57 | eval('%s'+__pjs_k+' = __pjs_tmp_module.'+__pjs_k+';'); 58 | } 59 | delete __pjs_a; 60 | delete __pjs_i; 61 | delete __pjs_k; 62 | } 63 | ''' 64 | } 65 | 66 | 67 | # vim: et sw=4 sts=4 68 | -------------------------------------------------------------------------------- /pjs/templates/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Auto PJs output for %(file)s 6 | 7 | 8 | 9 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /pjs/templates/template.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file %(file)s 4 | 5 | %(text)s 6 | var pjs_main =__builtins__.run_main('%(file)s', %(path)s); 7 | 8 | -------------------------------------------------------------------------------- /pjs/templates/template.ss.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file %(file)s 4 | 5 | load("%(lib)s"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | %(text)s 9 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 10 | var pjs_main = __builtins__.run_main('%(file)s', %(path)s); 11 | 12 | -------------------------------------------------------------------------------- /pjs/utils.py: -------------------------------------------------------------------------------- 1 | 2 | import ast 3 | import re 4 | import os 5 | 6 | def multiline(text, convert=True): 7 | '''convert 'text' to a multiline string (if it contains any \\n's) 8 | Optionally escaping & and :''' 9 | 10 | if text is None: 11 | return '""'; 12 | lines = text.split('\n') 13 | multi = (''.join("'%s\\n' +\n" % line.encode('string_escape') for line\ 14 | in lines[:-1]) + "'%s'" % lines[-1].encode('string_escape')) 15 | if convert: 16 | multi = multi.replace('&', '&').replace(':', '&coln;') 17 | return multi 18 | 19 | def fix_undef(text, scope, modlevel=False): 20 | '''Replace special {:undef:[vbl name]} blocks with the properly scoped 21 | variable if it's available. Otherwise, if [modlevel], replace then mith 22 | $b.assertdefined()''' 23 | 24 | prefix = local_prefix(scope) 25 | for name in scope.locals: 26 | text = re.sub('{:undef:' + name + ':[^:]*:}', prefix + name, text) 27 | 28 | if modlevel: 29 | text = re.sub('{:undef:(\w+):([^:]*):}', '$b.assertdefined(\\2\\1, "\\1")', text) 30 | text = text.replace('&coln;', ':').replace('&', '&') 31 | return text 32 | 33 | def local_prefix(scope): 34 | '''Get the prefix for local variables''' 35 | 36 | if scope.globals is scope.locals: 37 | return '_.' 38 | if scope.explicit_locals: 39 | return '__%d.' % len(scope.parent_locals) 40 | return '' 41 | 42 | def lhand_assign(name, scope): 43 | prefix = local_prefix(scope) 44 | if name in scope.locals: 45 | return prefix + name 46 | elif name in scope.explicit_globals: 47 | return '_.%s' % name 48 | 49 | if not prefix: 50 | prefix = 'var ' 51 | scope.locals.append(name) 52 | return prefix + name 53 | 54 | localfile = lambda x:os.path.join(os.path.dirname(__file__), x) 55 | reserved_words = open(localfile('data/js_reserved.txt')).read().split() 56 | 57 | reserved_words += ['js', 'py'] 58 | 59 | builtin_words = __builtins__.keys() 60 | builtin_words += ['js', 'py', 'definedor'] 61 | 62 | def resolve(name, scope): 63 | if name in ('window', 'js'): 64 | return name 65 | elif name in ('float', 'int'): 66 | return '$b._' + name 67 | elif name == 'py': 68 | return '$b.py' 69 | elif name == 'super': 70 | raise SyntaxError('Sorry, super is a reserved word in javascript. "super" will never be PJs supported; it requires too much attribute magic to correctly support') 71 | elif name in reserved_words: 72 | raise SyntaxError("Sorry, '%s' is a reserved word in javascript." % name) 73 | elif name in scope.explicit_globals: 74 | return '_.%s' % name 75 | elif name in scope.locals: 76 | if scope.globals is scope.locals: 77 | return '_.%s' % name 78 | elif scope.explicit_locals: 79 | return '__%d.%s' % (len(scope.parent_locals), name) 80 | return name 81 | for locs in scope.parent_locals: 82 | if name in locs[1:]: 83 | return locs[0] + name 84 | if name in scope.globals: 85 | return '_.%s' % name 86 | elif name in builtin_words: 87 | return '$b.%s' % name 88 | else: 89 | prefix = local_prefix(scope) 90 | return '{:undef:%s:%s:}' % (name, prefix) 91 | 92 | def deepleft(conv, node, at, scope, name='__pjs_tmp'): 93 | if isinstance(node, ast.Tuple): 94 | text = '' 95 | for i,n in enumerate(node.elts): 96 | text += deepleft(conv, n, at + [i], scope, name) 97 | return text 98 | else: 99 | right = name + ''.join('.__getitem__(%d)' % n for n in at) 100 | if isinstance(node, ast.Subscript): 101 | left = conv.get_converter(node)(conv, node, scope, True) 102 | if left.endswith(' '): 103 | return left + right + ');\n' 104 | elif isinstance(node, ast.Name): 105 | left = lhand_assign(node.id, scope) 106 | else: 107 | left = conv.convert_node(node, scope) 108 | return '%s = %s;\n' % (left, right) 109 | 110 | def new_scope(scope): 111 | scope = scope.copy() 112 | old_locals = scope['locals'] 113 | scope['locals'] = [] 114 | scope['exp globals'] = [] 115 | if scope['exp locals']: 116 | old_locals.insert(0, '__%d.' % scope['exp locals']) 117 | else: 118 | old_locals.insert(0, '') 119 | if len(old_locals) > 1: 120 | scope['parent locals'] = scope['parent locals'] + (tuple(old_locals), ) 121 | return scope 122 | 123 | # vim: et sw=4 sts=4 124 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pbj 2 | pytest 3 | -------------------------------------------------------------------------------- /runtest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import glob 3 | import os 4 | from subprocess import Popen, PIPE 5 | 6 | def execute(cmd): 7 | p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) 8 | out = p.stdout.read() 9 | err = p.stderr.read() 10 | return out, err 11 | 12 | if __name__ == '__main__': 13 | import sys 14 | if len(sys.argv) > 1: 15 | files = sys.argv[1:] 16 | else: 17 | files = glob.glob('test/py/*.py') 18 | execute(['make', 'jslib']) 19 | for fname in files: 20 | compare(fname) 21 | 22 | 23 | 24 | # vim: et sw=4 sts=4 25 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from distutils.core import setup 3 | import setuptools 4 | 5 | setup(name='PJs', 6 | version='0.0.2', 7 | description='kinda like pyjamas, but quicker, cleaner, and easier. has the goal of generating readable, usable *robust* javascript code from python code', 8 | author='Jared Forsyth', 9 | author_email='jared@jaredforsyth.com', 10 | url='http://jaredforsyth.com/projects/pjs/', 11 | packages=['pjs'], 12 | install_requires=['pbj'], 13 | include_package_data=True, 14 | classifiers=['Programming Language :: Python :: 2.7'] 15 | ) 16 | -------------------------------------------------------------------------------- /strider-custom.json: -------------------------------------------------------------------------------- 1 | {"test":"./venv/bin/python make.pbj pytest"} 2 | -------------------------------------------------------------------------------- /test/browser/hello.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | def hello(name='PJs'): 4 | window.alert("Hello " + name + '!') 5 | 6 | hello() 7 | hello('Frank') 8 | hello(name='Susan') 9 | 10 | # vim: et sw=4 sts=4 11 | -------------------------------------------------------------------------------- /test/browser/jqueryui.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Auto PJs output for /home/jared/clone/pjs/test/browser/hello.py 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 20 |
21 |

Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.

22 |
23 |
24 |

Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.

25 |
26 |
27 |

Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.

28 |

Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.

29 |
30 |
31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /test/browser/jqueryui.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /home/jared/clone/pjs/test/browser/jqueryui.py 4 | 5 | module('/home/jared/clone/pjs/test/browser/jqueryui.py', function (_) { 6 | _.__doc__ = ""; 7 | _.SplitPane = Class('SplitPane', [], (function(){ 8 | var __1 = {}; 9 | __1.__init__ = $m(function (self, node) { 10 | self.node = node; 11 | }); 12 | __1.__init__.__module__ = _.__name__; 13 | __1.__init__.__name__ = "__init__"; 14 | return __1; 15 | }())); 16 | _.SplitPane.__module__ = _.__name__; 17 | $b.str('Ways of embedding javascript code...\n' + 18 | '\n' + 19 | 'prepend js. to everything.... the js. gets removed...\n' + 20 | '\n' + 21 | 'so\n' + 22 | '\n' + 23 | 'hello(js.jQuery(\'world\'))\n' + 24 | '\n' + 25 | 'becomes\n' + 26 | '\n' + 27 | 'hello(jQuery($b.js($b.str(\'world\'))))\n' + 28 | '\n' + 29 | ''); 30 | _.json = $b.__import__("json", _.__name__, _.__file__); 31 | _.jq = window.jQuery; 32 | _.onload = $m(function (jQuery) { 33 | _.jq($b.js($b.str('#tabs'))).tabs(); 34 | $b.print(_.jq($b.js($b.str('#tabs'))).length);//, true 35 | $b.print(_.json.dumps($b.list([$b.str('hello'), $b.str('man'), $b.dict([[$b.str('yeah'), 6], [5, 2]])])));//, true 36 | }); 37 | _.onload.__module__ = _.__name__; 38 | _.onload.__name__ = "onload"; 39 | if ($b.bool($b.do_ops(_.__name__, '==', $b.str('__main__'))) === true) { 40 | _.jq($b.js($b.str('document'))).ready(_.onload); 41 | } 42 | }); 43 | 44 | module('/home/jared/clone/pjs/test/browser/json.py', function (_) { 45 | _.__doc__ = ""; 46 | _.loads = $m(function (string) { 47 | return window.JSON.parse($b.js(string)); 48 | }); 49 | _.loads.__module__ = _.__name__; 50 | _.loads.__name__ = "loads"; 51 | _.dumps = $m(function (obj) { 52 | return window.JSON.stringify($b.js(obj)); 53 | }); 54 | _.dumps.__module__ = _.__name__; 55 | _.dumps.__name__ = "dumps"; 56 | }); 57 | 58 | __builtins__.run_main('/home/jared/clone/pjs/test/browser/jqueryui.py'); 59 | -------------------------------------------------------------------------------- /test/browser/jqueryui.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class SplitPane: 4 | def __init__(self, node): 5 | self.node = node 6 | 7 | '''Ways of embedding javascript code... 8 | 9 | prepend js. to everything.... the js. gets removed... 10 | 11 | so 12 | 13 | hello(js.jQuery('world')) 14 | 15 | becomes 16 | 17 | hello(jQuery($b.js($b.str('world')))) 18 | 19 | ''' 20 | import json 21 | 22 | jq = window.jQuery; 23 | 24 | def onload(jQuery): 25 | js.jq('#tabs').tabs() 26 | print js.jq('#tabs').length 27 | print json.dumps(['hello', 'man', {'yeah':6,5:2}]) 28 | 29 | if __name__ == '__main__': 30 | js.jq("document").ready(onload); 31 | 32 | # vim: et sw=4 sts=4 33 | -------------------------------------------------------------------------------- /test/browser/json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | def loads(string): 4 | return window.JSON.parse(string) 5 | 6 | def dumps(obj): 7 | return window.JSON.stringify(obj) 8 | 9 | 10 | # vim: et sw=4 sts=4 11 | -------------------------------------------------------------------------------- /test/browser/makefile: -------------------------------------------------------------------------------- 1 | 2 | jqueryui: jqueryui.py ../../pjs/convert.py 3 | @../../convert.py jqueryui.py jqueryui.js 4 | 5 | test: jqueryui 6 | @google-chrome jqueryui.html 7 | 8 | -------------------------------------------------------------------------------- /test/pjs/basic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | x = 3 4 | 5 | assert(x == x) 6 | assert(3 == x) 7 | assert('Hello' == 'Hello') 8 | assert('Man' != 'Mouse') 9 | 10 | # vim: et sw=4 sts=4 11 | -------------------------------------------------------------------------------- /test/pjs/classes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class a: 4 | def b(self): 5 | return 5 6 | 7 | 8 | print a 9 | print a.b 10 | print a().b 11 | print type(a().b) 12 | inst = a() 13 | assert(a != a.b) 14 | assert(inst != inst.b) 15 | assert(a != inst) 16 | assert(isinstance(inst, a)) 17 | assert(type(inst) == a) 18 | 19 | c = js(a().b) 20 | assert(js.c() == 5) 21 | 22 | 23 | # vim: et sw=4 sts=4 24 | -------------------------------------------------------------------------------- /test/pjs/tojs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | x = js([1,2,3,4]) 4 | assert(js.x[1] == 2) 5 | assert(x.length == 4) 6 | assert(x.slice(0,2).length == 2) 7 | 8 | def m(e): 9 | return js.e[0] 10 | def y():return 4 11 | z = js([m,y]) 12 | 13 | assert [m][0] == m 14 | assert m == m 15 | assert js.z[0].__wraps__ == m 16 | 17 | assert js.z[0]([1]) == 1 18 | 19 | ham = js([[1,2,3], [2,3,4]]) 20 | assert m(js.ham[0]) 21 | 22 | def a(): 23 | def b(a): 24 | assert js.a[1] == 2 25 | return b 26 | 27 | js.a()([1,2]) 28 | 29 | assert(js.x.slice(2).slice(0)[1] == 4) 30 | 31 | # vim: et sw=4 sts=4 32 | -------------------------------------------------------------------------------- /test/py/allimports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from os.path import join as jon, dirname 4 | 5 | print jon('hi', 'ho') 6 | 7 | from os.path import * 8 | from toimp import * 9 | 10 | print thevalue 11 | print dirname(imports.__file__) 12 | 13 | 14 | # vim: et sw=4 sts=4 15 | -------------------------------------------------------------------------------- /test/py/assert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | assert True 4 | assert 1==1, 'with message' 5 | 6 | # vim: et sw=4 sts=4 7 | -------------------------------------------------------------------------------- /test/py/assign.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # normal 4 | a = 3 5 | b = 3,4 6 | print a, b 7 | a,b = b,a 8 | print a, b 9 | 10 | # tuple assign 11 | c, d = [4] + [5] 12 | print c, d 13 | a, (b,c) = 1, (2,3) 14 | print b+c-a 15 | 16 | # augassign 17 | r = [3] 18 | r += [1] 19 | print r 20 | a += 2 21 | b /= 1 22 | print a,b 23 | 24 | # multi assign 25 | mult = iple = 4 26 | print mult 27 | print iple 28 | a,b = c = 3,4 29 | print [a,b,c] 30 | 31 | class F:pass 32 | o = F 33 | 34 | F.r, F.g = 2,3 35 | 36 | F.r = 3 37 | e = F() 38 | e.t = 7 39 | print e.r,e.t 40 | 41 | # subscript assign 42 | f = {} 43 | f[4]=r 44 | f['6'] = [] 45 | f['6'] += [3,4] 46 | f['1'], f['2'] = 2,1 47 | 48 | # vim: et sw=4 sts=4 49 | -------------------------------------------------------------------------------- /test/py/class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | b = 3 4 | class Simple: 5 | a=2 6 | c=b 7 | b=4 8 | def man(self): 9 | print 'hi', self.a 10 | 11 | class A: 12 | a = 2 13 | class B: 14 | a = 3 15 | b = 4 16 | b = 5 17 | 18 | print b 19 | print Simple.a 20 | print Simple().man() 21 | print Simple.b, Simple.c 22 | 23 | print A.a 24 | print A.b 25 | print A.B.a, A.B.b 26 | 27 | # vim: et sw=4 sts=4 28 | -------------------------------------------------------------------------------- /test/py/cmp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | if 1 and 0: 4 | print 'hi' 5 | elif 2==3: 6 | print 'no' 7 | else: 8 | print 3>4 9 | 10 | if 3==1 or 2>=2: 11 | print 'yeah' 12 | 13 | 14 | # vim: et sw=4 sts=4 15 | -------------------------------------------------------------------------------- /test/py/decorators.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | def decorate_me(func): 4 | print 'decorating' 5 | def meta(*a, **b): 6 | print 'deca_args', len(a) 7 | func(*a, **b) 8 | return meta 9 | 10 | @decorate_me 11 | def hello(a,b): 12 | print a+b 13 | 14 | hello(3,5) 15 | 16 | class Cls: 17 | @decorate_me 18 | def hello(self, a,b): 19 | print a - b 20 | 21 | Cls().hello(4,5) 22 | 23 | # vim: et sw=4 sts=4 24 | -------------------------------------------------------------------------------- /test/py/deep_inherit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class a1(object): 4 | def a(self):print 'a.a' 5 | def b(self):print 'a.b' 6 | def c(self):print 'a.c' 7 | def d(self):print 'a.d' 8 | 9 | class a2(a1): 10 | pass 11 | 12 | class a3(a2): 13 | pass 14 | 15 | class b2(a1): 16 | def a(self):print 'b2.a' 17 | 18 | class b3(b2): 19 | pass 20 | 21 | class fin(a3, b3):pass 22 | 23 | fin().a() 24 | 25 | 26 | # vim: et sw=4 sts=4 27 | -------------------------------------------------------------------------------- /test/py/dicts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | d = {} 4 | d[2] = 3 5 | d['a'] = 'b' 6 | d[2], d['a'] = d['a'], d[2] 7 | print d[2] 8 | print 2 in d 9 | print 'a' in d 10 | print d.has_key(7) 11 | print d.has_key('a') 12 | 13 | # vim: et sw=4 sts=4 14 | -------------------------------------------------------------------------------- /test/py/errno.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | EINVAL = 22 4 | 5 | # vim: et sw=4 sts=4 6 | -------------------------------------------------------------------------------- /test/py/exceptions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | try: 4 | um 5 | 3+4+[3] 6 | a.b() 7 | except TypeError, e: 8 | print 'yeah' 9 | except (NotImplemented, ValueError), r: 10 | print 'and', r 11 | except: 12 | print 'failed' 13 | 14 | # vim: et sw=4 sts=4 15 | -------------------------------------------------------------------------------- /test/py/funcs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | def a(): 4 | print 'infunc' 5 | 6 | def b(a,b): 7 | print a+b 8 | 9 | def c(*d): 10 | print d,len(d) 11 | 12 | def e(*a, **e): 13 | print a, e 14 | 15 | print a.__name__, b.__name__, c.__name__, e.__name__ 16 | 17 | a() 18 | b(3,4) 19 | c(1,2,5,6) 20 | a() 21 | e(2,3,r=5) 22 | 23 | def defaults(man='me'): 24 | print man, 7 25 | 26 | defaults() 27 | defaults(89) 28 | 29 | def everything(a, b=2, *c, **d): 30 | print a, b 31 | print c, d 32 | 33 | everything(2,3,4) 34 | everything('ho') 35 | everything(1, one=2) 36 | everything(4,5,6,7,8,y=3) 37 | 38 | # vim: et sw=4 sts=4 39 | -------------------------------------------------------------------------------- /test/py/globals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | x = 3 4 | 5 | def a(): 6 | x = 4 7 | print x 8 | 9 | def b(): 10 | global x 11 | x = 5 12 | 13 | print x 14 | a() 15 | print x 16 | b() 17 | print x 18 | 19 | 20 | # vim: et sw=4 sts=4 21 | -------------------------------------------------------------------------------- /test/py/imports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import toimp 4 | import toimp 5 | 6 | print __name__ 7 | 8 | if __name__ == '__main__': 9 | print 23 10 | else: 11 | print 32 12 | 13 | # vim: et sw=4 sts=4 14 | -------------------------------------------------------------------------------- /test/py/inheritence.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class a(object): 4 | def a(self):print 'a.a' 5 | def b(self):print 'a.b' 6 | def c(self):print 'a.c' 7 | def d(self):print 'a.d' 8 | 9 | class b(a): 10 | def b(self):print 'b.b' 11 | def c(self):print 'b.c' 12 | 13 | class c(a): 14 | def d(self):print 'c.d' 15 | 16 | class d(c, b): 17 | def c(self):print 'd.c' 18 | 19 | e = d() 20 | e.a() 21 | e.b() 22 | e.c() 23 | e.d() 24 | 25 | ''' 26 | class a(object): 27 | def b(self): 28 | print 'a.b!' 29 | 30 | class b(a): 31 | def a(self): 32 | print 'b.a!' 33 | 34 | def b(self): 35 | print '!b.b' 36 | 37 | class c(b): 38 | def c(self): 39 | print 'c.c!' 40 | 41 | class d(a): 42 | def e(self): 43 | print 'e.d!' 44 | 45 | class e(c,d): 46 | def e(self): 47 | print 'e.e' 48 | 49 | a().b() 50 | b().a() 51 | b().b() 52 | c().a() 53 | c().b() 54 | c().c() 55 | 56 | e().a() 57 | e().c() 58 | e().e() 59 | ''' 60 | 61 | 62 | # vim: et sw=4 sts=4 63 | -------------------------------------------------------------------------------- /test/py/lcomp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print [x for x in range(5)] 4 | print [y for y in xrange(10) for x in range(2)] 5 | 6 | for nm in [(x,y,z) for x in range(3) for y in range(2) for z in range(4)]: 7 | print nm 8 | if nm[0] > nm[1]: 9 | print 'grear' 10 | 11 | print [x for x in range(10) if x%2==0] 12 | print [(x,y,z) for x in range(10) if x%2 == 0 for y in range(10) if y%2 == 1 for z in range(2)] 13 | 14 | 15 | # vim: et sw=4 sts=4 16 | -------------------------------------------------------------------------------- /test/py/loops.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print 'hello' 4 | x = [1,2,3] 5 | for i in x: 6 | print i 7 | 8 | y = range(20) 9 | for c in y: 10 | print c%5 11 | 12 | mult = [[1,2],[3,4],[5,6]] 13 | 14 | for a,b in mult: 15 | print a+b 16 | 17 | for x in range(10): 18 | if x>3: 19 | break 20 | print x 21 | 22 | for a in range(20): 23 | if a%3==0: 24 | continue 25 | print a 26 | 27 | r = 20 28 | while r>0: 29 | print r*2 30 | r -= 2 31 | 32 | 33 | # vim: et sw=4 sts=4 34 | -------------------------------------------------------------------------------- /test/py/math.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print 2+3 4 | print 4-2 5 | 6 | # vim: et sw=4 sts=4 7 | -------------------------------------------------------------------------------- /test/py/more_imports.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sub import vbl 4 | import sub.smod 5 | from sub import smod 6 | print vbl 7 | print smod.__name__ 8 | 9 | 10 | # vim: et sw=4 sts=4 11 | -------------------------------------------------------------------------------- /test/py/moreclass.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | '''here's a docstring for this module 4 | and it's multi-line''' 5 | 6 | class Bar: 7 | cattr = 'something' 8 | def __init__(self, a, b): 9 | print 'args', a, b 10 | 11 | @staticmethod 12 | def staticm(one, *alls): 13 | print 'from static', one, alls 14 | 15 | def bar(self, **baz): 16 | print 'bar_bar', baz 17 | 18 | def __str__(self): 19 | return '' 20 | 21 | def __repr__(self): 22 | return str(self) 23 | 24 | if __name__ == '__main__': 25 | Bar(3,4).bar(a=5,c='hoo') 26 | Bar.staticm(5,6,7,'i'); 27 | else: 28 | a=2 29 | foo(1,2,3,4,5,6) 30 | bar(r=5,t='man') 31 | print 'notmain' 32 | 33 | 34 | # vim: et sw=4 sts=4 35 | -------------------------------------------------------------------------------- /test/py/numbers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print 1+2 4 | print 3/2 5 | print 3.0/2 6 | print 1.0/2 7 | print 1/2.0 8 | print 1/2 9 | print int(1.0/2) 10 | print int(float(3)), int(4 + float(3)/2) 11 | 12 | 13 | # vim: et sw=4 sts=4 14 | -------------------------------------------------------------------------------- /test/py/ops.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print 2==3 4 | print 2!=3 5 | print 2>3 6 | print 2<3 7 | print 2<=3 8 | print 2>=3 9 | 10 | print 1<2<3 11 | print 1==2==3 12 | print 1==1==1+1-1 13 | print 2!=3!=4 14 | 15 | print 'a'=='a' 16 | print 'a'=='b' 17 | print 'a'!='a' 18 | print 'a'!='b' 19 | 20 | 21 | # vim: et sw=4 sts=4 22 | -------------------------------------------------------------------------------- /test/py/scope.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | a = 1 4 | 5 | def b(): 6 | c = 2 7 | def d(g): 8 | print g, c, a, e 9 | d(45) 10 | 11 | e = 4 12 | 13 | b() 14 | 15 | # vim: et sw=4 sts=4 16 | -------------------------------------------------------------------------------- /test/py/several_inherit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class a(object): 4 | def a(self):print 'a.a' 5 | 6 | class b(object): 7 | def a(self):print 'b.a' 8 | 9 | class c(object): 10 | def a(self):print 'c.a' 11 | 12 | class x(a):pass 13 | x().a() 14 | class y(a,b):pass 15 | y().a() 16 | class z(a,b,c):pass 17 | z().a() 18 | class e(c):pass 19 | e().a() 20 | class f(c,b):pass 21 | f().a() 22 | class g(c,b,a):pass 23 | g().a() 24 | 25 | class a(object): 26 | def a(self):print 'a.a' 27 | def b(self):print 'a.b' 28 | class b(object): 29 | def b(self):print 'b.b' 30 | class c(a,b):pass 31 | c().a() 32 | c().b() 33 | class d(b,a):pass 34 | d().a() 35 | d().b() 36 | 37 | # vim: et sw=4 sts=4 38 | -------------------------------------------------------------------------------- /test/py/simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print 'module initialized' 4 | print __name__ 5 | 6 | # vim: et sw=4 sts=4 7 | -------------------------------------------------------------------------------- /test/py/slice.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | a = [1,23,4] + range(5,15) 4 | print a 5 | print a[2] 6 | print a[:3] 7 | print range(20)[::5] 8 | print a[-2] 9 | print a[-2:] 10 | print a[:2] 11 | print a[:-2] 12 | print a[-5:-1] 13 | print a[1:-5:2] 14 | 15 | 16 | # vim: et sw=4 sts=4 17 | -------------------------------------------------------------------------------- /test/py/small_scope.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class A:pass 4 | b = A 5 | a = A() 6 | a.a = 3 7 | print a.a 8 | 9 | # vim: et sw=4 sts=4 10 | -------------------------------------------------------------------------------- /test/py/strings.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | s = 'some string' 4 | print s 5 | t = "double_quote" + 'concat' 6 | print t,t.split('_'); 7 | u = '''triple 8 | quoted 9 | 10 | string 11 | ''' 12 | print s.title() 13 | print s.upper() 14 | print s.upper().lower() 15 | 16 | # vim: et sw=4 sts=4 17 | -------------------------------------------------------------------------------- /test/py/sub/__init__.py: -------------------------------------------------------------------------------- 1 | vbl = 34 2 | -------------------------------------------------------------------------------- /test/py/sub/smod.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/test/py/sub/smod.py -------------------------------------------------------------------------------- /test/py/toimp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | '''this is a module to bge imported''' 4 | 5 | thevalue = 20 6 | 7 | import imports 8 | 9 | print type('some') == str 10 | 11 | print __name__ 12 | 13 | 14 | 15 | # vim: et sw=4 sts=4 16 | -------------------------------------------------------------------------------- /test/py/undef.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print '{:undef:a::}' 4 | print 'ha' 5 | 6 | 7 | # vim: et sw=4 sts=4 8 | -------------------------------------------------------------------------------- /test/py/xrange.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | print list(xrange(5)) 4 | a = xrange(4) 5 | for b in a: 6 | print b 7 | print list(a) 8 | print list(a) 9 | 10 | 11 | # vim: et sw=4 sts=4 12 | -------------------------------------------------------------------------------- /test/py2js/basic/assign_slice.py: -------------------------------------------------------------------------------- 1 | 2 | a = [1,2,3,4,5,6,7] 3 | 4 | a[4:6] = ['a','b'] 5 | 6 | def show(x): 7 | print "----" 8 | for x in a: 9 | print x 10 | 11 | show(a) 12 | 13 | 14 | a[2:4] = ['z'] 15 | 16 | show(a) 17 | 18 | a[0:2] = ['abc','def','abc','def'] 19 | 20 | show(a) 21 | -------------------------------------------------------------------------------- /test/py2js/basic/augassign.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1 3 | a += 1 4 | print a 5 | a += 3 6 | print a 7 | a -= 2 8 | print a 9 | -------------------------------------------------------------------------------- /test/py2js/basic/augassign2.py: -------------------------------------------------------------------------------- 1 | def f1(x): 2 | return x 3 | 4 | def f2(x): 5 | return x + 5 6 | 7 | def f3(x): 8 | a = x + 1 9 | return a - 5 10 | 11 | def f3b(x): 12 | a = x + 1 13 | a -= 5 14 | return a 15 | 16 | def f3c(x): 17 | a = float(x) + 1 18 | a /= 5 19 | return a 20 | 21 | def f3d(x): 22 | a = x + 1 23 | a *= 5 24 | return a 25 | 26 | def f3e(x): 27 | a = x + 1 28 | a += 5 29 | return a 30 | 31 | def f4(x): 32 | if x: 33 | return 5 34 | else: 35 | return 6 36 | 37 | def f5(x): 38 | a = 1 39 | if x: 40 | a = a + 1 41 | else: 42 | a = a - 1 43 | return a 44 | 45 | print f1(3) 46 | print f2(3) 47 | print f3(3) 48 | print f3b(3) 49 | print f3c(3) 50 | print f3d(3) 51 | print f3e(3) 52 | print f4(True) 53 | print f4(False) 54 | print f5(True) 55 | print f5(False) 56 | -------------------------------------------------------------------------------- /test/py2js/basic/binaryops.py: -------------------------------------------------------------------------------- 1 | 2 | x = 1 3 | y = 2 4 | z = 3 5 | 6 | print 10 % z 7 | print y*x 8 | print y-z 9 | print y+x+z 10 | print 10 / 2 11 | print 10 ** 2 12 | -------------------------------------------------------------------------------- /test/py2js/basic/break.py: -------------------------------------------------------------------------------- 1 | 2 | x = 0 3 | 4 | while True: 5 | x = x + 1 6 | print x 7 | if x > 10: 8 | break 9 | -------------------------------------------------------------------------------- /test/py2js/basic/class.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class foobar(object): 4 | 5 | x = 1 6 | 7 | def __init__(self): 8 | self.foovar = 1 9 | 10 | def foo(self,x): 11 | self.foovar = self.foovar + x 12 | 13 | def bar(self): 14 | print self.foovar 15 | 16 | f = foobar() 17 | f.bar() 18 | f.foo(1) 19 | f.foo(2) 20 | f.bar() 21 | f.bar() 22 | f.foo(-1) 23 | f.bar() 24 | f.foo(7) 25 | f.bar() 26 | 27 | 28 | -------------------------------------------------------------------------------- /test/py2js/basic/class2.py: -------------------------------------------------------------------------------- 1 | class Class1(object): 2 | 3 | def __init__(self): 4 | pass 5 | 6 | def test1(self): 7 | return 5 8 | 9 | class Class2(object): 10 | 11 | def test1(self): 12 | return 6 13 | 14 | class Class3(object): 15 | 16 | def test1(self, x): 17 | return self.test2(x)-1 18 | 19 | def test2(self, x): 20 | return 2*x 21 | 22 | a = Class1() 23 | print a.test1() 24 | 25 | a = Class2() 26 | print a.test1() 27 | 28 | a = Class3() 29 | print a.test1(3) 30 | print a.test2(3) 31 | -------------------------------------------------------------------------------- /test/py2js/basic/closure.py: -------------------------------------------------------------------------------- 1 | 2 | def factory(x): 3 | 4 | def fn(): 5 | return x 6 | 7 | return fn 8 | 9 | a1 = factory("foo") 10 | a2 = factory("bar") 11 | print a1() 12 | print a2() 13 | -------------------------------------------------------------------------------- /test/py2js/basic/continue.py: -------------------------------------------------------------------------------- 1 | 2 | for x in xrange(0,20): 3 | if x > 10 and x < 17: 4 | continue 5 | print x 6 | -------------------------------------------------------------------------------- /test/py2js/basic/default.py: -------------------------------------------------------------------------------- 1 | g = 99 2 | 3 | def f(a, b=1, c="default c", d=g): 4 | print a 5 | print b 6 | print c 7 | print d 8 | 9 | f(0) 10 | f(0, 77) 11 | f(0, 77, "hello") 12 | -------------------------------------------------------------------------------- /test/py2js/basic/del_array.py: -------------------------------------------------------------------------------- 1 | 2 | mylist = [1,2,3,4,5] 3 | 4 | del mylist[3] 5 | 6 | for x in xrange(0,len(mylist)): 7 | print mylist[x] 8 | -------------------------------------------------------------------------------- /test/py2js/basic/del_attr.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class spam: 4 | 5 | def __init__(self): 6 | self.eggs = 0 7 | 8 | def addegg(self): 9 | try: 10 | if self.eggs: 11 | self.eggs += 1 12 | else: 13 | self.eggs = 1 14 | except: 15 | self.eggs = 1 16 | 17 | def printit(self): 18 | try: 19 | if self.eggs: 20 | print self.eggs 21 | else: 22 | print "no eggs" 23 | except: 24 | print "no eggs" 25 | 26 | 27 | s = spam() 28 | s.addegg() 29 | s.addegg() 30 | s.printit() 31 | s.addegg() 32 | s.printit() 33 | del s.eggs 34 | s.printit() 35 | s.addegg() 36 | s.addegg() 37 | s.printit() 38 | -------------------------------------------------------------------------------- /test/py2js/basic/del_dict.py: -------------------------------------------------------------------------------- 1 | 2 | mydict = {} 3 | 4 | mydict["abc"] = "def" 5 | mydict["def"] = "abc" 6 | mydict["xyz"] = "rst" 7 | 8 | print mydict["abc"] 9 | print mydict["def"] 10 | print mydict["xyz"] 11 | 12 | del mydict["def"] 13 | 14 | if "abc" in mydict: 15 | print "abc in mydict" 16 | else: 17 | print "abc not in mydict" 18 | 19 | if "def" in mydict: 20 | print "def in mydict" 21 | else: 22 | print "def not in mydict" 23 | 24 | if "xyz" in mydict: 25 | print "xyz in mydict" 26 | else: 27 | print "xyz not in mydict" 28 | -------------------------------------------------------------------------------- /test/py2js/basic/del_global.py: -------------------------------------------------------------------------------- 1 | 2 | x = 1 3 | 4 | def foo(): 5 | global x 6 | del x 7 | 8 | print x 9 | 10 | foo() 11 | 12 | try: 13 | print x 14 | except: 15 | print "x is gone" 16 | -------------------------------------------------------------------------------- /test/py2js/basic/del_local.py: -------------------------------------------------------------------------------- 1 | 2 | x = "ABC" 3 | 4 | print x 5 | 6 | del x 7 | 8 | try: 9 | print x 10 | except: 11 | print "x is gone" 12 | -------------------------------------------------------------------------------- /test/py2js/basic/del_slice.py: -------------------------------------------------------------------------------- 1 | 2 | mylist = [1,2,3,4,5] 3 | myother = range(10) 4 | 5 | del mylist[1:3] 6 | del myother[[1][0]:3] 7 | del myother[7] 8 | 9 | for x in xrange(0,len(mylist)): 10 | print mylist[x] 11 | for x in xrange(0,len(myother)): 12 | print myother[x] 13 | -------------------------------------------------------------------------------- /test/py2js/basic/dictionary.py: -------------------------------------------------------------------------------- 1 | 2 | foo = { 'a':'b', 'c':'d' } 3 | 4 | print foo['a'] 5 | print foo['c'] 6 | 7 | if 'a' in foo: 8 | print "a in foo" 9 | -------------------------------------------------------------------------------- /test/py2js/basic/dictionary2.py: -------------------------------------------------------------------------------- 1 | def dict1(): 2 | a = {1: 3, "s": 4} 3 | return len(a) 4 | 5 | def dict2(): 6 | a = {1: 3, "s": 4} 7 | b = a[1] + a["s"] 8 | return b 9 | 10 | def dict3(): 11 | a = {} 12 | a[1] = 3 13 | a["s"] = 4 14 | b = a[1] + a["s"] 15 | return b 16 | 17 | print dict1() 18 | print dict2() 19 | print dict3() 20 | -------------------------------------------------------------------------------- /test/py2js/basic/docstring.py: -------------------------------------------------------------------------------- 1 | 2 | class myclass(object): 3 | 4 | """This is a class that really says something""" 5 | 6 | def __init__(self,msg): 7 | self.msg = msg 8 | 9 | def saysomething(self): 10 | print self.msg 11 | 12 | m = myclass("hello") 13 | 14 | m.saysomething() 15 | -------------------------------------------------------------------------------- /test/py2js/basic/embedding.py: -------------------------------------------------------------------------------- 1 | """py2js-verbatim: 2 | function foo(x) { 3 | print(x); 4 | } 5 | """ 6 | 7 | """py2js-skip-begin""" 8 | def foo(x): 9 | print x 10 | """py2js-skip-end""" 11 | 12 | foo('bar') 13 | -------------------------------------------------------------------------------- /test/py2js/basic/fib.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def fib(x): 5 | if x == 1: 6 | return x 7 | else: 8 | return x*fib(x-1) 9 | 10 | print fib(4) 11 | -------------------------------------------------------------------------------- /test/py2js/basic/float2int.py: -------------------------------------------------------------------------------- 1 | 2 | for f in [123.456,1.1,-0.00045,-1.45,1.5,1022423.22]: 3 | i = int(f) 4 | print i 5 | -------------------------------------------------------------------------------- /test/py2js/basic/for_in.py: -------------------------------------------------------------------------------- 1 | # iterating over a list 2 | a = [1,2,3,4,5] 3 | for x in a: 4 | print x 5 | 6 | # iterating over a tuple 7 | a = ('cats','dogs','squirrels') 8 | for x in a: 9 | print x 10 | 11 | # iterating over a dictionary 12 | # sort order in python is undefined, so need to sort the results 13 | # explictly before comparing output 14 | 15 | a = {'a':1,'b':2,'c':3 } 16 | 17 | keys = [] 18 | for x in a: 19 | keys.append(x) 20 | 21 | keys.sort() 22 | for k in keys: 23 | print k 24 | 25 | # iterating over a string 26 | a = 'defabc' 27 | for x in a: 28 | print x 29 | 30 | -------------------------------------------------------------------------------- /test/py2js/basic/for_step.py: -------------------------------------------------------------------------------- 1 | 2 | for x in xrange(19,342,13): 3 | print x 4 | -------------------------------------------------------------------------------- /test/py2js/basic/for_xrange.py: -------------------------------------------------------------------------------- 1 | 2 | for x in xrange(1,10): 3 | print x 4 | -------------------------------------------------------------------------------- /test/py2js/basic/generator.py: -------------------------------------------------------------------------------- 1 | 2 | class generator: 3 | 4 | class iterator: 5 | def __init__(self,parent): 6 | self.parent = parent 7 | self.value = parent.min 8 | 9 | def next(self): 10 | val = self.value 11 | if val > self.parent.max: 12 | raise StopIteration 13 | self.value += 1 14 | return val 15 | 16 | def __init__(self,min,max): 17 | self.min = min 18 | self.max = max 19 | 20 | def __iter__(self): 21 | return self.iterator(self) 22 | 23 | g = generator(5,10) 24 | for v in g: 25 | print v 26 | -------------------------------------------------------------------------------- /test/py2js/basic/globalvar.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a = "spam" 4 | b = "eggs" 5 | 6 | print a 7 | print b 8 | -------------------------------------------------------------------------------- /test/py2js/basic/helloworld.py: -------------------------------------------------------------------------------- 1 | 2 | print('hello') 3 | print('hello world') 4 | -------------------------------------------------------------------------------- /test/py2js/basic/ifs.py: -------------------------------------------------------------------------------- 1 | def ifs1(x): 2 | a = 1 3 | if x: 4 | a = a + 1 5 | a *= 2 6 | else: 7 | a = a - 1 8 | a *= 4 9 | return a 10 | 11 | def ifs2(x): 12 | a = 1 13 | if x > 0: 14 | a = a + 1 15 | a *= 2 16 | else: 17 | a = a - 1 18 | a *= 4 19 | return a 20 | 21 | def ifs3(x): 22 | a = 1 23 | if x > 0: 24 | if x > 10: 25 | a = 3 26 | else: 27 | a = 4 28 | a = 5 29 | return a 30 | 31 | def ifs4(x): 32 | a = 1 33 | if x > 0: 34 | if x > 10: 35 | a = 3 36 | else: 37 | a = 4 38 | else: 39 | a = 5 40 | return a 41 | 42 | print ifs1(True) 43 | print ifs1(False) 44 | print ifs2(1) 45 | print ifs2(-1) 46 | print ifs3(1) 47 | print ifs3(20) 48 | print ifs3(-1) 49 | print ifs4(1) 50 | print ifs4(20) 51 | print ifs4(-1) 52 | -------------------------------------------------------------------------------- /test/py2js/basic/keys.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | x = { 'foo':'bar','aaa':'bbb','xyz':'zyx','spam':'eggs' } 4 | 5 | s = x.keys() 6 | s.sort() 7 | for k in s: 8 | print k + " -> " + x[k] 9 | -------------------------------------------------------------------------------- /test/py2js/basic/kwargs.py: -------------------------------------------------------------------------------- 1 | def myfunc(a, b, *c, **d): 2 | print a 3 | print b 4 | for i in c: 5 | print i 6 | keys = d.keys() 7 | keys.sort() 8 | for i in keys: 9 | print i 10 | print d[i] 11 | 12 | myfunc(1, 2, bar='a', foo='c') 13 | print 14 | myfunc(1, 2, 3, 4, bar='a', foo='c') 15 | -------------------------------------------------------------------------------- /test/py2js/basic/kwargs2.py: -------------------------------------------------------------------------------- 1 | def myfunc(a, b=3, c=4): 2 | print a 3 | print b 4 | print c 5 | print 6 | 7 | myfunc(1) 8 | myfunc(1, 2) 9 | myfunc(1, 2, 3) 10 | myfunc(1, c=3, b=4) 11 | myfunc(1, b=4) 12 | -------------------------------------------------------------------------------- /test/py2js/basic/lambda.py: -------------------------------------------------------------------------------- 1 | 2 | y = lambda x:x*x 3 | 4 | print y(4) 5 | 6 | -------------------------------------------------------------------------------- /test/py2js/basic/list.py: -------------------------------------------------------------------------------- 1 | 2 | x = [1,2,3,'a','b','c'] 3 | y = x[2:4] 4 | print x[0] 5 | print x[3] 6 | print y[0] 7 | print y[1] 8 | -------------------------------------------------------------------------------- /test/py2js/basic/list2.py: -------------------------------------------------------------------------------- 1 | def list1(n): 2 | a = [] 3 | a.append(1) 4 | a.append(2) 5 | a.append(3) 6 | a.append(n) 7 | return a[0] + a[1] + a[2] + a[3] 8 | 9 | def list2(): 10 | a = list(range(5)) 11 | return str(a) 12 | 13 | def list3(): 14 | a = list(range(5)) 15 | a[0] = 5 16 | a[4] = 0 17 | return str(a) 18 | 19 | def list4(): 20 | a = [8, 9, 10, 11, 12, 13, 14] 21 | return a[2:4] 22 | 23 | def list5(): 24 | a = [8, 9, 10, 11, 12, 13, 14] 25 | return a[:4] 26 | 27 | def list6(): 28 | a = [8, 9, 10, 11, 12, 13, 14] 29 | return a[1:6:2] 30 | 31 | def list7(): 32 | a = [8, 9, 10, 11, 12, 13, 14] 33 | return a[:] 34 | 35 | def list8(): 36 | a = [8, 9, 10, 11, 12, 13, 14] 37 | return a[4:] 38 | 39 | print list1(4) 40 | print list1(5) 41 | print list2() 42 | print list3() 43 | print list4() 44 | print list5() 45 | print list6() 46 | print list7() 47 | print list8() 48 | -------------------------------------------------------------------------------- /test/py2js/basic/listcomp2.py: -------------------------------------------------------------------------------- 1 | 2 | for (x,y,z) in [(x,y,z) for x in xrange(0,3) for y in xrange(0,4) for z in xrange(0,5)]: 3 | print x,y,z 4 | if x < y < z: 5 | print x,y,z,"x y: 8 | print "x > y - incorrect" 9 | else: 10 | print "not x > y - correct" 11 | 12 | if y >= y2: 13 | print "y >= y2 - correct" 14 | else: 15 | print "not y >= y2 - incorrect" 16 | 17 | if z > x: 18 | print "z > x - correct" 19 | else: 20 | print "not z > x - incorrect" 21 | 22 | if y >= z: 23 | print "y >= z - incorrect" 24 | else: 25 | print "not y >= x - correct" 26 | 27 | -------------------------------------------------------------------------------- /test/py2js/functions/in.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a = { 1:'aaa', 'b':2 } 4 | 5 | if 2 in a: 6 | print "2 in a - incorrect" 7 | 8 | if 'b' in a: 9 | print "b in a - correct" 10 | 11 | if 1 in a: 12 | print "1 in a - correct" 13 | 14 | if 3 not in a: 15 | print "3 not in a - correct" 16 | 17 | if 'x' not in a: 18 | print "x not in a - correct" 19 | -------------------------------------------------------------------------------- /test/py2js/functions/int.py: -------------------------------------------------------------------------------- 1 | 2 | x = '123' 3 | y = int(x) 4 | print y 5 | -------------------------------------------------------------------------------- /test/py2js/functions/isinstance.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/functions/isinstance.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/functions/isinstance.py', function (_) { 9 | _.__doc__ = ""; 10 | _.Spam = Class('Spam', [$b.object], (function(){ 11 | var __0 = {}; 12 | __0.__init__ = $def(function $___init__(self, value) { // 4 13 | self.value = value; 14 | }); 15 | __0.__init__.__module__ = _.__name__; 16 | __0.__init__.__name__ = $b.str("__init__"); 17 | return __0; 18 | }())); 19 | _.Spam.__module__ = _.__name__; 20 | _.Eggs = Class('Eggs', [$b.object], (function(){ 21 | var __0 = {}; 22 | __0.__init__ = $def(function $___init__(self, value) { // 9 23 | self.value = value; 24 | }); 25 | __0.__init__.__module__ = _.__name__; 26 | __0.__init__.__name__ = $b.str("__init__"); 27 | return __0; 28 | }())); 29 | _.Eggs.__module__ = _.__name__; 30 | _.s = _.Spam(1); 31 | _.e = _.Eggs(2); 32 | if ($b.bool($b.isinstance(_.s, _.Spam)) === true) { 33 | $b.print($b.str('s is Spam - correct'));//, true 34 | } 35 | if ($b.bool($b.isinstance(_.s, _.Eggs)) === true) { 36 | $b.print($b.str('s is Eggs - incorrect'));//, true 37 | } 38 | if ($b.bool($b.isinstance(_.e, _.Spam)) === true) { 39 | $b.print($b.str('e is Spam - incorrect'));//, true 40 | } 41 | if ($b.bool($b.isinstance(_.e, _.Eggs)) === true) { 42 | $b.print($b.str('e is Eggs - correct'));//, true 43 | } 44 | }); 45 | 46 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 47 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/functions/isinstance.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 48 | 49 | -------------------------------------------------------------------------------- /test/py2js/functions/isinstance.py: -------------------------------------------------------------------------------- 1 | 2 | class Spam(object): 3 | 4 | def __init__(self,value): 5 | self.value = value 6 | 7 | class Eggs(object): 8 | 9 | def __init__(self,value): 10 | self.value = value 11 | 12 | s = Spam(1) 13 | e = Eggs(2) 14 | 15 | if isinstance(s,Spam): 16 | print "s is Spam - correct" 17 | 18 | if isinstance(s,Eggs): 19 | print "s is Eggs - incorrect" 20 | 21 | if isinstance(e,Spam): 22 | print "e is Spam - incorrect" 23 | 24 | if isinstance(e,Eggs): 25 | print "e is Eggs - correct" 26 | 27 | -------------------------------------------------------------------------------- /test/py2js/functions/len.py: -------------------------------------------------------------------------------- 1 | 2 | mylist = [1,2,3] 3 | 4 | print len(mylist) 5 | -------------------------------------------------------------------------------- /test/py2js/functions/lshift.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/functions/lshift.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/functions/lshift.py', function (_) { 9 | _.__doc__ = ""; 10 | _.x = 10; 11 | _.y = $b.lshift(_.x, 3); 12 | _.x = $b.lshift(_.x, 3); 13 | $b.print(_.x, _.y);//, true 14 | }); 15 | 16 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 17 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/functions/lshift.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 18 | 19 | -------------------------------------------------------------------------------- /test/py2js/functions/lshift.py: -------------------------------------------------------------------------------- 1 | 2 | x = 10 3 | y = x << 3 4 | x <<= 3 5 | print x,y 6 | -------------------------------------------------------------------------------- /test/py2js/functions/ltle.py: -------------------------------------------------------------------------------- 1 | 2 | x = 123 3 | y = 233 4 | y2 = 233 5 | z = 892 6 | 7 | if x < y: 8 | print "x < y - correct" 9 | else: 10 | print "not x < y - incorrect" 11 | 12 | if y <= y2: 13 | print "y <= y2 - correct" 14 | else: 15 | print "not y <= y2 - incorrect" 16 | 17 | if z < x: 18 | print "z < x - incorrect" 19 | else: 20 | print "not z < x - correct" 21 | 22 | if y <= z: 23 | print "y <= z - correct" 24 | else: 25 | print "not y <= x - incorrect" 26 | 27 | -------------------------------------------------------------------------------- /test/py2js/functions/ne.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | for (x,y) in [(1,2),('aaa','bbb'),(4,4),('a','a')]: 4 | if x <> y: 5 | print str(x)+" <> "+str(y) 6 | else: 7 | print "not: " + str(x)+" <> "+str(y) 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/py2js/functions/or.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/functions/or.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/functions/or.py', function (_) { 9 | _.__doc__ = ""; 10 | _.tests = $b.list([$b.tuple([$b.False, $b.False]), $b.tuple([$b.False, $b.True]), $b.tuple([$b.True, $b.False]), $b.tuple([$b.True, $b.True]), $b.tuple([$b.True, $b.None]), $b.tuple([$b.False, $b.None]), $b.tuple([$b.None, $b.True]), $b.tuple([$b.None, $b.False])]); 11 | _.pp = $def(function $_pp(v) { // 4 12 | if ($b.bool($b.do_ops(v, '==', $b.False)) === true) { 13 | return $b.str('F'); 14 | } 15 | if ($b.bool($b.do_ops(v, '==', $b.True)) === true) { 16 | return $b.str('T'); 17 | } 18 | return $b.str('?'); 19 | }); 20 | _.pp.__module__ = _.__name__; 21 | _.pp.__name__ = $b.str("pp"); 22 | var __pjs_iter_1 = $b.foriter(_.tests); 23 | while (__pjs_iter_1.trynext()) { 24 | _.t = __pjs_iter_1.value; 25 | 26 | var __pjs_tmp = _.t; 27 | _.b1 = __pjs_tmp.__getitem__(0); 28 | _.b2 = __pjs_tmp.__getitem__(1); 29 | $b.print($b.add($b.add($b.add($b.add(_.pp(_.b1), $b.str(' OR ')), _.pp(_.b2)), $b.str('=')), _.pp($b.bool(_.b1) || $b.bool(_.b2))));//, true 30 | } 31 | }); 32 | 33 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 34 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/functions/or.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 35 | 36 | -------------------------------------------------------------------------------- /test/py2js/functions/or.py: -------------------------------------------------------------------------------- 1 | 2 | tests = [(False,False),(False,True),(True,False),(True,True),(True,None),(False,None),(None,True),(None,False)] 3 | 4 | def pp(v): 5 | if v == False: 6 | return "F" 7 | if v == True: 8 | return "T" 9 | return "?" 10 | 11 | for t in tests: 12 | (b1,b2) = t 13 | print pp(b1) + " OR " + pp(b2) + "=" + pp(b1 or b2) 14 | -------------------------------------------------------------------------------- /test/py2js/functions/pop.py: -------------------------------------------------------------------------------- 1 | 2 | a = [1,2,3,4] 3 | 4 | print a.pop() 5 | 6 | -------------------------------------------------------------------------------- /test/py2js/functions/rshift.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/functions/rshift.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/functions/rshift.py', function (_) { 9 | _.__doc__ = ""; 10 | _.x = 345; 11 | _.y = $b.rshift(_.x, 7); 12 | _.x = $b.rshift(_.x, 7); 13 | $b.print(_.x, _.y);//, true 14 | }); 15 | 16 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 17 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/functions/rshift.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 18 | 19 | -------------------------------------------------------------------------------- /test/py2js/functions/rshift.py: -------------------------------------------------------------------------------- 1 | 2 | x = 345 3 | y = x >> 7 4 | x >>= 7 5 | print x,y 6 | -------------------------------------------------------------------------------- /test/py2js/functions/sort.py: -------------------------------------------------------------------------------- 1 | 2 | l = [3,2,1] 3 | 4 | l.sort() 5 | 6 | print l[0] 7 | print l[1] 8 | print l[2] 9 | -------------------------------------------------------------------------------- /test/py2js/functions/sort23.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/functions/sort23.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/functions/sort23.py', function (_) { 9 | _.__doc__ = ""; 10 | _.getkey = $def(function $_getkey(x) { // 2 11 | if ($b.bool($b.do_ops(x, '<', 5)) === true) { 12 | return $b.add(x, 10); 13 | } else return x; 14 | }); 15 | _.getkey.__module__ = _.__name__; 16 | _.getkey.__name__ = $b.str("getkey"); 17 | _.revcmp = $def(function $_revcmp(a, b) { // 8 18 | if ($b.bool($b.do_ops(b, '<', a)) === true) { 19 | return -1; 20 | } 21 | if ($b.bool($b.do_ops(b, '==', a)) === true) { 22 | return 0; 23 | } 24 | return 1; 25 | }); 26 | _.revcmp.__module__ = _.__name__; 27 | _.revcmp.__name__ = $b.str("revcmp"); 28 | _.l = $b.list([4, 7, 2, 3, 8, 1, 3]); 29 | _.l.sort(_.revcmp, _.getkey); 30 | $b.print(_.l.__getitem__(0));//, true 31 | $b.print(_.l.__getitem__(1));//, true 32 | $b.print(_.l.__getitem__(2));//, true 33 | $b.print($b.str('---'));//, true 34 | _.l.sort(_.revcmp, _.getkey, $b.True); 35 | $b.print(_.l.__getitem__(0));//, true 36 | $b.print(_.l.__getitem__(1));//, true 37 | $b.print(_.l.__getitem__(2));//, true 38 | }); 39 | 40 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 41 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/functions/sort23.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 42 | 43 | -------------------------------------------------------------------------------- /test/py2js/functions/sort23.py: -------------------------------------------------------------------------------- 1 | 2 | def getkey(x): 3 | if x < 5: 4 | return x + 10 5 | else: 6 | return x 7 | 8 | def revcmp(a,b): 9 | if b 0: 52 | XmlWriter.indent(writer,indent) 53 | writer.write("<"+self.tag) 54 | for k in self.attributes: 55 | writer.write(" "+k+'="'+self.attributes[k]+'"') 56 | if len(self.children) == 0: 57 | writer.write(" />") 58 | return 59 | writer.write(">") 60 | for c in self.children: 61 | c.write(writer,indent+1) 62 | if not self.hastext: 63 | XmlWriter.indent(writer,indent) 64 | writer.write("") 65 | 66 | @staticmethod 67 | def indent(writer,indent): 68 | writer.write("\n") 69 | for x in xrange(0,indent): 70 | writer.write(" ") 71 | 72 | def createRoot(self,tag): 73 | self.root = self.Element(tag) 74 | return self.root 75 | 76 | def write(self,writer): 77 | self.root.write(writer,0) 78 | 79 | 80 | if __name__ == '__main__': 81 | w = XmlWriter() 82 | r = w.createRoot("foo") 83 | r1 = r.addElement("r1") 84 | r1.addAttribute("spam","eggs") 85 | r2 = r1.addElement("r2") 86 | r2.addAttribute("eggs","spam") 87 | r2.addTextNode("This is some text") 88 | s = StringWriter() 89 | w.write(s) 90 | print s.getContents() 91 | 92 | -------------------------------------------------------------------------------- /test/py2js/lists/extend.py: -------------------------------------------------------------------------------- 1 | 2 | list1 = [1,2,'f',44] 3 | list2 = ['a',99,77] 4 | 5 | list3 = list1[:] 6 | list3.extend(list2) 7 | 8 | for item in list3: 9 | print item 10 | -------------------------------------------------------------------------------- /test/py2js/lists/filter.py: -------------------------------------------------------------------------------- 1 | 2 | l = [1,2,3,4,5,6,7,8,8] 3 | 4 | l2 = filter(lambda x:x>4,l) 5 | 6 | for v in l2: 7 | print v 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/py2js/lists/in.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | l = ['a','b','c'] 4 | 5 | def intest(item,list): 6 | if item in list: 7 | print str(item) + ' is in list' 8 | else: 9 | print str(item) + ' is not in list' 10 | 11 | 12 | intest('a',l) 13 | intest('b',l) 14 | intest(99,l) 15 | intest(0,l) 16 | intest('z',l) 17 | intest('c',l) 18 | 19 | 20 | -------------------------------------------------------------------------------- /test/py2js/lists/insert.py: -------------------------------------------------------------------------------- 1 | a = [] 2 | a.insert(0, 1) 3 | print a 4 | a.insert(0, 2) 5 | print a 6 | a.insert(0, 3) 7 | print a 8 | a.insert(1, 4) 9 | print a 10 | a.insert(2, 5) 11 | print a 12 | a.insert(5, 6) 13 | print a 14 | -------------------------------------------------------------------------------- /test/py2js/lists/map.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(x): 3 | return x*x 4 | 5 | y = [1,2,3,4,5] 6 | 7 | z = map(foo,y) 8 | for val in z: 9 | print val 10 | -------------------------------------------------------------------------------- /test/py2js/lists/max.py: -------------------------------------------------------------------------------- 1 | 2 | l = [4,7,3,4,2,1] 3 | 4 | v = max(l) 5 | 6 | print v 7 | -------------------------------------------------------------------------------- /test/py2js/lists/min.py: -------------------------------------------------------------------------------- 1 | 2 | l = [4,7,3,4,2,1] 3 | 4 | v = min(l) 5 | 6 | print v 7 | -------------------------------------------------------------------------------- /test/py2js/lists/reduce.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(x,y): 3 | return x*y 4 | 5 | y = [1,2,3,4,5] 6 | 7 | z = reduce(foo,y,10) 8 | print z 9 | z = reduce(foo,y) 10 | print z 11 | -------------------------------------------------------------------------------- /test/py2js/lists/reverse.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3, 4] 2 | a.reverse() 3 | print a 4 | -------------------------------------------------------------------------------- /test/py2js/lists/subclass.py: -------------------------------------------------------------------------------- 1 | class A(list): 2 | 3 | def my_append(self, a): 4 | self.append(a) 5 | 6 | a = A() 7 | print a 8 | a.append(5) 9 | print a 10 | a.append(6) 11 | print a 12 | a.remove(5) 13 | print a 14 | -------------------------------------------------------------------------------- /test/py2js/lists/subclass2.py: -------------------------------------------------------------------------------- 1 | class List(object): 2 | 3 | def __init__(self, l=[]): 4 | self._list = list(l) 5 | 6 | def append(self, x): 7 | self._list.append(x) 8 | 9 | def remove(self, x): 10 | self._list.remove(x) 11 | 12 | def __str__(self): 13 | return str(self._list) 14 | 15 | class A(List): 16 | 17 | def my_append(self, a): 18 | self.append(a) 19 | 20 | a = A() 21 | print a 22 | a.append(5) 23 | print a 24 | a.append(6) 25 | print a 26 | a.remove(5) 27 | print a 28 | -------------------------------------------------------------------------------- /test/py2js/lists/subclass3.py: -------------------------------------------------------------------------------- 1 | class List(object): 2 | 3 | def __init__(self, l=[]): 4 | self._list = list(l) 5 | 6 | def append(self, x): 7 | self._list.append(x) 8 | 9 | def remove(self, x): 10 | self._list.remove(x) 11 | 12 | def __str__(self): 13 | return str(self._list) 14 | 15 | class Layer(List): 16 | pass 17 | 18 | l1 = Layer() 19 | l1.append(1) 20 | l1.append(2) 21 | l2 = list() 22 | l2.append(3) 23 | l2.append(4) 24 | print l1 25 | print l2 26 | -------------------------------------------------------------------------------- /test/py2js/lists/sum.py: -------------------------------------------------------------------------------- 1 | 2 | s = [1,2,3,4,5] 3 | t = sum(s) 4 | u = sum([x*x for x in s]) 5 | print t,u 6 | -------------------------------------------------------------------------------- /test/py2js/lists/sum2.py: -------------------------------------------------------------------------------- 1 | s = [1,2,3,4,5] 2 | print sum(s) 3 | 4 | print sum([1, 8, 11]) 5 | 6 | print sum((1, 8, 11)) 7 | -------------------------------------------------------------------------------- /test/py2js/lists/xrange.py: -------------------------------------------------------------------------------- 1 | 2 | xr = xrange(20,40) 3 | 4 | for x in xr: 5 | print x 6 | -------------------------------------------------------------------------------- /test/py2js/lists/zip.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | l1 = [1,2,3,4,5] 4 | l2 = [5,4,3,2,1] 5 | l3 = [4,4,4,4] 6 | 7 | l4 = zip(l1,l2,l3) 8 | 9 | for item in l4: 10 | print "---" 11 | for val in item: 12 | print val 13 | -------------------------------------------------------------------------------- /test/py2js/modules/classname.py: -------------------------------------------------------------------------------- 1 | 2 | from modules.moda import ModA 3 | 4 | m = ModA('hello') 5 | m.describe() 6 | 7 | mc = m.clone() 8 | mc.describe() 9 | -------------------------------------------------------------------------------- /test/py2js/modules/from_import.py: -------------------------------------------------------------------------------- 1 | 2 | from imported.modulea import modulea_fn 3 | from imported.moduleb import moduleb_fn as modb_fn 4 | from imported.modulec import * 5 | 6 | modulea_fn() 7 | modb_fn() 8 | foo() 9 | -------------------------------------------------------------------------------- /test/py2js/modules/import.py: -------------------------------------------------------------------------------- 1 | 2 | from imported.modulea import * 3 | import imported.moduleb 4 | 5 | modulea_fn() 6 | imported.moduleb.moduleb_fn() 7 | 8 | ma = modulea_class() 9 | print ma.msg(1) 10 | 11 | mb = imported.moduleb.moduleb_class() 12 | print mb.msg(2) 13 | -------------------------------------------------------------------------------- /test/py2js/modules/import_alias.py: -------------------------------------------------------------------------------- 1 | 2 | from imported.alias_fns import foo as bar 3 | from imported.alias_classes import spam as eggs 4 | 5 | # call imported function 6 | bar() 7 | 8 | # call imported class 9 | e = eggs() 10 | e.msg() 11 | 12 | 13 | -------------------------------------------------------------------------------- /test/py2js/modules/import_class.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import modules.klasses 4 | 5 | k = modules.klasses.klass() 6 | 7 | k.sayhello() 8 | modules.klasses.klass.sayhello() 9 | 10 | -------------------------------------------------------------------------------- /test/py2js/modules/import_diamond.py: -------------------------------------------------------------------------------- 1 | 2 | import modules.diamond1 3 | import modules.diamond2 4 | 5 | modules.diamond1.run() 6 | modules.diamond2.run() 7 | 8 | -------------------------------------------------------------------------------- /test/py2js/modules/import_global.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/test/py2js/modules/import_global.js -------------------------------------------------------------------------------- /test/py2js/modules/import_global.py: -------------------------------------------------------------------------------- 1 | 2 | import imported.moduleb 3 | import imported.moduled 4 | 5 | imported.moduleb.moduleb_fn() 6 | imported.moduled.moduled_fn() 7 | -------------------------------------------------------------------------------- /test/py2js/modules/import_multi.py: -------------------------------------------------------------------------------- 1 | 2 | import imported.modulec 3 | 4 | def foo(): 5 | print "foo" 6 | imported.modulec.foo() 7 | 8 | foo() 9 | -------------------------------------------------------------------------------- /test/py2js/modules/imported/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/test/py2js/modules/imported/__init__.py -------------------------------------------------------------------------------- /test/py2js/modules/imported/alias_classes.py: -------------------------------------------------------------------------------- 1 | 2 | class spam: 3 | 4 | def __init__(self): 5 | self.msgtxt = "this is spam" 6 | 7 | def msg(self): 8 | print self.msgtxt 9 | 10 | if __name__ == '__main__': 11 | s = spam() 12 | s.msg() 13 | -------------------------------------------------------------------------------- /test/py2js/modules/imported/alias_fns.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | print "this is foo" 4 | 5 | 6 | -------------------------------------------------------------------------------- /test/py2js/modules/imported/modulea.py: -------------------------------------------------------------------------------- 1 | 2 | def modulea_fn(): 3 | 4 | print "import_modulea.modulea_fn()" 5 | 6 | class modulea_class(object): 7 | 8 | def __init__(self): 9 | pass 10 | 11 | def msg(self,val): 12 | return "modulea_class:"+str(val) 13 | -------------------------------------------------------------------------------- /test/py2js/modules/imported/moduleb.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | print "foo" 4 | 5 | def moduleb_fn(): 6 | print "import_moduleb.moduleb_fn()" 7 | 8 | class moduleb_class(object): 9 | 10 | def __init__(self): 11 | pass 12 | 13 | def msg(self,val): 14 | return "moduleb_class:"+str(val) 15 | -------------------------------------------------------------------------------- /test/py2js/modules/imported/modulec.py: -------------------------------------------------------------------------------- 1 | 2 | import submodules.submodulea 3 | 4 | def foo(): 5 | print "imported.modulec.foo()" 6 | submodules.submodulea.foo() 7 | -------------------------------------------------------------------------------- /test/py2js/modules/imported/moduled.py: -------------------------------------------------------------------------------- 1 | 2 | import imported.modulea 3 | 4 | def moduled_fn(): 5 | print "import_moduled.moduled_fn()" 6 | print "calling module a now..." 7 | imported.modulea.modulea_fn() 8 | -------------------------------------------------------------------------------- /test/py2js/modules/imported/submodules/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/test/py2js/modules/imported/submodules/__init__.py -------------------------------------------------------------------------------- /test/py2js/modules/imported/submodules/submodulea.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | print "imported.modules.submodules.modulea.foo()" 4 | -------------------------------------------------------------------------------- /test/py2js/modules/module_name.py: -------------------------------------------------------------------------------- 1 | 2 | import modules.module_name 3 | 4 | print "1st level module __name__:"+__name__ 5 | -------------------------------------------------------------------------------- /test/py2js/modules/modules/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/test/py2js/modules/modules/__init__.py -------------------------------------------------------------------------------- /test/py2js/modules/modules/diamond1.py: -------------------------------------------------------------------------------- 1 | 2 | import submodules.diamondbase 3 | 4 | def run(): 5 | print "calling diamond1.run()" 6 | submodules.diamondbase.run() 7 | -------------------------------------------------------------------------------- /test/py2js/modules/modules/diamond2.py: -------------------------------------------------------------------------------- 1 | 2 | import submodules.diamondbase 3 | 4 | def run(): 5 | print "Calling diamond2.run()" 6 | submodules.diamondbase.run() 7 | -------------------------------------------------------------------------------- /test/py2js/modules/modules/klasses.py: -------------------------------------------------------------------------------- 1 | 2 | class baseklass(object): 3 | 4 | @staticmethod 5 | def sayhello(): 6 | print "baseklass says hello" 7 | 8 | class klass(baseklass): 9 | 10 | pass 11 | 12 | 13 | if __name__ == '__main__': 14 | 15 | k = klass() 16 | k.sayhello() 17 | klass.sayhello() 18 | baseklass.sayhello() 19 | -------------------------------------------------------------------------------- /test/py2js/modules/modules/moda.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class ModA: 4 | 5 | def __init__(self,val): 6 | self.val = val 7 | 8 | def clone(self): 9 | return ModA(self.val) 10 | 11 | def describe(self): 12 | print self.val 13 | -------------------------------------------------------------------------------- /test/py2js/modules/modules/module_name.py: -------------------------------------------------------------------------------- 1 | 2 | import submodules.module_name 3 | 4 | print "2nd level module __name__:"+__name__ 5 | -------------------------------------------------------------------------------- /test/py2js/modules/modules/submodules/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/test/py2js/modules/modules/submodules/__init__.py -------------------------------------------------------------------------------- /test/py2js/modules/modules/submodules/diamondbase.py: -------------------------------------------------------------------------------- 1 | 2 | counter = 0 3 | 4 | def run(): 5 | global counter 6 | counter += 1 7 | print "diamondbase called " + str(counter) + " time(s)" 8 | -------------------------------------------------------------------------------- /test/py2js/modules/modules/submodules/module_name.py: -------------------------------------------------------------------------------- 1 | 2 | print "3rd level module __name__:"+__name__ 3 | -------------------------------------------------------------------------------- /test/py2js/modules/rng.py: -------------------------------------------------------------------------------- 1 | 2 | from mtrandom import * 3 | 4 | def float2str(v,dp): 5 | s = str(v) 6 | dotpos = s.find(".") 7 | if dotpos >= 0: 8 | return s[:dotpos+dp+1] 9 | return s 10 | 11 | class RNG: 12 | def __init__(self): 13 | init = [0x123, 0x234, 0x345, 0x456] 14 | self.r = MersenneTwister() 15 | self.r.init_by_array(init,4) 16 | 17 | def next(self): 18 | return self.r.genrand_res53() 19 | 20 | if __name__ == "__main__": 21 | r = RNG() 22 | print float2str(r.next(),9) 23 | print float2str(r.next(),9) 24 | print float2str(r.next(),9) 25 | 26 | -------------------------------------------------------------------------------- /test/py2js/strings/count.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/count.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/count.py', function (_) { 9 | _.__doc__ = ""; 10 | _.txt = $b.str('the quick brown fox jumped over the lazy dogthe'); 11 | _.c = _.txt.count($b.str('the')); 12 | $b.print(_.c);//, true 13 | _.c = _.txt.count($b.str('the'), 0, -20); 14 | $b.print(_.c);//, true 15 | _.c = _.txt.count($b.str('the'), 3); 16 | $b.print(_.c);//, true 17 | _.c = _.txt.count($b.str('the'), 4, 15); 18 | $b.print(_.c);//, true 19 | _.c = _.txt.count($b.str('the'), 1, $b.len(_.txt)); 20 | $b.print(_.c);//, true 21 | _.c = _.txt.count($b.str('the'), 4, $b.sub($b.len(_.txt), 1)); 22 | $b.print(_.c);//, true 23 | }); 24 | 25 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 26 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/count.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 27 | 28 | -------------------------------------------------------------------------------- /test/py2js/strings/count.py: -------------------------------------------------------------------------------- 1 | 2 | txt = "the quick brown fox jumped over the lazy dogthe" 3 | 4 | c = txt.count("the") 5 | print c 6 | c = txt.count("the",0,-20) 7 | print c 8 | c = txt.count("the",3) 9 | print c 10 | c = txt.count("the",4,15) 11 | print c 12 | c = txt.count("the",1,len(txt)) 13 | print c 14 | c = txt.count("the",4,len(txt)-1) 15 | print c 16 | -------------------------------------------------------------------------------- /test/py2js/strings/find.py: -------------------------------------------------------------------------------- 1 | 2 | s = "the quick brown fox" 3 | i = s.find("quick") 4 | print str(i) 5 | i = s.find("dog") 6 | print str(i) 7 | i = s.find("the") 8 | print str(i) 9 | -------------------------------------------------------------------------------- /test/py2js/strings/join.py: -------------------------------------------------------------------------------- 1 | a = ["a", "b", "c"] 2 | print "".join(a) 3 | print " ".join(a) 4 | print "x".join(a) 5 | print "x ".join(a) 6 | -------------------------------------------------------------------------------- /test/py2js/strings/lstrip0.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/lstrip0.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/lstrip0.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s1 = $b.str('\n' + 11 | '\n' + 12 | 'abc\n' + 13 | '\n' + 14 | '\n' + 15 | ''); 16 | _.s2 = $b.str('\t abc\n' + 17 | '\t \n' + 18 | ''); 19 | _.s3 = $b.str(' abc '); 20 | var __pjs_iter_1 = $b.foriter($b.list([_.s1, _.s2, _.s3])); 21 | while (__pjs_iter_1.trynext()) { 22 | _.s = __pjs_iter_1.value; 23 | 24 | $b.print($b.add($b.add($b.str('original('), _.s), $b.str(')')));//, true 25 | $b.print($b.add($b.add($b.str('strip('), _.s.lstrip()), $b.str(')')));//, true 26 | } 27 | }); 28 | 29 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 30 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/lstrip0.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 31 | 32 | -------------------------------------------------------------------------------- /test/py2js/strings/lstrip0.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s1 = "\n\nabc\n\n\n" 4 | s2 = "\t abc\n\t \n" 5 | s3 = " abc " 6 | 7 | for s in [s1,s2,s3]: 8 | print "original("+s+")" 9 | print "strip("+s.lstrip()+")" 10 | -------------------------------------------------------------------------------- /test/py2js/strings/lstrip1.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/lstrip1.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/lstrip1.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s = $b.str('abcxyz'); 11 | $b.print($b.add($b.add($b.str('original('), _.s), $b.str(')')));//, true 12 | $b.print($b.add($b.add($b.str('strip('), _.s.lstrip($b.str('cba'))), $b.str(')')));//, true 13 | }); 14 | 15 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 16 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/lstrip1.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 17 | 18 | -------------------------------------------------------------------------------- /test/py2js/strings/lstrip1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = "abcxyz" 4 | 5 | print "original("+s+")" 6 | print "strip("+s.lstrip("cba")+")" 7 | -------------------------------------------------------------------------------- /test/py2js/strings/replace.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/replace.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/replace.py', function (_) { 9 | _.__doc__ = ""; 10 | _.txt = $b.str('the quick brown fox jumped over thethe lazy dog'); 11 | _.txt2 = _.txt.replace($b.str('the'), $b.str('a')); 12 | $b.print(_.txt);//, true 13 | $b.print(_.txt2);//, true 14 | $b.print(_.txt.replace($b.str('the'), $b.str('a'), 0));//, true 15 | $b.print(_.txt.replace($b.str('the'), $b.str('a'), 1));//, true 16 | $b.print(_.txt.replace($b.str('the'), $b.str('a'), 2));//, true 17 | $b.print(_.txt.replace($b.str('the'), $b.str('a'), 3));//, true 18 | $b.print(_.txt.replace($b.str('the'), $b.str('a'), 4));//, true 19 | $b.print(_.txt.replace($b.str('the'), $b.str('a'), 50));//, true 20 | }); 21 | 22 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 23 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/replace.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 24 | 25 | -------------------------------------------------------------------------------- /test/py2js/strings/replace.py: -------------------------------------------------------------------------------- 1 | 2 | txt = "the quick brown fox jumped over thethe lazy dog" 3 | 4 | txt2 = txt.replace("the","a") 5 | 6 | print txt 7 | print txt2 8 | 9 | print txt.replace("the", "a", 0) 10 | print txt.replace("the", "a", 1) 11 | print txt.replace("the", "a", 2) 12 | print txt.replace("the", "a", 3) 13 | print txt.replace("the", "a", 4) 14 | print txt.replace("the", "a", 50) 15 | -------------------------------------------------------------------------------- /test/py2js/strings/rfind.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/rfind.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/rfind.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s = $b.str('the quick brown quick the fox'); 11 | _.i = _.s.rfind($b.str('quick')); 12 | $b.print($b.str(_.i));//, true 13 | _.i = _.s.rfind($b.str('dog')); 14 | $b.print($b.str(_.i));//, true 15 | _.i = _.s.rfind($b.str('the')); 16 | $b.print($b.str(_.i));//, true 17 | }); 18 | 19 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 20 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/rfind.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 21 | 22 | -------------------------------------------------------------------------------- /test/py2js/strings/rfind.py: -------------------------------------------------------------------------------- 1 | 2 | s = "the quick brown quick the fox" 3 | i = s.rfind("quick") 4 | print str(i) 5 | i = s.rfind("dog") 6 | print str(i) 7 | i = s.rfind("the") 8 | print str(i) 9 | -------------------------------------------------------------------------------- /test/py2js/strings/rstrip0.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/rstrip0.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/rstrip0.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s1 = $b.str('abc\n' + 11 | '\n' + 12 | '\n' + 13 | ''); 14 | _.s2 = $b.str('abc\n' + 15 | '\t \n' + 16 | ''); 17 | _.s3 = $b.str('abc '); 18 | var __pjs_iter_1 = $b.foriter($b.list([_.s1, _.s2, _.s3])); 19 | while (__pjs_iter_1.trynext()) { 20 | _.s = __pjs_iter_1.value; 21 | 22 | $b.print($b.add($b.add($b.str('original('), _.s), $b.str(')')));//, true 23 | $b.print($b.add($b.add($b.str('strip('), _.s.rstrip()), $b.str(')')));//, true 24 | } 25 | }); 26 | 27 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 28 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/rstrip0.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 29 | 30 | -------------------------------------------------------------------------------- /test/py2js/strings/rstrip0.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s1 = "abc\n\n\n" 4 | s2 = "abc\n\t \n" 5 | s3 = "abc " 6 | 7 | for s in [s1,s2,s3]: 8 | print "original("+s+")" 9 | print "strip("+s.rstrip()+")" 10 | -------------------------------------------------------------------------------- /test/py2js/strings/rstrip1.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/rstrip1.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/rstrip1.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s = $b.str('abcxyz'); 11 | $b.print($b.add($b.add($b.str('original('), _.s), $b.str(')')));//, true 12 | $b.print($b.add($b.add($b.str('strip('), _.s.rstrip($b.str('yzx'))), $b.str(')')));//, true 13 | }); 14 | 15 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 16 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/rstrip1.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 17 | 18 | -------------------------------------------------------------------------------- /test/py2js/strings/rstrip1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = "abcxyz" 4 | 5 | print "original("+s+")" 6 | print "strip("+s.rstrip("yzx")+")" 7 | -------------------------------------------------------------------------------- /test/py2js/strings/split.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/split.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/split.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s = $b.str('the quick brown fox jumped over the lazy dog'); 11 | _.t = _.s.split($b.str(' ')); 12 | var __pjs_iter_1 = $b.foriter(_.t); 13 | while (__pjs_iter_1.trynext()) { 14 | _.v = __pjs_iter_1.value; 15 | 16 | $b.print(_.v);//, true 17 | } 18 | _.r = _.s.split($b.str('e')); 19 | var __pjs_iter_1 = $b.foriter(_.r); 20 | while (__pjs_iter_1.trynext()) { 21 | _.v = __pjs_iter_1.value; 22 | 23 | $b.print(_.v);//, true 24 | } 25 | _.x = _.s.split(); 26 | var __pjs_iter_1 = $b.foriter(_.x); 27 | while (__pjs_iter_1.trynext()) { 28 | _.v = __pjs_iter_1.value; 29 | 30 | $b.print(_.v);//, true 31 | } 32 | }); 33 | 34 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 35 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/split.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 36 | 37 | -------------------------------------------------------------------------------- /test/py2js/strings/split.py: -------------------------------------------------------------------------------- 1 | 2 | s="the quick brown fox jumped over the lazy dog" 3 | t = s.split(" ") 4 | for v in t: 5 | print v 6 | r = s.split("e") 7 | for v in r: 8 | print v 9 | x = s.split() 10 | for v in x: 11 | print v 12 | 13 | # 2-arg version of split not supported 14 | # y = s.split(" ",7) 15 | # for v in y: 16 | # print v 17 | -------------------------------------------------------------------------------- /test/py2js/strings/splitlines.py: -------------------------------------------------------------------------------- 1 | 2 | txt = """ 3 | aaa 4 | 5 | bcfdss 6 | 7 | sdsd 8 | wqarwqr 9 | 10 | 11 | werewr""" 12 | 13 | lines = txt.splitlines() 14 | 15 | for line in lines: 16 | print line 17 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_d.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/string_format_d.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/string_format_d.py', function (_) { 9 | _.__doc__ = ""; 10 | _.a = $b._float(1.123456); 11 | _.b = 10; 12 | _.c = -30; 13 | _.d = 34; 14 | _.e = $b._float(123.456); 15 | _.f = 19892122; 16 | _.s = $b.mod($b.str('b=%d'), _.b); 17 | $b.print(_.s);//, true 18 | _.s = $b.mod($b.str('b,c,d=%d+%d+%d'), $b.tuple([_.b, _.c, _.d])); 19 | $b.print(_.s);//, true 20 | _.s = $b.mod($b.str('b=%(b)0d and c=%(c)d and d=%(d)d'), $b.dict([[$b.str('b'), _.b], [$b.str('c'), _.c], [$b.str('d'), _.d]])); 21 | $b.print(_.s);//, true 22 | _.s = $b.mod($b.str('e=%020d e=%+d e=%20d e=%-20d (e=%- 20d)'), $b.tuple([_.e, _.e, _.e, _.e, _.e])); 23 | $b.print(_.s);//, true 24 | }); 25 | 26 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 27 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/string_format_d.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 28 | 29 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_d.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 10 4 | c = -30 5 | d = 34 6 | e = 123.456 7 | f = 19892122 8 | 9 | # form 0 10 | s = "b=%d" % b 11 | print s 12 | 13 | # form 1 14 | s = "b,c,d=%d+%d+%d" % (b,c,d) 15 | print s 16 | 17 | # form 2 18 | s = "b=%(b)0d and c=%(c)d and d=%(d)d" % { 'b':b,'c':c,'d':d } 19 | print s 20 | 21 | # width,flags 22 | s = "e=%020d e=%+d e=%20d e=%-20d (e=%- 20d)" % (e,e,e,e,e) 23 | print s 24 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_efg.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/string_format_efg.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/string_format_efg.py', function (_) { 9 | _.__doc__ = ""; 10 | _.a = $b._float(1.123456); 11 | _.b = $b._float(3.24324e-10); 12 | _.c = $b._float(18347894.2131); 13 | _.d = $b._float(0.0); 14 | _.e = $b._float(-1324323.456); 15 | _.f = $b._float(-1.9892122e-11); 16 | _.vars = $b.list([_.a, _.b, _.c, _.d, _.e, _.f]); 17 | _.codes = $b.list([$b.str('e'), $b.str('E'), $b.str('f'), $b.str('F'), $b.str('g'), $b.str('G')]); 18 | _.fmts = $b.list([$b.str('a=%e'), $b.str('a=%10.5e'), $b.str('a=%+10.5e'), $b.str('a=%#e')]); 19 | var __pjs_iter_1 = $b.foriter(_.codes); 20 | while (__pjs_iter_1.trynext()) { 21 | _.code = __pjs_iter_1.value; 22 | 23 | var __pjs_iter_2 = $b.foriter(_.fmts); 24 | while (__pjs_iter_2.trynext()) { 25 | _.fmt = __pjs_iter_2.value; 26 | 27 | _.fmt = _.fmt.replace($b.str('e'), _.code); 28 | var __pjs_iter_3 = $b.foriter(_.vars); 29 | while (__pjs_iter_3.trynext()) { 30 | _.v = __pjs_iter_3.value; 31 | 32 | $b.print($b.add(_.fmt, $b.str(':')), $b.mod(_.fmt, _.v));//, true 33 | } 34 | } 35 | } 36 | }); 37 | 38 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 39 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/string_format_efg.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 40 | 41 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_efg.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 0.000000000324324 4 | c = 18347894.213123 5 | d = 0.0 6 | e = -1324323.456 7 | f = -0.000000000019892122 8 | 9 | vars = [a,b,c,d,e,f] 10 | codes = ['e','E','f','F','g','G'] 11 | 12 | fmts = ["a=%e","a=%10.5e","a=%+10.5e","a=%#e"] 13 | 14 | for code in codes: 15 | for fmt in fmts: 16 | fmt = fmt.replace('e',code) 17 | for v in vars: 18 | print fmt + ":", fmt % v 19 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_i.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/string_format_i.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/string_format_i.py', function (_) { 9 | _.__doc__ = ""; 10 | _.a = $b._float(1.123456); 11 | _.b = 10; 12 | _.c = -30; 13 | _.d = 34; 14 | _.e = $b._float(123.456); 15 | _.f = 19892122; 16 | _.s = $b.mod($b.str('b=%i'), _.b); 17 | $b.print(_.s);//, true 18 | _.s = $b.mod($b.str('b,c,d=%i+%i+%i'), $b.tuple([_.b, _.c, _.d])); 19 | $b.print(_.s);//, true 20 | _.s = $b.mod($b.str('b=%(b)i and c=%(c)i and d=%(d)i'), $b.dict([[$b.str('b'), _.b], [$b.str('c'), _.c], [$b.str('d'), _.d]])); 21 | $b.print(_.s);//, true 22 | _.s = $b.mod($b.str('e=%020i e=%+i e=%20i e=%-20i (e=%- 20i)'), $b.tuple([_.e, _.e, _.e, _.e, _.e])); 23 | $b.print(_.s);//, true 24 | }); 25 | 26 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 27 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/string_format_i.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 28 | 29 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_i.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 10 4 | c = -30 5 | d = 34 6 | e = 123.456 7 | f = 19892122 8 | 9 | # form 0 10 | s = "b=%i" % b 11 | print s 12 | 13 | # form 1 14 | s = "b,c,d=%i+%i+%i" % (b,c,d) 15 | print s 16 | 17 | # form 2 18 | s = "b=%(b)i and c=%(c)i and d=%(d)i" % { 'b':b,'c':c,'d':d } 19 | print s 20 | 21 | # width,flags 22 | s = "e=%020i e=%+i e=%20i e=%-20i (e=%- 20i)" % (e,e,e,e,e) 23 | print s 24 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_o.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/string_format_o.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/string_format_o.py', function (_) { 9 | _.__doc__ = ""; 10 | _.vals = $b.list([0, 10, -30, 173247, 123, 19892122]); 11 | _.formats = $b.list([$b.str('%o'), $b.str('%020o'), $b.str('%-20o'), $b.str('%#o'), $b.str('+%o'), $b.str('+%#o')]); 12 | var __pjs_iter_1 = $b.foriter(_.vals); 13 | while (__pjs_iter_1.trynext()) { 14 | _.val = __pjs_iter_1.value; 15 | 16 | var __pjs_iter_2 = $b.foriter(_.formats); 17 | while (__pjs_iter_2.trynext()) { 18 | _.fmt = __pjs_iter_2.value; 19 | 20 | $b.print($b.add(_.fmt, $b.str(':')), $b.mod(_.fmt, _.val));//, true 21 | } 22 | } 23 | }); 24 | 25 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 26 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/string_format_o.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 27 | 28 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_o.py: -------------------------------------------------------------------------------- 1 | 2 | vals = [0,10,-30,173247,123,19892122] 3 | 4 | formats = ['%o','%020o', '%-20o', '%#o', '+%o', '+%#o'] 5 | 6 | for val in vals: 7 | for fmt in formats: 8 | print fmt+":", fmt % val 9 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_u.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/string_format_u.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/string_format_u.py', function (_) { 9 | _.__doc__ = ""; 10 | _.a = $b._float(1.123456); 11 | _.b = 10; 12 | _.c = -30; 13 | _.d = 34; 14 | _.e = $b._float(123.456); 15 | _.f = 19892122; 16 | _.s = $b.mod($b.str('b=%u'), _.b); 17 | $b.print(_.s);//, true 18 | _.s = $b.mod($b.str('b,c,d=%u+%u+%u'), $b.tuple([_.b, _.c, _.d])); 19 | $b.print(_.s);//, true 20 | _.s = $b.mod($b.str('b=%(b)0u and c=%(c)u and d=%(d)u'), $b.dict([[$b.str('b'), _.b], [$b.str('c'), _.c], [$b.str('d'), _.d]])); 21 | $b.print(_.s);//, true 22 | _.s = $b.mod($b.str('e=%020u e=%+u e=%20u e=%-20u (e=%- 20u)'), $b.tuple([_.e, _.e, _.e, _.e, _.e])); 23 | $b.print(_.s);//, true 24 | }); 25 | 26 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 27 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/string_format_u.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 28 | 29 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_u.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 10 4 | c = -30 5 | d = 34 6 | e = 123.456 7 | f = 19892122 8 | 9 | # form 0 10 | s = "b=%u" % b 11 | print s 12 | 13 | # form 1 14 | s = "b,c,d=%u+%u+%u" % (b,c,d) 15 | print s 16 | 17 | # form 2 18 | s = "b=%(b)0u and c=%(c)u and d=%(d)u" % { 'b':b,'c':c,'d':d } 19 | print s 20 | 21 | # width,flags 22 | s = "e=%020u e=%+u e=%20u e=%-20u (e=%- 20u)" % (e,e,e,e,e) 23 | print s 24 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_x.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/string_format_x.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/string_format_x.py', function (_) { 9 | _.__doc__ = ""; 10 | _.vals = $b.list([0, 10, -30, 173247, 123, 19892122]); 11 | _.formats = $b.list([$b.str('%x'), $b.str('%020x'), $b.str('%X'), $b.str('%020X'), $b.str('%-20x'), $b.str('%#x')]); 12 | var __pjs_iter_1 = $b.foriter(_.vals); 13 | while (__pjs_iter_1.trynext()) { 14 | _.val = __pjs_iter_1.value; 15 | 16 | var __pjs_iter_2 = $b.foriter(_.formats); 17 | while (__pjs_iter_2.trynext()) { 18 | _.fmt = __pjs_iter_2.value; 19 | 20 | $b.print($b.add(_.fmt, $b.str(':')), $b.mod(_.fmt, _.val));//, true 21 | } 22 | } 23 | }); 24 | 25 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 26 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/string_format_x.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 27 | 28 | -------------------------------------------------------------------------------- /test/py2js/strings/string_format_x.py: -------------------------------------------------------------------------------- 1 | 2 | vals = [0,10,-30,173247,123,19892122] 3 | 4 | formats = ['%x','%020x','%X', '%020X', '%-20x', '%#x'] 5 | 6 | for val in vals: 7 | for fmt in formats: 8 | print fmt+":", fmt % val 9 | -------------------------------------------------------------------------------- /test/py2js/strings/strip.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/strip.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/strip.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s1 = $b.str('\n' + 11 | '\n' + 12 | 'abc\n' + 13 | '\n' + 14 | '\n' + 15 | ''); 16 | _.s2 = $b.str('\t abc\n' + 17 | '\t \n' + 18 | ''); 19 | _.s3 = $b.str(' abc '); 20 | var __pjs_iter_1 = $b.foriter($b.list([_.s1, _.s2, _.s3])); 21 | while (__pjs_iter_1.trynext()) { 22 | _.s = __pjs_iter_1.value; 23 | 24 | $b.print($b.add($b.add($b.str('original('), _.s), $b.str(')')));//, true 25 | $b.print($b.add($b.add($b.str('strip('), _.s.strip()), $b.str(')')));//, true 26 | } 27 | }); 28 | 29 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 30 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/strip.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 31 | 32 | -------------------------------------------------------------------------------- /test/py2js/strings/strip.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s1 = "\n\nabc\n\n\n" 4 | s2 = "\t abc\n\t \n" 5 | s3 = " abc " 6 | 7 | for s in [s1,s2,s3]: 8 | print "original("+s+")" 9 | print "strip("+s.strip()+")" 10 | -------------------------------------------------------------------------------- /test/py2js/strings/strip1.js: -------------------------------------------------------------------------------- 1 | /*** File generated by PJs http://jaredforsyth.com/projects/pjs ***/ 2 | 3 | // from source file /Users/jared/clone/PJs/test/py2js/strings/strip1.py 4 | 5 | load("pjs/data/pjslib.js"); 6 | var console = {log:function(){print.apply(this, arguments);}}; 7 | var window = this; 8 | module('/Users/jared/clone/PJs/test/py2js/strings/strip1.py', function (_) { 9 | _.__doc__ = ""; 10 | _.s = $b.str('yxabcxyz'); 11 | $b.print($b.add($b.add($b.str('original('), _.s), $b.str(')')));//, true 12 | $b.print($b.add($b.add($b.str('strip('), _.s.strip($b.str('yzx'))), $b.str(')')));//, true 13 | }); 14 | 15 | __builtins__.__import__('sys').argv = __builtins__.list(arguments); 16 | var pjs_main = __builtins__.run_main('/Users/jared/clone/PJs/test/py2js/strings/strip1.py', ['/Users/jared/clone/PJs', '/Users/jared/.venv/default/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/pip-1.3-py2.7.egg', '/Users/jared/.venv/default/lib/python2.7/site-packages/readline-6.2.4.1-py2.7-macosx-10.7-intel.egg', '/Users/jared/.venv/default/lib/python27.zip', '/Users/jared/.venv/default/lib/python2.7', '/Users/jared/.venv/default/lib/python2.7/plat-darwin', '/Users/jared/.venv/default/lib/python2.7/plat-mac', '/Users/jared/.venv/default/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/Extras/lib/python', '/Users/jared/.venv/default/lib/python2.7/lib-tk', '/Users/jared/.venv/default/lib/python2.7/lib-old', '/Users/jared/.venv/default/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/jared/.venv/default/lib/python2.7/site-packages']); 17 | 18 | -------------------------------------------------------------------------------- /test/py2js/strings/strip1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = "yxabcxyz" 4 | 5 | print "original("+s+")" 6 | print "strip("+s.strip("yzx")+")" 7 | -------------------------------------------------------------------------------- /test/py2js/strings/ulcase.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | str = "aBcddEzUh" 4 | 5 | print str 6 | str = str.upper() 7 | print str 8 | str = str.lower() 9 | print str 10 | -------------------------------------------------------------------------------- /test/py2js/strings/ulcase1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a = "aBcddEzUh" 4 | 5 | print a 6 | a = a.upper() 7 | print a 8 | a = a.lower() 9 | print a 10 | -------------------------------------------------------------------------------- /test/py2js/strings/zipstring.py: -------------------------------------------------------------------------------- 1 | 2 | s1 = "hello" 3 | s2 = "world" 4 | s3 = "abcd" 5 | 6 | s4 = zip(s1,s2,s3) 7 | 8 | for item in s4: 9 | print "----" 10 | for val in item: 11 | print val 12 | -------------------------------------------------------------------------------- /test/py2js/test_compile_js.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jaredly/PJs/4aaae6f56217247d90deee2cbc77f2ab8216fe5f/test/py2js/test_compile_js.js -------------------------------------------------------------------------------- /test/runtests.js: -------------------------------------------------------------------------------- 1 | var window = {}; 2 | load("pjs/data/pjslib.js"); 3 | 4 | load('test/js/jasmine/lib/jasmine-0.10.3.js'); 5 | 6 | load('test/js/lib.js'); 7 | 8 | var jasmineEnv = jasmine.getEnv(); 9 | jasmineEnv.reporter = new jasmine.Reporter(); 10 | jasmineEnv.execute(); 11 | --------------------------------------------------------------------------------