├── .gitignore ├── .travis.yml ├── COPYING ├── README.md ├── deploy-docs.sh ├── doc ├── getting_started.md ├── index.md ├── js_backend.md ├── lists.md ├── markdown_format.md ├── memory.md ├── quick_start.md ├── seastar.md └── syntax.md ├── examples ├── c++ │ ├── array_generics.md │ ├── array_slice.md │ ├── async_channels.md │ ├── call_c_from_c++.md │ ├── cyclic_weakptr.md │ ├── fails_bad_order.md │ ├── hello_civetweb.md │ ├── hello_dpdk.md │ ├── hello_sdl.md │ ├── hello_seastar.md │ ├── macro_templates.md │ ├── namespaces.md │ ├── seastar_capture_syntax.md │ ├── seastar_do_with.md │ ├── seastar_future.md │ ├── seastar_semaphore.md │ ├── seastar_sleep.md │ ├── std_move.md │ ├── subclass_from_c++.md │ ├── unreal_blueprint.md │ ├── unreal_cpython.md │ ├── unreal_cyclic_weakptr.md │ └── unreal_plugin.md ├── callbacks.md ├── cpython_ctypes.md ├── cpython_embed.md ├── cpython_multithreaded.md ├── cpython_numpy.md ├── cpython_pymzml.md ├── cpython_pysam.md ├── custom_syntax.md ├── cython_mandelbrot.md ├── dddom.py ├── doxygen.md ├── example-project.md ├── fullstack_nosql_onsql.md ├── hello_angular.md ├── hello_caffe.md ├── hello_coffee.md ├── hello_cpython.md ├── hello_cython.md ├── hello_elm.md ├── hello_fullstack.md ├── hello_iframe.md ├── hello_java.md ├── hello_javascript.md ├── hello_jsplumb.md ├── hello_literate_unicode.md ├── hello_nim.md ├── hello_nuitka.md ├── hello_nw_gyp.md ├── hello_openlayers.md ├── hello_osv.md ├── hello_peerjs.md ├── hello_rapydscript.md ├── hello_threejs.md ├── helloworld.py ├── import_markdown.md ├── index.md ├── java │ ├── giws_jython.md │ ├── giws_subclass.md │ ├── java_giws.md │ └── nim_java.md ├── javascript_classes.md ├── javascript_debugger.md ├── javascript_gotchas.md ├── javascript_redefine_function.md ├── javascript_sleep.md ├── javascript_static_types.md ├── javascript_syntax.md ├── javascript_timeout_loops.md ├── javascript_timeout_webworkers.md ├── javascript_typed_dict.md ├── javascript_webworkers.md ├── javascript_webworkers_advanced.md ├── javascript_webworkers_classes.md ├── javascript_webworkers_transferable_bidirectional.md ├── javascript_webworkers_transferable_objects.md ├── jsplumb_simple.md ├── mylib │ ├── mylib_A.md │ └── mylib_B.md ├── nim_threadpool.md ├── nodejs_file.md ├── nodejs_subprocess.md ├── nodejs_tornado.md ├── nuitka_nim.md ├── numba.md ├── operator_overloading.md ├── osv_raise_rebuild.md ├── rust │ └── async_channels_rust.md ├── simple_callback.md ├── simple_class.md ├── simple_subclass.md ├── string.md ├── threejs_catmullclark.md ├── threejs_midi.md ├── threejs_static_types.md ├── threejs_webglcss3d_simple_editor.md └── visjs_shadows.md ├── install.sh ├── make-linux-packages.sh ├── mkdocs.yml ├── preview-docs.sh ├── pythia.py ├── regtests ├── asm │ ├── asm_hello.py │ └── asm_hello_rust.py ├── bargraph.pl ├── bench │ ├── add-opt.py │ ├── add-typed-go.py │ ├── add-typed-stack.py │ ├── add-typed.py │ ├── add.py │ ├── copy_list-typed-go.py │ ├── copy_list-typed-stack.py │ ├── copy_list-typed.py │ ├── copy_list.py │ ├── fannkuch-cython.pyx │ ├── fannkuch-typed-stack.py │ ├── fannkuch-typed.py │ ├── fannkuch.py │ ├── float-typed-stack.py │ ├── float-typed.py │ ├── float.py │ ├── mandelbrot.py │ ├── nbody.py │ ├── new_list.py │ ├── operator_overloading-typed-stack.py │ ├── operator_overloading-typed.py │ ├── operator_overloading.py │ ├── operator_overloading_functor.py │ ├── operator_overloading_nonfunctor.py │ ├── pystone-typed-stack.py │ ├── pystone-typed.py │ ├── pystone-version-typed-stack.py │ ├── pystone.py │ ├── recursive_fib-typed-go.py │ ├── recursive_fib-typed.py │ ├── recursive_fib.py │ ├── richards-typed-stack.py │ ├── richards-typed.py │ ├── richards.py │ ├── simd_float32vec.py │ ├── simd_float32x4.py │ ├── thread_collision-typed.py │ ├── thread_collision.py │ ├── thread_shared_vector-pypy.py │ ├── thread_shared_vector-typed-stack.py │ ├── thread_shared_vector-typed.py │ ├── thread_shared_vector.py │ ├── typed_int.py │ ├── untyped_int.py │ ├── webclgl_array_mult.py │ ├── webworker.py │ ├── webworker_single.py │ └── webworkers.py ├── c++ │ ├── array_methods.py │ ├── array_of_arrays.py │ ├── array_of_arrays_objects.py │ ├── array_sized.py │ ├── array_slice.py │ ├── array_slice_assignment.py │ ├── block_scope.py │ ├── chain.py │ ├── chan.py │ ├── classmethod.py │ ├── cyclic.py │ ├── cyclic_simple.py │ ├── decays_to_pointer.py │ ├── free_memory.py │ ├── generics.py │ ├── generics_array_subclasses.py │ ├── generics_subclasses.py │ ├── globals.py │ ├── if_else.py │ ├── if_none.py │ ├── let_styles.py │ ├── listcomp.py │ ├── map_types.py │ ├── math.py │ ├── named_params.py │ ├── pointers_returns_array.py │ ├── pointers_returns_array2D.py │ ├── print_classname.py │ ├── returns_array2D.py │ ├── returns_auto.py │ ├── returns_object.py │ ├── returns_subclasses.py │ ├── shared_from_this.py │ ├── stack_mode.py │ ├── subscript.py │ ├── try_except_finally.py │ ├── tuple_types.py │ ├── untyped_args.py │ └── while.py ├── calling │ ├── args.py │ ├── keyword.py │ ├── lambda.py │ ├── param_name.py │ ├── starargs.py │ ├── variable_args.py │ ├── variable_kwargs.py │ ├── variable_kwargs_class.py │ └── variable_kwargs_class_init.py ├── class │ ├── __add__.py │ ├── __call__.py │ ├── __getattr__.py │ ├── __mul__.py │ ├── attr.py │ ├── init_keyword.py │ ├── isinstance.py │ ├── mi.py │ ├── mi__getattr__.py │ ├── mi_override.py │ └── simple.py ├── dict │ ├── contains.py │ ├── dict_comprehension.py │ ├── if_empty.py │ ├── init.py │ ├── item.py │ ├── keys.py │ └── tuple_keys.py ├── exceptions │ ├── AttributeError.py │ └── KeyError.py ├── go │ ├── array_of_objects.py │ ├── arrays.py │ ├── callback_in_class.py │ ├── chan.py │ ├── class.py │ ├── func_calls.py │ ├── generics_init.py │ ├── generics_methods.py │ ├── generics_mreturns.py │ ├── generics_subclasses.py │ ├── generics_subcls_return_a_subcls.py │ ├── go_select.py │ ├── list_comprehension.py │ ├── loop_arrays.py │ ├── loop_map.py │ ├── map_comprehension.py │ ├── maps.py │ ├── nested_func.py │ ├── print.py │ ├── subclass.py │ └── vars.py ├── html │ ├── date.html │ ├── dddom.py │ ├── three_basic_geoms.html │ ├── three_catmull_clark.html │ ├── threepy.py │ ├── webgl_css3d_domshadow.html │ ├── webgl_css3d_editor.html │ ├── webgl_css3d_sandbox.html │ └── webgl_css3d_simple_editor.html ├── lang │ ├── builtins.py │ ├── equality.py │ ├── eval.py │ ├── eval_order.py │ ├── func_locals.py │ ├── if_else.py │ ├── if_not.py │ ├── importing.py │ ├── in.py │ ├── inline.py │ ├── list_passed_as_arg.py │ ├── map_passed_as_arg.py │ ├── new.py │ ├── raise.py │ ├── switch.py │ ├── try_except.py │ └── typedarrays.py ├── list │ ├── comp.py │ ├── concatenate.py │ ├── contains.py │ ├── if_empty.py │ ├── index.py │ ├── insert.py │ ├── loop.py │ ├── mul.py │ ├── neg_index.py │ ├── pop.py │ ├── range.py │ ├── remove.py │ ├── set_slice.py │ ├── setitem.py │ ├── simple.py │ ├── slice.py │ ├── slice_reverse.py │ └── sort.py ├── loop │ ├── for_else.py │ ├── for_loop.py │ ├── interval_loop.py │ ├── range.py │ ├── while.py │ ├── while_else.py │ └── yield.py ├── regtest-report-c++.md ├── regtest-report-go.md ├── regtest-report-js-calling.md ├── regtest-report-js-class.md ├── regtest-report-js-dict.md ├── regtest-report-js-lang.md ├── regtest-report-js-list.md ├── regtest-report-js-loop.md ├── regtest-report-js-set.md ├── regtest-report-js-str.md ├── regtest-report-rust.md ├── requirejs │ ├── import_p2js.py │ ├── import_threejs.py │ └── webworker_p2js.py ├── rpc │ ├── async_iter.py │ ├── attr.py │ ├── hello_server.py │ └── hello_server_as.py ├── run-benchmarks.py ├── run.py ├── rust │ ├── arrays.py │ ├── chan.py │ ├── chan_universal_style.py │ ├── ffi_hello.py │ ├── list_comp.py │ ├── multiple_inheritance.py │ ├── pointer_syntax.py │ ├── rust_select.py │ ├── simple_class.py │ ├── simple_subclass.py │ └── try.py ├── set │ └── issubset.py ├── stdlib │ ├── array.py │ ├── json.py │ ├── math_and_random.py │ └── sleep.py ├── str │ ├── basics.py │ ├── compare.py │ ├── format.py │ ├── iter.py │ ├── mul.py │ ├── replace.py │ ├── specials.py │ └── sprintf.py ├── test-all.py ├── test-c++.py ├── test-go.py ├── test-javascript.py ├── test-markdowns.py ├── test-rust.py ├── threads │ ├── args.py │ ├── call_from_worker.py │ ├── call_from_worker_blocking.py │ ├── shared_dict.py │ ├── shared_dict_coop.py │ ├── shared_list.py │ ├── shared_list_coop.py │ ├── shared_list_sleep.py │ └── simple.py └── typed │ ├── float32vec.py │ ├── float32x4.py │ ├── int.py │ └── long.py └── src ├── main.md ├── mkdocs.yml └── pythia ├── astutils.md ├── clikelang.md ├── codewriter.md ├── cppheader.md ├── cpprustbase.md ├── cpptranslator.md ├── cpython.md ├── fakestdlib.md ├── generatorbase.md ├── genmarkdown.md ├── gotranslator.md ├── index.md ├── intermediateform.md ├── jstranslator.md ├── jvm.md ├── nim.md ├── nuitka.md ├── runtime ├── builtins.py ├── builtins_core.py ├── builtins_debugger.py ├── builtins_glsl.py ├── builtins_nodejs.py ├── builtins_webworker.py ├── c++ │ ├── cpp-channel-LICENSE │ └── cpp-channel.h ├── cpp_builtins.py ├── dart_builtins.py ├── go_builtins.py ├── nodejs_tornado.py ├── osv_builtins.py ├── pythonpythonjs.py └── rust_builtins.py ├── rusttranslator.md └── typedpython.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | *~ 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | 10 | # gcc PGO 11 | *.gcda 12 | 13 | __pycache__ 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | before_install: 3 | # We need this line to have g++4.8 available in apt 4 | - sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test 5 | - sudo apt-get update -qq 6 | install: 7 | - sudo apt-get install -qq gcc-4.8 g++-4.8 8 | # We want to compile with g++ 4.8 when rather than the default g++ 9 | - sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 90 10 | - wget https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz 11 | - sudo tar -C /usr/local -xzf go1.4.2.linux-amd64.tar.gz 12 | - sudo apt-get install python-numpy 13 | 14 | language: python 15 | python: 16 | - "2.7" 17 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 18 | #install: 19 | # command to run tests, e.g. python setup.py test 20 | script: "python ./regtests/test-all.py" 21 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | "The New BSD License" 2 | 3 | Copyright (c) 2013, Amirouche Boubekki and Brett Hartshorn 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 7 | 8 | Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 9 | 10 | Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 11 | 12 | Neither the name of the Amirouche Boubekki or Brett Hartshorn nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /deploy-docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cp examples-mkdocs.yml mkdocs.yml 3 | mkdocs gh-deploy --clean 4 | cp docs-mkdocs.yml mkdocs.yml 5 | -------------------------------------------------------------------------------- /doc/getting_started.md: -------------------------------------------------------------------------------- 1 | 2 | using `pythia` command line 3 | ----------------- 4 | pythia compiles [markdown containers](markdown_format.md) into executeable packages. 5 | 6 | to build and run a markdown container file 7 | ```bash 8 | pythia mymarkdown.md 9 | ``` 10 | 11 | note: to see all the command line options run `pythia --help` 12 | 13 | 14 | output c++ and run binary 15 | ------------------------- 16 | 17 | transpile python script to c++, build and run 18 | ```bash 19 | pythia myscript.py 20 | ``` 21 | 22 | javascript backend 23 | ------------------ 24 | 25 | transpile python script to javascript, build and run in node.js 26 | ```bash 27 | pythia myscript.py --javascript 28 | ``` 29 | 30 | output simple tar container 31 | ---------------------------- 32 | 33 | build and save to a tar file 34 | ```bash 35 | pythia mymarkdown.md myoutput.tar 36 | ``` 37 | 38 | OSv 39 | ------ 40 | Pythia generates containers for `OSv` a cloud optimized operating system. 41 | 42 | http://osv.io/ 43 | 44 | use `--osv` , to package into an OSv container and run in qemu. 45 | (requires 64bit linux) 46 | ```bash 47 | pythia path/to/mymarkdown.md mybuild.tar --osv 48 | ``` 49 | 50 | installing pythia on 64bix linux 51 | -------------------------------- 52 | run `install.sh` script as root. 53 | 54 | ```bash 55 | git clone https://github.com/secureosv/pythia.git 56 | cd pythia 57 | sudo ./install.sh 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /doc/index.md: -------------------------------------------------------------------------------- 1 | pythia links 2 | ------------ 3 | * [pythia extended markdown](markdown_format.md) 4 | * [getting started](getting_started.md) 5 | * [c++ memory management](memory.md) 6 | * [lists](lists.md) 7 | -------------------------------------------------------------------------------- /doc/lists.md: -------------------------------------------------------------------------------- 1 | When transpiled to C++14 lists `[]` are converted to a vector of a single element type. In regular python you are allowed to create a list that contains different types, like: `[1, "foo", 2.2]`, this is not allowed in Pythia because the list must be translated into a C++11 vector type `std::vector` (where `T` is the element type). Lists and other container types are restricted in this way, and follows closely the [RPython language spec](http://rpython.readthedocs.org/en/latest/rpython.html#object-restrictions). 2 | 3 | invalid list 4 | ------------ 5 | lists of multiple types are not allowed 6 | ```python 7 | a = [100, "mystring", 99.9999] 8 | ``` 9 | 10 | integer list 11 | ------------ 12 | if the type of a list can be inferred from its arguments, 13 | then regular python syntax can be used to create it, 14 | otherwise the syntax `[]int(...)` must be used. 15 | 16 | ```python 17 | a = [1,2,3] 18 | b = []int() 19 | c = []int(1,2,3) 20 | ``` 21 | 22 | fixed size arrays 23 | ----------------- 24 | in stack mode a fixed size array is allocated as a low level C array, 25 | and new items can not be appended to it. 26 | ```python 27 | with stack: 28 | a = [2]int() 29 | a[0] = 100 30 | a[1] = 2500 31 | ``` 32 | 33 | multi dimensional lists 34 | ----------------------- 35 | ```python 36 | a = [][]int() 37 | a.append( [1,2,3] ) 38 | a.append( [3,4,5] ) 39 | assert a[0][0]==1 40 | assert a[1][2]==5 41 | ``` 42 | 43 | slicing lists 44 | ------------- 45 | when slicing a list the slice must be assigned to a variable, 46 | passing a slice directly in a function call `f( a[1:2] )` is not allowed. 47 | 48 | ```python 49 | myslice = mylist[ 10:2 ] 50 | f( myslice ) 51 | ``` 52 | -------------------------------------------------------------------------------- /doc/markdown_format.md: -------------------------------------------------------------------------------- 1 | Markdown Containers 2 | ------------------- 3 | 4 | The primary format `pythia` works with is [markdown](https://guides.github.com/features/mastering-markdown/) containers files (`.md`). 5 | Markdown containers allow you to bundle code and data into a single file. They store project and file directory stucture, 6 | code build options, and code documentation. 7 | 8 | Markdown files that contain fenced-code-blocks using [github style markdown](https://help.github.com/categories/writing-on-github/), can be compiled and run with `pythia`. 9 | Tripple backquotes `ʽʽʽ` are used to fence a block of code. The start of a fence can contain a language name, like: `ʽʽʽc++`, 10 | this will trigger that fenced code block to be compiled with `g++`. 11 | 12 | Fenced code blocks can also contain a label that must be on the line just before it and start with `@` followed by a file name 13 | or the special label name `@embed`. 14 | 15 | Multi-backend Python Transpiler 16 | ----------------- 17 | 18 | Fenced code blocks that begin with `ʽʽʽpythia` will be transpiled to C++14 (by default), and compiled with `g++`. 19 | A single markdown file can contain multiple targets to transpile, each fenced block must have its own file name label, 20 | and define at the start of the script which backend to transpile with. 21 | 22 | Pythia's transpiler will check each script's first line for a special comment starting with `#backend:`, valid options are: 23 | * `#backend:c++` 24 | * `#backend:javascript` 25 | * `#backend:go` 26 | 27 | -------------------------------------------------------------------------------- /doc/memory.md: -------------------------------------------------------------------------------- 1 | Pythia script translated into C++14 will allocate objects on the heap, 2 | and use standard reference counted garbage collection by default. 3 | 4 | Each of these object types will be wrapped by `std::shared_ptr`: 5 | * `myclass()` objects are initialized as `std::shared_ptr` 6 | * `[]` lists become `std::shared_ptr>` 7 | * `{}` dicts become `std::shared_ptr>` 8 | 9 | Note in stack memory mode, objects are not wrapped by `std::shared_ptr`, 10 | and memory is automatically freed when it falls out of scope. 11 | 12 | create an object on the stack 13 | ----------------------------- 14 | ```python 15 | with stack: 16 | a = MyClass() 17 | ``` 18 | 19 | create an array on the stack 20 | ----------------------------- 21 | ```python 22 | with stack: 23 | a = [1,2,3] 24 | ``` 25 | 26 | cyclic data structures 27 | ---------------------- 28 | 29 | Wrapping objects with `std::shared_ptr` requires using `std::weak_ptr` to break cyclic references. 30 | The translator will detect simple cases where a child class has a reference to a class that contains 31 | a list of itself, when this is found the parent will be wrapped with `std::weak_ptr` instead of `std::shared_ptr` 32 | 33 | The child can then access its parent with some additional logic, 34 | getting a reference to the parent must be done by wrapping it with 35 | `p = weakref.unwrap( self.myparent )` 36 | and then checking if `p` is None. 37 | `if p is None: print "parent has been freed"` 38 | then if the parent is not None, it can be used normally, because `weakref.unwrap()` will convert the `std::weak_ref` to a `std::shared_ptr`. 39 | -------------------------------------------------------------------------------- /doc/quick_start.md: -------------------------------------------------------------------------------- 1 | installing pythia 2 | ----------------- 3 | 4 | pythia requires 64bit linux and g++4.9 for all features and test scripts to work. 5 | 6 | Run `install.sh` script as root. 7 | This creates a symbolic link `pythia` that points to the current location of `pythia.py`. 8 | 9 | 10 | ```bash 11 | cd 12 | git clone https://github.com/secureosv/pythia.git 13 | cd pythia 14 | sudo ./install.sh 15 | ``` 16 | 17 | optional dependencies 18 | ------------------- 19 | * git 20 | * gnuplot 21 | * cython 22 | 23 | documentation 24 | ------------- 25 | * [getting started](getting_started.md) 26 | * [syntax](syntax.md) 27 | * [seastar](seastar.md) 28 | -------------------------------------------------------------------------------- /doc/seastar.md: -------------------------------------------------------------------------------- 1 | Seastar Example 2 | --------------- 3 | Pythia includes syntax for calling and chaining lambda functions. 4 | The syntax below `and then():` chains a new lambda function to the previous one. 5 | The functions are defined under `with stack:` are set to use stack memory mode (CPU Cache). 6 | note: the default memory mode is c++11 smart pointers (reference counted garbage collection). 7 | 8 | ```python 9 | 10 | with stack: 11 | def delay(seconds) -> future<>: 12 | print 'sleeping', seconds 13 | sleep(seconds) 14 | return future 15 | 16 | def f() -> future<>: 17 | delay(1) and then(): 18 | print 'sleep1' 19 | and then(): 20 | print 'sleep1.1' 21 | delay(1) and then(): 22 | print 'nested 1.1:1' 23 | and then(): 24 | print 'nested 1.1:2' 25 | 26 | and then(): 27 | print 'sleep1.2' 28 | and then(): 29 | print 'sleep1.2.1' 30 | 31 | delay(2) and then(): 32 | print 'sleep2' 33 | 34 | return delay(3) and then(): 35 | print 'all done' 36 | 37 | ``` 38 | -------------------------------------------------------------------------------- /examples/c++/array_generics.md: -------------------------------------------------------------------------------- 1 | Array Generics 2 | -------------- 3 | Below `if isinstance` is used to cast item to that type, if it is an instance of that class. 4 | 5 | ```rusthon 6 | class A: 7 | def __init__(self, x:int): 8 | self.x = x 9 | def method1(self) -> int: 10 | return self.x 11 | 12 | class B(A): 13 | def method1(self) ->int: 14 | return self.x * 2 15 | def method2(self, y:int): 16 | print( self.x + y ) 17 | 18 | class C(A): 19 | def method1(self) ->int: 20 | return self.x + 200 21 | def say_hi(self): 22 | print('hi from C') 23 | 24 | def main(): 25 | a = A( 1 ) 26 | b = B( 200 ) 27 | c = C( 3000 ) 28 | arr = []A( a,b,c ) 29 | 30 | for item in arr: 31 | print(item.method1()) 32 | 33 | if isinstance(item, B): 34 | item.method2( 20 ) 35 | 36 | if isinstance(item, C): 37 | item.say_hi() 38 | ``` -------------------------------------------------------------------------------- /examples/c++/array_slice.md: -------------------------------------------------------------------------------- 1 | array slice syntax 2 | ------------------ 3 | 4 | note: below the untyped literal `[1,2,3,4,5]` is used to initalize `a`, this is a simple case and the transpiler can infer that you want a shared reference to a `std::vector`. 5 | 6 | ```rusthon 7 | #backend:c++ 8 | 9 | def somefunc(): 10 | a = [1,2,3,4,5] 11 | print('a addr:', a) 12 | print('len a:', len(a)) 13 | b = a[1:] 14 | print('b addr (should not be `a` above):', b) 15 | print('len b (should be 4):', len(b)) 16 | 17 | c = a[:] 18 | print('c addr (should not be `a` or `b` above):', c) 19 | print('len c:', len(c)) 20 | c.append(6) 21 | print('len c - after append:', len(c)) 22 | print('len a:', len(a)) 23 | 24 | print('end slice test') 25 | 26 | d = a[:2] 27 | print('len d:', len(d)) 28 | print d[0] 29 | print d[1] 30 | 31 | print('len a:', len(a)) 32 | e = a[::1] 33 | print('len e should be same as a:', len(e)) 34 | for i in e: print i 35 | 36 | f = a[::2] 37 | print('len f:', len(f)) 38 | for i in f: print i 39 | 40 | g = a[::-1] 41 | print('len g:', len(g)) 42 | for i in g: print i 43 | 44 | h = a[2::-1] 45 | print('len h:', len(h)) 46 | for i in h: print i 47 | 48 | print('---slice assignment---') 49 | h.append(1000) 50 | h.append(1000) 51 | a[:2] = h 52 | for i in a: print i 53 | print('len a:', len(a)) 54 | 55 | print('somefunc done') 56 | 57 | def main(): 58 | print('calling somefunc') 59 | somefunc() 60 | print('OK') 61 | 62 | ``` -------------------------------------------------------------------------------- /examples/c++/async_channels.md: -------------------------------------------------------------------------------- 1 | Async Channels 2 | --------------- 3 | 4 | Below works with the C++ and Go backends. 5 | Channels are implemented in C++ using [cpp-channel](https://github.com/ahorn/cpp-channel). 6 | 7 | See the Wiki doc for more info on channels and spawn [here](https://github.com/rusthon/Rusthon/wiki/concurrency). 8 | 9 | ```rusthon 10 | #backend:c++ 11 | 12 | def sender_wrapper(a:int, send: chan int ): 13 | print 'sending' 14 | result = 100 15 | send <- result 16 | 17 | def recv_wrapper(a:int, recver: chan int ) -> int: 18 | print 'receiving' 19 | v = <- recver 20 | return v 21 | 22 | def main(): 23 | print 'enter main' 24 | c = channel(int) 25 | spawn( sender_wrapper(17, c) ) 26 | x = recv_wrapper(2, c) 27 | print(x) 28 | print 'ok' 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /examples/c++/call_c_from_c++.md: -------------------------------------------------------------------------------- 1 | c staticlib 2 | ------ 3 | this C code gets compiled by gcc, compiled to its own staticlib, and linked into the main c++ program. 4 | ```c 5 | #include 6 | 7 | void say_hi_c() { 8 | printf("Hello world from C\n"); 9 | } 10 | ``` 11 | 12 | c++ 13 | -------- 14 | ```c++ 15 | #include 16 | #include 17 | #include 18 | 19 | void say_hi_cpp() { 20 | std::cout << std::string("hello world from c++") << std::endl; 21 | } 22 | 23 | ``` 24 | 25 | rusthon 26 | ---------- 27 | ```rusthon 28 | #backend:c++ 29 | 30 | with extern(): 31 | def say_hi_c(): pass 32 | 33 | def say_hi(): 34 | print( 'hello world') 35 | 36 | def main(): 37 | say_hi() 38 | say_hi_cpp() 39 | say_hi_c() 40 | ``` 41 | 42 | 43 | -------------------------------------------------------------------------------- /examples/c++/fails_bad_order.md: -------------------------------------------------------------------------------- 1 | C++ Gotcha 2 | ---------- 3 | If your comming from Python, nothing looks wrong with the program below. Your thinking of course g++ is going to do a second pass and find the definition of `otherfunc` and use it in `main` - sadly this is **not** how it works in C/C++. 4 | 5 | ```rusthon 6 | #backend:c++ 7 | 8 | def main(): 9 | otherfunc() 10 | 11 | def otherfunc(): 12 | print('hi') 13 | ``` 14 | 15 | Rusthon makes no attempt to reorder your functions so that they can be compiled by g++. So for now you need to pay attention to how you order functions that depend on one another. In the future this will be fixed with forward declarations of all functions in the header. Until then, if you make this mistake, your going to see an error like this: 16 | ``` 17 | brett@mint15 ~/Rusthon $ ./rusthon.py ./examples/fails_bad_order.md 18 | /tmp/rusthon-c++-build.cpp: In function ‘int main()’: 19 | /tmp/rusthon-c++-build.cpp:64:12: error: ‘otherfunc’ was not declared in this scope 20 | ``` 21 | -------------------------------------------------------------------------------- /examples/c++/hello_civetweb.md: -------------------------------------------------------------------------------- 1 | C++11 Webserver Example 2 | ------------- 3 | * requires https://github.com/secureosv/civetweb.git 4 | * for more info see https://github.com/civetweb/civetweb/blob/master/docs/Embedding.md 5 | 6 | Auto Build CivetWeb 7 | ---------- 8 | @https://github.com/secureosv/civetweb.git 9 | ```bash 10 | export WITH_CPP:=1 11 | export WITH_WEBSOCKETS:=1 12 | export WITH_IPV6=0 WITH_LUA=0 13 | make lib 14 | sudo cp -v ./include/CivetServer.h /usr/local/include/. 15 | sudo cp -v ./include/civetweb.h /usr/local/include/. 16 | sudo cp -v libcivetweb.a /usr/local/lib/. 17 | make clean 18 | make slib 19 | sudo cp -v libcivetweb.so.1 /usr/local/lib/. 20 | ``` 21 | 22 | Main Script 23 | ------------- 24 | * @link:civetweb 25 | ```rusthon 26 | #backend:c++ 27 | import CivetServer.h 28 | from time import sleep 29 | 30 | class MyHandler( CivetHandler ): 31 | def __init__(self): 32 | print 'init MyHandler' 33 | 34 | def handleGet(self, server:CivetServer*, conn: struct mg_connection*) -> bool: 35 | mg_printf( conn, "hello world".c_str() ) 36 | return True 37 | 38 | def main(): 39 | print 'init civet test...' 40 | let options : const char* = {'document_root', '.', 'listening_ports', '8081', 0} 41 | server = new CivetServer( options ) 42 | handler = new MyHandler() 43 | server.addHandler("/helloworld", handler) 44 | sleep(30) 45 | print 'exit' 46 | ##std::quick_exit(0) ## missing in osv 47 | std::exit(0) 48 | 49 | ``` -------------------------------------------------------------------------------- /examples/c++/hello_sdl.md: -------------------------------------------------------------------------------- 1 | SDL C++ Example 2 | ------------- 3 | * requires libSDL2pp 4 | * libSDL2pp is downloaded from github, built and installed automatically. 5 | 6 | 7 | libSDL2pp 8 | ---------- 9 | @https://github.com/AMDmi3/libSDL2pp.git 10 | ```bash 11 | cmake . 12 | make 13 | sudo make install 14 | ``` 15 | 16 | Build Options 17 | ------------- 18 | * @link:SDL2pp 19 | ```rusthon 20 | #backend:c++ 21 | import SDL2pp/SDL2pp.hh 22 | from time import sleep 23 | 24 | namespace('SDL2pp') 25 | 26 | def main(): 27 | print 'init sdl' 28 | SDL( SDL_INIT_VIDEO ) 29 | 30 | ttf = new(SDLTTF()) 31 | 32 | win = Window( 33 | "my sdl window", 34 | SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 35 | 640, 480, 36 | SDL_WINDOW_RESIZABLE 37 | ) 38 | 39 | // Create accelerated video renderer with default driver 40 | ren = new Renderer(win, -1, SDL_RENDERER_ACCELERATED) 41 | font = new Font('/usr/share/fonts/gnu-free/FreeSans.ttf', 20) 42 | 43 | let color : SDL_Color = {255,0,255, 255} 44 | tex = new Texture(*ren, font.RenderText_Blended("hello world", color)) 45 | 46 | // Clear screen 47 | ren.Clear() 48 | // Render text 49 | ren.Copy(*tex) 50 | // Show rendered frame 51 | ren.Present() 52 | // 5 second delay 53 | sleep(5.0) 54 | 55 | 56 | ``` -------------------------------------------------------------------------------- /examples/c++/hello_seastar.md: -------------------------------------------------------------------------------- 1 | Auto Build Seastar 2 | ---------- 3 | @https://github.com/scylladb/seastar.git 4 | ```bash 5 | sudo apt-get install libaio-dev ninja-build ragel libhwloc-dev libnuma-dev libpciaccess-dev libcrypto++-dev libboost-all-dev libxen-dev libxml2-dev xfslibs-dev 6 | sudo apt-get install software-properties-common python-software-properties 7 | sudo add-apt-repository ppa:ubuntu-toolchain-r/test 8 | sudo apt-get update 9 | sudo apt-get install g++-4.9 gcc-4.9-multilib g++-4.9-multilib libgnutls28-dev 10 | ./configure.py --compiler=g++-4.9 11 | ninja -j 1 build/release/libseastar 12 | sudo cp -v ./build/release/libseastar.a /usr/local/lib/. 13 | 14 | ``` 15 | 16 | Main Script 17 | ------------- 18 | * @link:seastar 19 | * @include:~/rusthon_cache/seastar 20 | ```rusthon 21 | #backend:c++ 22 | import core/app-template.hh 23 | import core/reactor.hh 24 | 25 | def main(argc:int, argv:char**): 26 | app = new app_template() 27 | def on_run(): 28 | print 'hello seastar' 29 | return future 30 | app.run(argc, argv, on_run) 31 | ``` -------------------------------------------------------------------------------- /examples/c++/namespaces.md: -------------------------------------------------------------------------------- 1 | C++ Namespaces 2 | -------------- 3 | Macros are used when C++ name spaces need to be used directly. 4 | 5 | note `[...]` is syntax for manual pointer deference 6 | 7 | ```rusthon 8 | #backend:c++ 9 | 10 | def main(): 11 | vec = []int(1,2,3,4,5,6) 12 | ref = vec[...] 13 | with Max as 'std::max_element( std::begin(%s), std::end(%s) )': 14 | max = Max(ref, ref) 15 | print max[...] 16 | 17 | with Min as 'std::min_element( std::begin(%s), std::end(%s) )': 18 | min = Min(ref, ref) 19 | print min[...] 20 | 21 | 22 | ``` -------------------------------------------------------------------------------- /examples/c++/seastar_future.md: -------------------------------------------------------------------------------- 1 | Auto Build Seastar 2 | ---------- 3 | @https://github.com/scylladb/seastar.git 4 | ```bash 5 | sudo apt-get install libaio-dev ninja-build ragel libhwloc-dev libnuma-dev libpciaccess-dev libcrypto++-dev libboost-all-dev libxen-dev libxml2-dev xfslibs-dev 6 | sudo apt-get install software-properties-common python-software-properties 7 | sudo add-apt-repository ppa:ubuntu-toolchain-r/test 8 | sudo apt-get update 9 | sudo apt-get install g++-4.9 gcc-4.9-multilib g++-4.9-multilib libgnutls28-dev 10 | ./configure.py --compiler=g++-4.9 11 | ninja -j 1 build/release/libseastar 12 | sudo cp -v ./build/release/libseastar.a /usr/local/lib/. 13 | 14 | ``` 15 | 16 | Main Script 17 | ------------- 18 | * @link:seastar 19 | * @include:~/rusthon_cache/seastar 20 | ```rusthon 21 | #backend:c++ 22 | import core/app-template.hh 23 | import core/reactor.hh 24 | import core/future.hh 25 | 26 | 27 | with stack: 28 | class Foo: 29 | def __init__(self, x:int ): 30 | self.x = x 31 | def add(self, y) ->int: 32 | return self.x + y 33 | 34 | def fast() -> future: 35 | print 'fast...' 36 | f = Foo(400) 37 | r = f.add(20) 38 | print f.x 39 | return future(r) ## gets translated to make_ready_future(r) 40 | 41 | def main(argc:int, argv:char**): 42 | app = new app_template() 43 | def on_run(): 44 | print 'hello seastar future' 45 | 46 | def after_fast(val:int): 47 | print 'after fast...' 48 | print val 49 | 50 | fast().then( after_fast ) 51 | 52 | return future 53 | 54 | app.run(argc, argv, on_run) 55 | 56 | ``` 57 | -------------------------------------------------------------------------------- /examples/c++/std_move.md: -------------------------------------------------------------------------------- 1 | C++11 std::move 2 | -------------- 3 | 4 | `std::move` is also used below, this is the fastest way to move strings around without making a copy, 5 | the original variable becomes invalid after moved. 6 | http://en.cppreference.com/w/cpp/utility/move 7 | 8 | ```rusthon 9 | #backend:c++ 10 | 11 | def foo( s:string&& ): 12 | print 'string moved into foo' 13 | s += 'z' 14 | print s 15 | 16 | def main(): 17 | vec = []string( 18 | 'hello', 19 | 'world' 20 | ) 21 | print vec[0] 22 | print vec[1] 23 | 24 | a = 'bar' 25 | b = 'xxx' 26 | print 'testing std::move' 27 | with MV as "std::move(%s)": 28 | vec.append( MV(a) ) 29 | foo( MV(b) ) 30 | print 'done moving a and b' 31 | ## this prints nothing because std::move was used on a and b 32 | print a 33 | print b 34 | print vec[2] ## this prints `bar` 35 | 36 | 37 | ``` -------------------------------------------------------------------------------- /examples/c++/subclass_from_c++.md: -------------------------------------------------------------------------------- 1 | C++ Class Example 2 | ---------------- 3 | 4 | The extra markdown syntax below `@embed:mybinary` is used to 5 | insert the c++ code into the transpiled output. 6 | 7 | 8 | @embed:mybinary 9 | ```c++ 10 | #include 11 | #include 12 | #include 13 | 14 | class HelloWorld { 15 | public: 16 | std::string mystring; 17 | void mymethod(); 18 | void set( std::string s ) { this->mystring = s;} 19 | }; 20 | void HelloWorld::mymethod() { 21 | std::cout << this->mystring << std::endl; 22 | } 23 | 24 | int mycppfunc( HelloWorld* ob ) { 25 | ob->mymethod(); 26 | return 1; 27 | } 28 | 29 | ``` 30 | 31 | `Subclass` defines `__init__` to workaround the problem of calling the parent constructor 32 | of an external c++ class. 33 | 34 | @mybinary 35 | ```rusthon 36 | #backend:c++ 37 | 38 | class Subclass( HelloWorld ): 39 | def __init__(self, s:string ): 40 | self.set( s ) 41 | 42 | def foo(self): 43 | print 'foo' 44 | return self.mystring 45 | 46 | def main(): 47 | ## because HelloWorld is an external c++ class, 48 | ## `new` must be used to initialize it. 49 | ob = new(HelloWorld()) 50 | ob.set('hi') 51 | ob.mymethod() 52 | print ob 53 | 54 | ## note: mycppfunc can be called directly 55 | ## because it is embedded, and not linked 56 | ## to an external library. 57 | assert mycppfunc( ob ) == 1 58 | 59 | ## because Subclass is defined here, 60 | ## it can be initialized without using `new` 61 | s1 = new Subclass('bar1') 62 | s2 = new(Subclass('bar2')) 63 | s3 = Subclass('bar3') 64 | print s1 65 | s1.mymethod() 66 | assert s1.foo()=='bar1' 67 | 68 | 69 | ``` -------------------------------------------------------------------------------- /examples/doxygen.md: -------------------------------------------------------------------------------- 1 | ```rusthon 2 | class A: 3 | ''' 4 | doc about my class 5 | ''' 6 | def mymethod(self): 7 | ''' 8 | doc about mymethod 9 | ''' 10 | pass 11 | 12 | def somefunc( x:int ) -> bool: 13 | ''' 14 | my documentation on somefunc 15 | @param [in] x Number to print. 16 | @retval TRUE Returns true if less than ten. 17 | @retval FALSE Returns false otherwise. 18 | ''' 19 | print(x) 20 | if x < 10: return True 21 | else: return False 22 | 23 | def main(): 24 | somefunc( 10 ) 25 | ``` 26 | 27 | -------------------------------------------------------------------------------- /examples/hello_coffee.md: -------------------------------------------------------------------------------- 1 | CoffeeScript 2 | ------------ 3 | 4 | http://coffeescript.org/ 5 | 6 | 7 | @mycoffee.js 8 | ```coffee 9 | 10 | elvis = 1 11 | alert "I knew it!" if elvis? 12 | 13 | square = (x) -> x * x 14 | 15 | ``` 16 | 17 | PythonJS 18 | --------- 19 | 20 | @mypython.js 21 | ```rusthon 22 | #backend:javascript 23 | 24 | def main(): 25 | alert( square(420) ) 26 | 27 | main() 28 | 29 | ``` 30 | 31 | HTML 32 | ----- 33 | 34 | The output of both transpilers is inserted into the final html 35 | 36 | @index.html 37 | ```html 38 | 39 | 40 | <@mycoffee.js> 41 | <@mypython.js> 42 | 43 | 44 | ``` -------------------------------------------------------------------------------- /examples/hello_cython.md: -------------------------------------------------------------------------------- 1 | Cython Hello World 2 | ------- 3 | 4 | @embed 5 | ```python 6 | import os, sys 7 | sys.path.append( os.path.curdir ) ## TODO this should not be required to import the cython module 8 | import mycython_module as cymod 9 | 10 | def run_test(): 11 | cymod.hi_cython() 12 | 13 | ``` 14 | 15 | 16 | @mycython_module 17 | ```cython 18 | 19 | def hi_cython(): 20 | a = 'hello' 21 | b = 'world' 22 | print a + b 23 | cdef int x=10 24 | cdef int y=20 25 | print x + y 26 | 27 | ``` 28 | 29 | Build Options 30 | ------------- 31 | * @link:python2.7 32 | * @include:/usr/include/python2.7 33 | @myexe 34 | ```pythia 35 | #backend:c++ 36 | import cpython 37 | 38 | def main(): 39 | a = 'hello' 40 | b = 'world' 41 | print a + b 42 | x=10 43 | y=20 44 | print x + y 45 | 46 | 47 | print 'init CPython...' 48 | state = cpython.initalize() 49 | with gil: 50 | cpython.run_test() 51 | cpython.finalize(state) 52 | print 'OK' 53 | 54 | ``` 55 | -------------------------------------------------------------------------------- /examples/hello_iframe.md: -------------------------------------------------------------------------------- 1 | iframe html 2 | ---- 3 | 4 | @myiframe.html 5 | ```html 6 | 7 | 8 | 9 | 10 |

Hello Iframe

11 | 12 | 13 | ``` 14 | 15 | main html 16 | ---- 17 | 18 | @index.html 19 | ```html 20 | 21 | 22 | <@myscript> 23 | 24 | 25 | 26 | 27 | 28 | ``` 29 | 30 | Script 31 | --------------- 32 | 33 | @myscript 34 | ```rusthon 35 | #backend:javascript 36 | from runtime import * 37 | 38 | @debugger 39 | def hello_world(): 40 | iframe = document->('iframe')->(src='myiframe.html') 41 | document.body->(iframe) 42 | global doc 43 | sleep(1) 44 | doc = iframe.contentDocument 45 | h1 = doc->('#FOO') 46 | print h1 47 | sleep(1) 48 | h1->('foo') 49 | h1->( doc->('a')->('bar', href="http://...") ) 50 | 51 | 52 | ``` 53 | -------------------------------------------------------------------------------- /examples/hello_java.md: -------------------------------------------------------------------------------- 1 | Java Frontend with Java2Rusthon 2 | -------------- 3 | Requires: 4 | * https://github.com/rusthon/java2python 5 | * Antlr 3.1.3 for Python2 6 | 7 | @install-script.sh 8 | ```bash 9 | cd 10 | git clone https://github.com/rusthon/java2python.git 11 | cd java2python 12 | sudo python setup.py install 13 | cd 14 | wget http://www.antlr3.org/download/antlr-3.1.3.tar.gz 15 | tar xfz antlr-3.1.3.tar.gz 16 | cd antlr-3.1.3/runtime/Python/ 17 | sudo python setup.py install 18 | ``` 19 | 20 | Java 21 | ----- 22 | Some hand written Java source code, auto converted to Rusthon's syntax, 23 | and merged with below. 24 | @java2rusthon 25 | ```java 26 | 27 | public class HelloWorld { 28 | public static void test() { 29 | System.out.println("Hello, World test"); 30 | } 31 | 32 | public static void foo(String msg) { 33 | System.out.println(msg); 34 | } 35 | 36 | } 37 | ``` 38 | 39 | Rusthon 40 | --------------------------- 41 | The above Java code is converted to Rusthon, and merged with this code. 42 | ```rusthon 43 | #backend:c++ 44 | 45 | def main(): 46 | HelloWorld.test() 47 | HelloWorld.foo("hi java") 48 | 49 | ``` -------------------------------------------------------------------------------- /examples/hello_javascript.md: -------------------------------------------------------------------------------- 1 | testing 2 | ------- 3 | 4 | To run this example run these commands in your shell: 5 | 6 | ```bash 7 | cd 8 | git clone https://github.com/rusthon/Rusthon.git 9 | cd Rusthon/ 10 | ./rusthon.py ./examples/hello_javascript.md 11 | ``` 12 | 13 | html 14 | ---- 15 | 16 | 17 | @index.html 18 | ```html 19 | 20 | 21 | 22 | <@myscript> 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | ``` 31 | 32 | Above a special syntax is used `@myscript` this tells Rusthon where to insert the output of scripts it translates using the javascript backend below. 33 | 34 | 35 | rusthon javascript backend 36 | -------------------------- 37 | 38 | Below `@myscript` is given on the line just before the fenced rusthon code block. This allows you to insert multiple scripts into your html, in the head or body. 39 | 40 | @myscript 41 | ```rusthon 42 | #backend:javascript 43 | from runtime import * 44 | 45 | def hello_world(): 46 | window.alert("hi") 47 | 48 | ``` 49 | -------------------------------------------------------------------------------- /examples/hello_nuitka.md: -------------------------------------------------------------------------------- 1 | Nuitka Class 2 | ------------ 3 | Class `A` 4 | 5 | @nuitka:mymodule 6 | ```python 7 | 8 | class A(): 9 | def pymethod(self): 10 | print 'hello world' 11 | 12 | ``` 13 | 14 | Nuitka Function 15 | ------------ 16 | `foo` returns `A` 17 | 18 | @nuitka 19 | ```python 20 | def foo(): 21 | print 'foo' 22 | return A() 23 | 24 | ``` 25 | 26 | Build Options 27 | ------------- 28 | * @link:python2.7 29 | * @include:/usr/include/python2.7 30 | 31 | ```rusthon 32 | #backend:c++ 33 | import cpython 34 | 35 | with pointers: 36 | def bar( pyob:PyObject ): 37 | pyob->pymethod() 38 | 39 | def main(): 40 | s = cpython.initalize() 41 | with gil: 42 | pyob = cpython.foo() 43 | bar( pyob ) 44 | cpython.finalize(s) 45 | 46 | ``` -------------------------------------------------------------------------------- /examples/hello_nw_gyp.md: -------------------------------------------------------------------------------- 1 | NW.js C++ Extension 2 | ------------- 3 | * https://github.com/nwjs/nw-gyp 4 | * https://github.com/nodejs/node/blob/master/test/addons/hello-world/binding.cc 5 | 6 | 7 | Gyp File 8 | ---------- 9 | ```gyp 10 | { 11 | 'targets': [ 12 | { 13 | 'target_name': 'binding', 14 | 'sources': [ 'binding.cc' ] 15 | } 16 | ] 17 | } 18 | ``` 19 | 20 | Main Script 21 | ------------- 22 | 23 | @binding.cc 24 | ```rusthon 25 | #backend:c++ 26 | import node.h 27 | import v8.h 28 | 29 | namespace('v8') 30 | 31 | def MyMethod(args : const FunctionCallbackInfo&): 32 | isolate = Isolate::GetCurrent() 33 | let scope(isolate) : HandleScope 34 | args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world".c_str() )) 35 | 36 | def init(target: Local): 37 | NODE_SET_METHOD(target, "hello".c_str(), MyMethod) 38 | 39 | NODE_MODULE(binding, init) 40 | 41 | ``` 42 | 43 | Nw.js 44 | ------ 45 | tests the c++ module from javascript 46 | 47 | @myscript.js 48 | ```rusthon 49 | #backend:javascript 50 | mymodule = require('./build/Release/binding') 51 | def test(): 52 | alert( mymodule.hello() ) 53 | 54 | ``` 55 | 56 | HTML 57 | ----- 58 | 59 | @index.html 60 | ```html 61 | 62 | 63 | <@myscript.js> 64 | 65 | 66 | 67 | 68 | 69 | ``` -------------------------------------------------------------------------------- /examples/hello_openlayers.md: -------------------------------------------------------------------------------- 1 | OpenLayers Hello World 2 | ----------------------- 3 | * https://github.com/openlayers/ol3 4 | * http://openlayers.org/en/master/apidoc/ 5 | 6 | 7 | @index.html 8 | ```html 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | <@myscript> 17 | 18 | 19 |
20 | 21 | 22 | ``` 23 | 24 | Script 25 | --------------- 26 | 27 | @myscript 28 | ```rusthon 29 | #backend:javascript 30 | from runtime import * 31 | 32 | @debugger 33 | def main(): 34 | london = ol.proj.fromLonLat([-0.12755, 51.507222]) 35 | moscow = ol.proj.fromLonLat([37.6178, 55.7517]) 36 | istanbul = ol.proj.fromLonLat([28.9744, 41.0128]) 37 | rome = ol.proj.fromLonLat([12.5, 41.9]) 38 | bern = ol.proj.fromLonLat([7.4458, 46.95]) 39 | madrid = ol.proj.fromLonLat([-3.683333, 40.4]) 40 | 41 | view = new ol.View(center=istanbul, zoom=6) 42 | 43 | layers = [ 44 | new ol.layer.Tile( 45 | preload=4, 46 | source = new ol.source.OSM() 47 | ) 48 | ] 49 | 50 | map = new ol.Map( 51 | view = view, 52 | layers = layers, 53 | target = 'MAPDIV', 54 | controls = ol.control.defaults(attributionOptions={collapsible: false}), 55 | loadTilesWhileAnimating = True, 56 | ) 57 | 58 | 59 | ``` 60 | -------------------------------------------------------------------------------- /examples/hello_osv.md: -------------------------------------------------------------------------------- 1 | OSV Hello World 2 | ------------- 3 | What is OSv? http://osv.io/ 4 | 5 | You do not need to install OSv, Pythia will automatically download and build the base image for you. 6 | After installing Pythia, run this command, this will compile and run the example. 7 | ```bash 8 | cd 9 | git clone https://github.com/secureosv/pythia.git 10 | cd pythia 11 | sudo ./install.sh 12 | pythia ./examples/hello_osv.md --osv 13 | ``` 14 | 15 | 16 | ```pythia 17 | #backend:c++ 18 | from runtime import * 19 | from time import sleep 20 | import osv/power.hh 21 | 22 | class A: 23 | def __init__(self, txt:string ): 24 | self.txt = txt 25 | def foo(self): 26 | print self.txt 27 | 28 | def main(): 29 | a = A('hello world xxx') 30 | a.foo() 31 | sleep(1) 32 | #osv::halt() ## hang and lock up vm 33 | print 'rebooting..' 34 | osv::reboot() 35 | 36 | ``` -------------------------------------------------------------------------------- /examples/hello_rapydscript.md: -------------------------------------------------------------------------------- 1 | testing 2 | ------- 3 | 4 | To run this example run these commands in your shell: 5 | 6 | ```bash 7 | cd 8 | git clone https://github.com/rusthon/Rusthon.git 9 | cd Rusthon/ 10 | ./rusthon.py ./examples/hello_rapydscript.md 11 | ``` 12 | 13 | html 14 | ---- 15 | 16 | 17 | @index.html 18 | ```html 19 | 20 | 21 | 22 | <@my_rapydscript.js> 23 | <@my_rusthon_script.js> 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | ``` 32 | 33 | rapydscript 34 | ----------- 35 | You need to install RapydScript for this to work. 36 | http://www.rapydscript.com/ 37 | 38 | Test calling Rusthon translated JS from RapydScript. 39 | 40 | @my_rapydscript.js 41 | ```rapydscript 42 | 43 | ## note unicode is broken in rapydscript 44 | #𝑭𝑶𝑶𝒃𝒂𝒓 = 'UNICODE_OK' 45 | 46 | def hi_from_rapyd(): 47 | window.alert('hey rapydscript!') 48 | a = [1,2,3] 49 | hi_from_rusthon(a) 50 | 51 | ``` 52 | 53 | 54 | rusthon javascript backend 55 | -------------------------- 56 | 57 | @my_rusthon_script.js 58 | ```rusthon 59 | #backend:javascript 60 | from runtime import * 61 | 62 | def hi_from_rusthon(v): 63 | assert inline('𝑭𝑶𝑶𝒃𝒂𝒓') == 'UNICODE_OK' 64 | assert len(v) == 3 65 | assert v[0] == 1 66 | for x in v: 67 | print(x) 68 | 69 | ``` 70 | -------------------------------------------------------------------------------- /examples/helloworld.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Helloworld Example 3 | 4 | If this file is compiled without any extra arguments, it will be transpiled using the C++ backend, 5 | compiled with GCC, and then binary will be executed. 6 | ./rusthon.py ./examples/helloworld.py 7 | 8 | To transpile with another backend use one of these command line options: 9 | --javascript 10 | --rust 11 | --go 12 | 13 | JavaScript Example: 14 | This will transpile and test it using NodeJS 15 | ./rusthon.py ./examples/helloworld.py --javascript 16 | 17 | This will transpile and save helloworld.js into mytar.tar file 18 | ./rusthon.py ./examples/helloworld.py --javascript /tmp/mytar.tar 19 | 20 | 21 | Note that using python files (.py) is not the preferred input method, 22 | and instead you should use markdown files (.md) as the container format. 23 | https://github.com/rusthon/Rusthon/wiki/Literate-Programming 24 | 25 | Why are python files not preferred? 26 | Because in regular python files are modules, and provide a namespace for what 27 | they contain. This is not the case here, where all files are merged into a 28 | single unit of translation. 29 | 30 | ''' 31 | 32 | def say_hi(): 33 | print( 'hello world') 34 | 35 | def main(): 36 | say_hi() 37 | 38 | main() -------------------------------------------------------------------------------- /examples/import_markdown.md: -------------------------------------------------------------------------------- 1 | Syntax for importing external markdowns into one for building together. 2 | 3 | * [@import mylib/mylib_A](mylib/mylib_A.md) 4 | * [@import mylib/mylib_B](mylib/mylib_B.md) 5 | 6 | 7 | ```rusthon 8 | 9 | def main(): 10 | a = A() 11 | a.foo() 12 | b = B() 13 | b.bar() 14 | 15 | ``` -------------------------------------------------------------------------------- /examples/index.md: -------------------------------------------------------------------------------- 1 | Pythia Examples 2 | --------------- 3 | 4 | The examples here are written in markdown (`.md`) container files that encapsulates: documentation, multiple languages and data formats. 5 | 6 | Multi-exe 7 | -------- 8 | 9 | Multiple executeables in different languages can be compiled from a single markdown, 10 | see this [example](example-project.md). 11 | 12 | 13 | Supported Languages 14 | ------------------ 15 | 16 | * C/C++ 17 | * Go 18 | * Nim 19 | * Rust 20 | * Python 21 | * Cython 22 | * CoffeeScript 23 | * RapydScript 24 | * JavaScript 25 | 26 | -------------------------------------------------------------------------------- /examples/java/giws_jython.md: -------------------------------------------------------------------------------- 1 | Jython Hello World 2 | ------------------ 3 | You need to download jython-standalone.jar from 4 | http://www.jython.org/downloads.html 5 | tested with jython-standalone-2.7-b3.jar, rename to jython.jar and build with this command: 6 | 7 | @test.sh 8 | ```bash 9 | ./rusthon.py ./examples/giws_jython.md --data=~/Downloads/jython.jar 10 | ``` 11 | 12 | Gwis Wrapper 13 | ------- 14 | Gwis generates JNI wrappers so the Java object can be used from C++. 15 | https://github.com/opencollab/giws 16 | The XML below wraps the PythonInterpreter from Jython. 17 | 18 | @gwis 19 | ```xml 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | ``` 28 | 29 | 30 | Rusthon 31 | ------------ 32 | 33 | ```rusthon 34 | import jvm 35 | jvm.load( 'jython.jar' ) 36 | jvm.namespace('org.python.util') 37 | 38 | def main(): 39 | interp = jvm( PythonInterpreter() ) 40 | script = "print 'hello world'" 41 | interp.__exec__(cstr(script)) 42 | 43 | ``` -------------------------------------------------------------------------------- /examples/java/java_giws.md: -------------------------------------------------------------------------------- 1 | Java 2 | ----- 3 | @mymodule/MyJavaClass.java 4 | ```java 5 | package mymodule; 6 | 7 | public class MyJavaClass{ 8 | public MyJavaClass(){ 9 | } 10 | public double bar(double a, double b){ 11 | return a*b; 12 | } 13 | } 14 | ``` 15 | 16 | Gwis Wrapper 17 | ------- 18 | Gwis generates JNI wrappers so the Java object can be used from C++. 19 | https://github.com/opencollab/giws 20 | @gwis 21 | ```xml 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | ``` 31 | 32 | 33 | Rusthon 34 | ------------ 35 | ```rusthon 36 | import jvm 37 | jvm.namespace('mymodule') 38 | 39 | 40 | def foo( ob: MyJavaClass ): 41 | print ob.bar( 10.0, 100.0 ) 42 | 43 | def main(): 44 | ob = jvm( MyJavaClass() ) 45 | foo( ob ) 46 | 47 | ``` -------------------------------------------------------------------------------- /examples/javascript_sleep.md: -------------------------------------------------------------------------------- 1 | Sleep - Async 2 | ------------- 3 | 4 | async javascript functions made easy. 5 | 6 | 7 | To run this example run these commands in your shell: 8 | 9 | ```bash 10 | cd 11 | git clone https://github.com/rusthon/Rusthon.git 12 | cd Rusthon/ 13 | ./rusthon.py ./examples/javascript_sleep.md 14 | ``` 15 | 16 | html 17 | ---- 18 | 19 | 20 | @index.html 21 | ```html 22 | 23 | 24 | <@myscript> 25 | 26 | 27 |
28 | 
29 | 30 | 31 | ``` 32 | 33 | Example 34 | -------------------------- 35 | 36 | `sleep(seconds)` pauses a function for a given number of seconds, 37 | it can only be used in the function body, and not under any conditional blocks or loops. 38 | 39 | @myscript 40 | ```rusthon 41 | #backend:javascript 42 | from runtime import * 43 | 44 | def show(txt): 45 | document.getElementById('CONTAINER').appendChild( 46 | document.createTextNode(txt + '\n') 47 | ) 48 | 49 | def invalid_sleep(): 50 | ## sleep is not allowed under any control or loop blocks 51 | ## uncomment below to see a transpiler error 52 | #if True: 53 | # show('sleep2') 54 | # sleep(1) 55 | #else: 56 | # show('never seen') 57 | #for i in range(10): 58 | # sleep(1) 59 | #while True: 60 | # sleep(1) 61 | # break 62 | pass 63 | 64 | @debugger 65 | def test(): 66 | 67 | show('sleep1') 68 | 69 | sleep(1) 70 | 71 | show('sleep2') 72 | sleep(1) 73 | 74 | show('sleep3') 75 | sleep(1) 76 | 77 | show('sleep test OK') 78 | 79 | 80 | ``` 81 | -------------------------------------------------------------------------------- /examples/mylib/mylib_A.md: -------------------------------------------------------------------------------- 1 | Library A 2 | ------- 3 | 4 | ```rusthon 5 | 6 | class A: 7 | def foo(self): 8 | print("hello world - foo") 9 | ``` 10 | -------------------------------------------------------------------------------- /examples/mylib/mylib_B.md: -------------------------------------------------------------------------------- 1 | Library B 2 | ------- 3 | 4 | ```rusthon 5 | 6 | class B: 7 | def bar(self): 8 | print("hello world - bar") 9 | ``` 10 | -------------------------------------------------------------------------------- /examples/nim_threadpool.md: -------------------------------------------------------------------------------- 1 | Nim ThreadPool and Parallel 2 | --------------------------- 3 | 4 | 5 | ```nim 6 | import threadpool 7 | {.experimental.} 8 | 9 | type 10 | IntSeq = seq[int] 11 | 12 | proc calc_something(x:int, y:int): IntSeq = 13 | result = @[x,y,x+y] 14 | 15 | proc start_nim_threadpool( a:cint, b:cint ): cint {.cdecl, exportc.} = 16 | var r: FlowVar[ IntSeq ] 17 | echo("a:", a) 18 | echo("b:", b) 19 | parallel: 20 | r = spawn calc_something( int(a), int(b) ) 21 | return cast[cint]((^r)[2]) 22 | 23 | ``` 24 | 25 | Run ThreadPool 26 | -------------- 27 | 28 | ```rusthon 29 | #backend:c++ 30 | import nim 31 | 32 | def main(): 33 | nim.main() 34 | print 'starting nim threadpool' 35 | msg = start_nim_threadpool( 10, 20 ) 36 | print msg 37 | print 'ok' 38 | 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /examples/nodejs_file.md: -------------------------------------------------------------------------------- 1 | NodeJS Fake Python Builtin Modules 2 | --------------------- 3 | 4 | using `from nodejs import *` imports these modules that wrap around the nodejs api. 5 | 6 | * os 7 | * sys 8 | * open 9 | * tempfile 10 | 11 | To run this example run these commands in your shell, nodejs will be used to run it: 12 | 13 | ```bash 14 | cd 15 | git clone https://github.com/rusthon/Rusthon.git 16 | cd Rusthon/ 17 | ./rusthon.py ./examples/nodejs_file.md --run=myapp.js 18 | ``` 19 | 20 | 21 | @myapp.js 22 | ```rusthon 23 | #backend:javascript 24 | from runtime import * 25 | from nodejs import * 26 | 27 | f = open('/tmp/test.txt') 28 | f.write('hello world') 29 | f.close() 30 | 31 | a = open('/tmp/test.txt', 'r') 32 | print a.read() 33 | 34 | tdir = tempfile.gettempdir() 35 | print tdir 36 | 37 | print sys.argv 38 | print sys.stdin 39 | 40 | print os.environ 41 | print os.getcwd() 42 | print os.getpid() 43 | 44 | print dir(os) 45 | print dir(sys) 46 | 47 | ``` 48 | -------------------------------------------------------------------------------- /examples/nodejs_subprocess.md: -------------------------------------------------------------------------------- 1 | NodeJS fake Python subprocess module 2 | ------- 3 | 4 | tries to emulate python subprocess module, so far this is a minimal implementation, 5 | because nodejs is async, this is also async and you need to pass a callback to get the result of the subprocess. 6 | 7 | see [builtins_nodejs.py](../src/runtime/builtins_nodejs.py) 8 | 9 | * subprocess.call 10 | * subprocess.Popen 11 | 12 | To run this example run these commands in your shell, nodejs will be used to run it: 13 | 14 | ```bash 15 | cd 16 | git clone https://github.com/rusthon/Rusthon.git 17 | cd Rusthon/ 18 | ./rusthon.py ./examples/nodejs_subprocess.md --run=myapp.js 19 | ``` 20 | 21 | 22 | @myapp.js 23 | ```rusthon 24 | #backend:javascript 25 | from runtime import * 26 | from nodejs import * 27 | 28 | def cb(data): 29 | print data 30 | 31 | subprocess.call(executeable='ls', args=['-lh'], callback=cb) 32 | p = subprocess.Popen(executeable='ls', args=['-h'], callback=cb) 33 | 34 | ``` 35 | -------------------------------------------------------------------------------- /examples/nuitka_nim.md: -------------------------------------------------------------------------------- 1 | 2 | Nim 3 | -------------- 4 | 5 | ```nim 6 | proc my_nim_function( a:cint, b:cint, s:cstring ): cint {.cdecl, exportc.} = 7 | echo("calling my_nim_function") 8 | echo(s) 9 | echo("a:", a) 10 | echo("b:", b) 11 | result = a+b 12 | 13 | ``` 14 | 15 | Nuitka Class 16 | ------------ 17 | Class `A` 18 | 19 | @nuitka:mymodule 20 | ```python 21 | 22 | class A(): 23 | def pymethod(self, msg): 24 | print 'hello world from nuitka:', msg 25 | 26 | ``` 27 | 28 | 29 | Build Options 30 | ------------- 31 | * @link:python2.7 32 | * @include:/usr/include/python2.7 33 | 34 | ```rusthon 35 | #backend:c++ 36 | import nim 37 | import cpython 38 | 39 | def main(): 40 | ts = cpython.initalize() 41 | nim.main() 42 | print 'calling nim function' 43 | s = 'mymessage to nim' 44 | msg = my_nim_function( 10, 20, cstr(s) ) 45 | print msg 46 | with gil: 47 | a = cpython.A() 48 | a->pymethod( msg as pyint ) 49 | print 'OK' 50 | cpython.finalize(ts) 51 | ``` 52 | -------------------------------------------------------------------------------- /examples/osv_raise_rebuild.md: -------------------------------------------------------------------------------- 1 | Auto Recompile OSv Image 2 | ------------------ 3 | What is OSv? http://osv.io/ 4 | 5 | 6 | @https://github.com/secureosv/pythia.git 7 | ```bash 8 | pythia ./examples/osv_raise_rebuild.md --osv 9 | ``` 10 | 11 | @reboot.log 12 | ``` 13 | 0 myreboot log file 14 | ``` 15 | 16 | 17 | ```pythia 18 | #backend:c++ 19 | from runtime import * 20 | from time import sleep 21 | 22 | def main(): 23 | print 'hello rebuild...' 24 | print 'about to fail...' 25 | sleep(1) 26 | a = True 27 | if a: 28 | raise RuntimeError( 29 | #git='(optional other branch)', 30 | #deploy_server='https://...' 31 | #report_server='https://...' 32 | reboots = 10, ## number of times to reboot before VM shutdown 33 | sleep = 2 ## seconds to wait after each reboot 34 | ) 35 | else: 36 | print 'bug fixed' 37 | 38 | ``` -------------------------------------------------------------------------------- /examples/rust/async_channels_rust.md: -------------------------------------------------------------------------------- 1 | Async Channels Rust 2 | ----- 3 | 4 | Rust has builtin async channels, but the `Sender` and `Receiver` are different types. 5 | This syntax is also compatible with the C++ and Go backends, but `chan Sender` and `chan Receiver` has no extra meaning, they are simply two way channels. 6 | 7 | ```rusthon 8 | #backend:rust 9 | 10 | def sender_wrapper(a:int, send: chan Sender ): 11 | result = 100 12 | send <- result 13 | 14 | def recv_wrapper(a:int, recver: chan Receiver ) -> int: 15 | v = <- recver 16 | return v 17 | 18 | def main(): 19 | ## sender and recver are the same object in Go and C++ 20 | sender, recver = channel(int) 21 | spawn( sender_wrapper(17, sender) ) 22 | x = recv_wrapper(2, recver) 23 | print(x) 24 | ``` -------------------------------------------------------------------------------- /examples/simple_callback.md: -------------------------------------------------------------------------------- 1 | Callback Functions/Methods 2 | ---------------- 3 | 4 | Note: `|` is used to separate multiple argument types in a `lambda()()` callback typedef. 5 | 6 | ```rusthon 7 | #backend:c++ 8 | 9 | class Vec2: 10 | def __init__(self, x:f32, y:f32): 11 | self.x = x 12 | self.y = y 13 | 14 | def add(self, x:f32, y:f32): 15 | self.x += x 16 | self.y += y 17 | 18 | def show(self): 19 | print self.x 20 | print self.y 21 | 22 | 23 | def call_method( callback:lambda(f32|f32)(), other:Vec2 ): 24 | callback( other.x, other.y ) 25 | 26 | 27 | def main(): 28 | v1 = Vec2( 1.0, 2.0 ) 29 | v2 = Vec2( 100.0, 200.0 ) 30 | 31 | call_method( 32 | lambda x=f32, y=f32: v1.add(x,y), 33 | v2 34 | ) 35 | v1.show() 36 | 37 | ``` -------------------------------------------------------------------------------- /examples/simple_class.md: -------------------------------------------------------------------------------- 1 | rusthon 2 | ------- 3 | ```rusthon 4 | #backend:c++ 5 | 6 | class HelloWorld: 7 | def mymethod(self): 8 | print("hello world") 9 | 10 | def main(): 11 | a = HelloWorld() 12 | a.mymethod() 13 | ``` -------------------------------------------------------------------------------- /examples/simple_subclass.md: -------------------------------------------------------------------------------- 1 | Subclass Example 2 | ---------------- 3 | overload method of parent, also calls parent method from subclass overload, `BaseClass.method(self)` 4 | note this is old style python where the base class is used directly, the `super` special call is not supported. 5 | 6 | ```rusthon 7 | #backend:c++ 8 | 9 | class Vec2: 10 | def __init__(self, x:f32=0.0, y:f32=0.0): 11 | self.x = x 12 | self.y = y 13 | 14 | def sum(self) ->f32: 15 | return self.x + self.y 16 | 17 | class Vec3( Vec2 ): 18 | def __init__(self, z:f32): 19 | Vec2.__init__(self, x=400.0, y=20.0) 20 | self.z = z 21 | 22 | def sum(self) ->f32: 23 | return Vec2.sum(self) + self.z 24 | 25 | 26 | def main(): 27 | v = Vec3( 100.0 ) 28 | print v.sum() 29 | 30 | ``` -------------------------------------------------------------------------------- /examples/string.md: -------------------------------------------------------------------------------- 1 | String 2 | ------ 3 | the c++ backend translates strings into `std::string`. 4 | 5 | ```rusthon 6 | 7 | myglobal = 'hi' 8 | def main(): 9 | u = 'X' 10 | print len(u) 11 | ``` 12 | 13 | below the end of the string is indexed with `a[-1]`, negative indices must be given as literals. 14 | normal postive indices can be variables like `a[n]`. 15 | 16 | ```rusthon 17 | 18 | a = 'XYZ' 19 | print( a[0] == 'X' ) 20 | print( a[-1] == 'Z' ) 21 | print myglobal[-1] 22 | 23 | ``` 24 | 25 | string slice syntax 26 | ------------------- 27 | just lower and upper slicing is supported, step is not allowed. 28 | 29 | ```rusthon 30 | print( a[0:2] == 'XY' ) 31 | print a[0:2] 32 | print a[:2] == 'XY' 33 | 34 | print a[1:3] == 'YZ' 35 | print a[1:] == 'YZ' 36 | ``` 37 | 38 | builtins and methods 39 | 40 | ```rusthon 41 | print a.lower() 42 | 43 | print ord('A') ## should be 65 44 | print chr(65) ## should be 'A' 45 | 46 | v1 = a.split() 47 | print v1 48 | print len(v1) 49 | print v1[0] 50 | 51 | abc = 'a b c' 52 | print abc 53 | print abc.upper() 54 | ``` 55 | 56 | split into a vector, only single character splits are supported now. 57 | 58 | ```rusthon 59 | v2 = abc.split() 60 | print 'string split ok' 61 | print v2 62 | print 'should print 3:', len(v2) 63 | print 'v2[0]' 64 | print v2[0] 65 | ``` 66 | 67 | test if string is in a string. 68 | 69 | ```rusthon 70 | if 'b' in abc: 71 | print 'b in abc' 72 | else: 73 | print 'in test error' 74 | 75 | if 'b' in v2: 76 | print 'b in vector' 77 | else: 78 | print 'in array test error' 79 | 80 | print 'ok' 81 | 82 | ``` 83 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ## this just creates the command `transpile` for you, 3 | ## nothing is copied, this assumes that your pulling often from the git repo, 4 | ## and always want to stay in sync with the latest version. 5 | chmod +x pythia.py 6 | #sudo ln --symbolic --force `pwd`/rusthon.py /usr/local/bin/transpile ## linux only 7 | ## osx compatible 8 | sudo ln -s -f `pwd`/pythia.py /usr/local/bin/pythia 9 | -------------------------------------------------------------------------------- /make-linux-packages.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ## create DEB and RPM packages for Debian and Fedora. 3 | ## requires: FPM 4 | ## https://github.com/jordansissel/fpm 5 | ## apt-get install ruby-dev gcc 6 | ## gem install fpm 7 | 8 | rm *.deb 9 | rm *.rpm 10 | 11 | chmod +x rusthon.py 12 | sudo ln --symbolic --force /usr/lib/rusthon/rusthon.py /usr/bin/transpile 13 | 14 | ## debian 15 | fpm -s dir -t deb -a all -m "brett hartshorn " -n rusthon -v 0.9.6 /usr/bin/transpile ./rusthon.py=/usr/lib/rusthon/rusthon.py ./src=/usr/local/lib/rusthon/ 16 | 17 | ## check contents of deb 18 | dpkg -c rusthon_0.9.6_all.deb 19 | 20 | ## fedora -- requires rpmbuild -- which is not available in debian? 21 | fpm -s dir -t rpm -a noarch -n rusthon -v 0.9.6 /usr/bin/transpile ./rusthon.py=/usr/lib/rusthon/rusthon.py ./src=/usr/local/lib/rusthon/ 22 | 23 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: Pythia 2 | site_url: http://secureosv.news 3 | repo_url: https://github.com/secureosv/pythia 4 | docs_dir: doc 5 | 6 | pages: 7 | - Home: index.md 8 | - QuickStart: quick_start.md 9 | - CommandLine: getting_started.md 10 | - ExtendedMarkdown: markdown_format.md 11 | - Syntax: syntax.md 12 | - Lists: lists.md 13 | - MemoryModel: memory.md 14 | - Seastar: seastar.md 15 | - JavaScript: js_backend.md 16 | theme: readthedocs -------------------------------------------------------------------------------- /preview-docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | mkdocs serve 3 | echo "go to localhost:8000" 4 | 5 | -------------------------------------------------------------------------------- /regtests/asm/asm_hello.py: -------------------------------------------------------------------------------- 1 | ''' 2 | gcc inline assembly 3 | ''' 4 | #with asm( volatile=True, inputs=(a,b), outputs=(c,d), clobber=("cc", "memory") ): 5 | 6 | def test_single_input( a : int ) -> int: 7 | b = 0 8 | with asm( outputs=b, inputs=a, volatile=True, clobber='%ebx', alignstack=True ): 9 | movl %1, %%ebx; 10 | movl %%ebx, %0; 11 | return b 12 | 13 | def test_multi_input( a : int, b : int ) -> int: 14 | out = 0 15 | with asm( outputs=out, inputs=(a,b), volatile=True, clobber=('%ebx','memory') ): 16 | movl %1, %%ebx; 17 | addl %2, %%ebx; 18 | movl %%ebx, %0; 19 | return out 20 | 21 | 22 | def main(): 23 | x = test_single_input(999) 24 | print x ## should print 999 25 | 26 | y = test_multi_input(400, 20) 27 | print y ## should print 420 -------------------------------------------------------------------------------- /regtests/asm/asm_hello_rust.py: -------------------------------------------------------------------------------- 1 | ''' 2 | rust inline assembly 3 | ''' 4 | 5 | def test_single_input( a : int ) -> int: 6 | let mut b = 0 7 | with asm( outputs=b, inputs=a, volatile=True, clobber='%ebx', alignstack=True ): 8 | movl %1, %%ebx; 9 | movl %%ebx, %0; 10 | return b 11 | 12 | def test_multi_input( a : int, b : int ) -> int: 13 | let mut out = 0 14 | with asm( outputs=out, inputs=(a,b), volatile=True, clobber=('%ebx','memory') ): 15 | movl %1, %%ebx; 16 | addl %2, %%ebx; 17 | movl %%ebx, %0; 18 | return out 19 | 20 | 21 | def main(): 22 | x = test_single_input(999) 23 | print x ## should print 999 24 | 25 | y = test_multi_input(400, 20) 26 | print y ## should print 420 -------------------------------------------------------------------------------- /regtests/bench/add-opt.py: -------------------------------------------------------------------------------- 1 | ''' 2 | loop and add (integer) 3 | ''' 4 | from time import clock 5 | 6 | with (pointers, noexcept): 7 | class A: 8 | def __init__(self, x:int,y:int,z:int): 9 | self.x = x; self.y = y; self.z = z 10 | def add(self, other:A) ->A: 11 | a = A(self.x+other.x, self.y+other.y, self.z+other.z) 12 | return a 13 | def iadd(self, other:A): 14 | self.x += other.x 15 | self.y += other.y 16 | self.z += other.z 17 | 18 | class M: 19 | 20 | def f2(self, step:int, a:A, b:A, c:A, x:int,y:int,z:int) ->A: 21 | s = A(0,0,0) 22 | for j in range(step): 23 | u = A(x,y,z) 24 | w = a.add(u).add(b).add(c) 25 | s.iadd(w) 26 | return s 27 | 28 | def f1(self, x:int, y:int, a:A, b:A, c:A ) -> A: 29 | w = A(0,0,0) 30 | flip = False 31 | for i in range(x): 32 | if flip: 33 | flip = False 34 | w.iadd(self.f2(y, a,b,c, 1,2,3)) 35 | else: 36 | flip = True 37 | w.iadd(self.f2(y, a,b,c, 4,5,6)) 38 | return w 39 | 40 | def main(): 41 | m = M() 42 | xsteps = 1000 43 | ysteps = 100 44 | start = clock() 45 | n = -1000000 46 | a = A(n,n+1,n) 47 | b = A(n,n+2,n) 48 | c = A(n,n+3,n) 49 | w = m.f1(xsteps, ysteps, a,b,c) 50 | print(clock()-start) -------------------------------------------------------------------------------- /regtests/bench/add-typed-go.py: -------------------------------------------------------------------------------- 1 | ''' 2 | loop and add (integer) 3 | ''' 4 | from time import clock 5 | 6 | class A: 7 | def __init__(self, x:int,y:int,z:int): 8 | self.x = x; self.y = y; self.z = z 9 | 10 | def add(self, other:A) ->A: 11 | a = A(self.x+other.x, self.y+other.y, self.z+other.z) 12 | return a 13 | 14 | def iadd(self, other:A): 15 | self.x += other.x 16 | self.y += other.y 17 | self.z += other.z 18 | 19 | class M: 20 | 21 | def f2(self, step:int, a:A, b:A, c:A, x:int,y:int,z:int) ->A: 22 | s = A(0,0,0) 23 | for j in range(step): 24 | u = A(x,y,z) 25 | w = a.add(u).add(b).add(c) 26 | s.iadd(w) 27 | return s 28 | 29 | def f1(self, x:int, y:int, a:A, b:A, c:A ) -> A: 30 | w = A(0,0,0) 31 | flip = False 32 | for i in range(x): 33 | if flip: 34 | flip = False 35 | w.iadd(self.f2(y, a,b,c, 1,2,3)) 36 | else: 37 | flip = True 38 | w.iadd(self.f2(y, a,b,c, 4,5,6)) 39 | return w 40 | 41 | def main(): 42 | m = M() 43 | xsteps = 1000 44 | ysteps = 500 45 | start = clock() 46 | n = -1000000 47 | a = A(n,n+1,n) 48 | b = A(n,n+2,n) 49 | c = A(n,n+3,n) 50 | w = m.f1(xsteps, ysteps, a,b,c) 51 | print(clock()-start) 52 | print(w) ## go will not allow unused variables 53 | -------------------------------------------------------------------------------- /regtests/bench/add-typed-stack.py: -------------------------------------------------------------------------------- 1 | ''' 2 | loop and add (integer) 3 | ''' 4 | from time import clock 5 | 6 | with stack: 7 | class A: 8 | def __init__(self, x:int,y:int,z:int): 9 | self.x = x; self.y = y; self.z = z 10 | 11 | def add(self, other:A) ->A: 12 | a = A(self.x+other.x, self.y+other.y, self.z+other.z) 13 | return a 14 | 15 | def iadd(self, other:A): 16 | self.x += other.x 17 | self.y += other.y 18 | self.z += other.z 19 | 20 | class M: 21 | 22 | def f2(self, step:int, a:A, b:A, c:A, x:int,y:int,z:int) ->A: 23 | s = A(0,0,0) 24 | for j in range(step): 25 | u = A(x,y,z) 26 | w = a.add(u).add(b).add(c) 27 | s.iadd(w) 28 | return s 29 | 30 | def f1(self, x:int, y:int, a:A, b:A, c:A ) -> A: 31 | w = A(0,0,0) 32 | flip = False 33 | for i in range(x): 34 | if flip: 35 | flip = False 36 | w.iadd(self.f2(y, a,b,c, 1,2,3)) 37 | else: 38 | flip = True 39 | w.iadd(self.f2(y, a,b,c, 4,5,6)) 40 | return w 41 | 42 | def test(): 43 | m = M() 44 | xsteps = 1000 45 | ysteps = 500 46 | start = clock() 47 | n = -1000000 48 | a = A(n,n+1,n) 49 | b = A(n,n+2,n) 50 | c = A(n,n+3,n) 51 | w = m.f1(xsteps, ysteps, a,b,c) 52 | print(clock()-start) 53 | 54 | def main(): 55 | test() 56 | -------------------------------------------------------------------------------- /regtests/bench/add-typed.py: -------------------------------------------------------------------------------- 1 | ''' 2 | loop and add (integer) 3 | ''' 4 | from time import clock 5 | 6 | class A: 7 | def __init__(self, x:int,y:int,z:int): 8 | self.x = x; self.y = y; self.z = z 9 | 10 | def add(self, other:A) ->A: 11 | a = A(self.x+other.x, self.y+other.y, self.z+other.z) 12 | return a 13 | 14 | def iadd(self, other:A): 15 | self.x += other.x 16 | self.y += other.y 17 | self.z += other.z 18 | 19 | class M: 20 | 21 | def f2(self, step:int, a:A, b:A, c:A, x:int,y:int,z:int) ->A: 22 | s = A(0,0,0) 23 | for j in range(step): 24 | u = A(x,y,z) 25 | w = a.add(u).add(b).add(c) 26 | s.iadd(w) 27 | return s 28 | 29 | def f1(self, x:int, y:int, a:A, b:A, c:A ) -> A: 30 | w = A(0,0,0) 31 | flip = False 32 | for i in range(x): 33 | if flip: 34 | flip = False 35 | w.iadd(self.f2(y, a,b,c, 1,2,3)) 36 | else: 37 | flip = True 38 | w.iadd(self.f2(y, a,b,c, 4,5,6)) 39 | return w 40 | 41 | def main(): 42 | m = M() 43 | xsteps = 1000 44 | ysteps = 500 45 | start = clock() 46 | n = -1000000 47 | a = A(n,n+1,n) 48 | b = A(n,n+2,n) 49 | c = A(n,n+3,n) 50 | w = m.f1(xsteps, ysteps, a,b,c) 51 | print(clock()-start) 52 | print(w) ## go will not allow unused variables 53 | -------------------------------------------------------------------------------- /regtests/bench/add.py: -------------------------------------------------------------------------------- 1 | ''' 2 | loop and add (integer) 3 | ''' 4 | from time import clock 5 | 6 | class A: 7 | def __init__(self, x,y,z): 8 | self.x = x; self.y = y; self.z = z 9 | 10 | def add(self, other): 11 | return A(self.x+other.x, self.y+other.y, self.z+other.z) 12 | 13 | def iadd(self, other): 14 | self.x += other.x 15 | self.y += other.y 16 | self.z += other.z 17 | 18 | class M: 19 | 20 | def f2(self, step, a, b, c, x,y,z): 21 | s = A(0,0,0) 22 | for j in range(step): 23 | u = A(x,y,z) 24 | w = a.add(u).add(b).add(c) 25 | s.iadd(w) 26 | return s 27 | 28 | def f1(self, x, y, a, b, c ): 29 | w = A(0,0,0) 30 | flip = False 31 | for i in range(x): 32 | if flip: 33 | flip = False 34 | w.iadd(self.f2(y, a,b,c, 1,2,3)) 35 | else: 36 | flip = True 37 | w.iadd(self.f2(y, a,b,c, 4,5,6)) 38 | return w 39 | 40 | def main(): 41 | m = M() 42 | xsteps = 1000 43 | ysteps = 500 44 | start = clock() 45 | n = -1000000 46 | a = A(n,n+1,n) 47 | b = A(n,n+2,n) 48 | c = A(n,n+3,n) 49 | w = m.f1(xsteps, ysteps, a,b,c) 50 | print(clock()-start) 51 | print(w) ## go will not allow unused variables 52 | 53 | main() -------------------------------------------------------------------------------- /regtests/bench/copy_list-typed-go.py: -------------------------------------------------------------------------------- 1 | '''copy list micro benchmark''' 2 | 3 | from time import clock 4 | from runtime import * 5 | 6 | def copy_list( a:[]int, n:int ) -> [][]int: 7 | x = [][]int() 8 | for i in range(n): 9 | b = a[:] 10 | for j in range(10): 11 | b.append( j ) 12 | x.append( b[...] ) 13 | return x 14 | 15 | def test(): 16 | a = range(1000) 17 | times = []float64() 18 | for i in range(4): 19 | t0 = clock() 20 | _ = copy_list(a, 10000) 21 | tk = clock() 22 | times.append(tk - t0) 23 | avg = 0.0 24 | for t in times: 25 | avg += t 26 | avg /= float64( len(times) ) 27 | print(avg) 28 | 29 | def main(): 30 | print 'starting...' 31 | test() 32 | 33 | -------------------------------------------------------------------------------- /regtests/bench/copy_list-typed-stack.py: -------------------------------------------------------------------------------- 1 | '''copy list micro benchmark''' 2 | 3 | from time import clock 4 | from runtime import * 5 | with stack: 6 | def copy_list( a:[]int, n ) -> [][]int: 7 | x = [][]int() 8 | for i in range(n): 9 | b = a[:] 10 | for j in range(10): 11 | b.push_back( j ) 12 | x.push_back( b ) 13 | return x 14 | 15 | def test(): 16 | a = range(1000) 17 | times = []double() 18 | for i in range(4): 19 | t0 = clock() 20 | res = copy_list(addr(a), 10000) 21 | tk = clock() 22 | times.append(tk - t0) 23 | avg = sumd(times) / len(times) 24 | print(avg) 25 | 26 | def main(): 27 | test() 28 | 29 | main() -------------------------------------------------------------------------------- /regtests/bench/copy_list-typed.py: -------------------------------------------------------------------------------- 1 | '''copy list micro benchmark''' 2 | 3 | from time import clock 4 | from runtime import * 5 | 6 | def copy_list( a:[]int, n:int ) -> [][]int: 7 | x = [][]int() 8 | for i in range(n): 9 | b = a[:] 10 | for j in range(10): 11 | b.push_back( j ) 12 | x.append( b ) 13 | return x 14 | 15 | def test(): 16 | a = range(1000) 17 | times = []double() 18 | for i in range(4): 19 | t0 = clock() 20 | res = copy_list(a, 10000) 21 | tk = clock() 22 | times.append(tk - t0) 23 | avg = sumd(times) / len(times) 24 | print(avg) 25 | 26 | def main(): 27 | test() 28 | 29 | main() -------------------------------------------------------------------------------- /regtests/bench/copy_list.py: -------------------------------------------------------------------------------- 1 | '''copy list micro benchmark''' 2 | 3 | from time import time 4 | from runtime import * 5 | 6 | def test(): 7 | a = list(range(1000)) 8 | times = [] 9 | for i in range(4): 10 | t0 = time() 11 | res = copy_list(a, 10000) 12 | tk = time() 13 | times.append(tk - t0) 14 | avg = sum(times) / len(times) 15 | print(avg) 16 | 17 | def copy_list( a, n ): 18 | x = [] 19 | for i in range(n): 20 | b = a[:] 21 | for j in range(10): 22 | b.append( j ) 23 | x.append( b ) 24 | return x 25 | 26 | 27 | 28 | def main(): 29 | test() 30 | 31 | main() -------------------------------------------------------------------------------- /regtests/bench/float-typed-stack.py: -------------------------------------------------------------------------------- 1 | ''' 2 | float numbers 3 | ''' 4 | 5 | from time import clock 6 | 7 | POINTS = 100000 8 | 9 | with stack: 10 | class Point(object): 11 | 12 | def __init__(self, i:float): 13 | let self.x:float = std::sin(i) 14 | let self.y:float = std::cos(i) * 3 15 | let self.z:float = (self.x * self.x) / 2 16 | 17 | def normalize(self) ->self: 18 | norm = std::sqrt( 19 | self.x * self.x + self.y * self.y + self.z * self.z 20 | ) 21 | self.x /= norm 22 | self.y /= norm 23 | self.z /= norm 24 | return self 25 | 26 | def maximize(self, other:Point ) ->self: 27 | if self.x < other.x: self.x = other.x 28 | if self.y < other.y: self.y = other.y 29 | if self.z < other.z: self.z = other.z 30 | return self 31 | 32 | 33 | def maximize( points:[]Point ) ->Point: 34 | nxt = points[0] 35 | slice = points[1:] 36 | for p in slice: 37 | nxt = nxt.maximize(p) 38 | return nxt 39 | 40 | def benchmark( n:int ) -> Point: 41 | #points = []Point( 42 | # Point(i as float) for i in range(n) 43 | #) 44 | points = []Point() 45 | for i in range(n): 46 | points.append(Point(i as float)) 47 | 48 | for p in points: 49 | p.normalize() 50 | 51 | return maximize(points) 52 | 53 | 54 | def test( arg:int ) ->[]float: 55 | times = []float() 56 | for i in range(arg): 57 | t0 = clock() 58 | o = benchmark(POINTS) 59 | #with stack: 60 | # print 'x:', o.x 61 | # print 'y:', o.y 62 | # print 'z:', o.z 63 | tk = clock() 64 | times.append(tk - t0) 65 | return times 66 | 67 | def main(): 68 | times = test( 3 ) 69 | avg = sumf(times) / len(times) 70 | print( avg ) 71 | -------------------------------------------------------------------------------- /regtests/bench/float-typed.py: -------------------------------------------------------------------------------- 1 | ''' 2 | float numbers 3 | ''' 4 | 5 | from time import clock 6 | 7 | POINTS = 100000 8 | 9 | class Point(object): 10 | 11 | def __init__(self, i:float): 12 | let self.x:float = std::sin(i) 13 | let self.y:float = std::cos(i) * 3 14 | let self.z:float = (self.x * self.x) / 2 15 | 16 | def normalize(self) ->self: 17 | norm = std::sqrt( 18 | self.x * self.x + self.y * self.y + self.z * self.z 19 | ) 20 | self.x /= norm 21 | self.y /= norm 22 | self.z /= norm 23 | return self 24 | 25 | def maximize(self, other:Point ) ->self: 26 | if self.x < other.x: self.x = other.x 27 | if self.y < other.y: self.y = other.y 28 | if self.z < other.z: self.z = other.z 29 | return self 30 | 31 | 32 | def maximize( points:[]Point ) ->Point: 33 | nxt = points[0] 34 | slice = points[1:] 35 | for p in slice: 36 | nxt = nxt.maximize(p) 37 | return nxt 38 | 39 | def benchmark( n:int ) -> Point: 40 | #points = []Point( 41 | # Point(i as float) for i in range(n) 42 | #) 43 | points = []Point() 44 | for i in range(n): 45 | points.append(Point(i as float)) 46 | 47 | for p in points: 48 | p.normalize() 49 | 50 | return maximize(points) 51 | 52 | 53 | def test( arg:int ) ->[]float: 54 | times = []float() 55 | for i in range(arg): 56 | t0 = clock() 57 | o = benchmark(POINTS) 58 | #print 'x:', o.x 59 | #print 'y:', o.y 60 | #print 'z:', o.z 61 | tk = clock() 62 | times.append(tk - t0) 63 | return times 64 | 65 | def main(): 66 | times = test( 3 ) 67 | avg = sumf(times) / len(times) 68 | print( avg ) 69 | -------------------------------------------------------------------------------- /regtests/bench/float.py: -------------------------------------------------------------------------------- 1 | ''' 2 | float numbers 3 | ''' 4 | 5 | from time import clock 6 | from math import sin, cos, sqrt 7 | from runtime import * 8 | 9 | def main(): 10 | times = test( 3 ) 11 | avg = sum(times) / len(times) 12 | print( avg ) 13 | 14 | 15 | #class Point(object): ## not allowed in RapydScript 16 | class Point: 17 | def __init__(self, i): 18 | self.x = sin(i) 19 | self.y = cos(i) * 3 20 | self.z = (self.x * self.x) / 2 21 | 22 | def __repr__(self): 23 | return "Point: x=%s, y=%s, z=%s" % (self.x, self.y, self.z) 24 | 25 | def normalize(self): 26 | norm = sqrt(self.x * self.x + self.y * self.y + self.z * self.z) 27 | self.x /= norm 28 | self.y /= norm 29 | self.z /= norm 30 | 31 | def maximize(self, other): 32 | if self.x < other.x: self.x = other.x 33 | if self.y < other.y: self.y = other.y 34 | if self.z < other.z: self.z = other.z 35 | return self 36 | 37 | 38 | def maximize(points): 39 | next = points[0] 40 | for p in points[1:]: 41 | next = next.maximize(p) 42 | return next 43 | 44 | def benchmark(n): 45 | points = [None] * n 46 | for i in range(n): 47 | points[i] = Point(i) 48 | for p in points: 49 | p.normalize() 50 | return maximize(points) 51 | 52 | POINTS = 100000 53 | 54 | def test(arg): 55 | times = [] 56 | for i in range(arg): 57 | t0 = clock() 58 | o = benchmark(POINTS) 59 | #print( 'x:', o.x) 60 | #print( 'y:', o.y) 61 | #print( 'z:', o.z) 62 | tk = clock() 63 | times.append(tk - t0) 64 | return times 65 | 66 | 67 | main() -------------------------------------------------------------------------------- /regtests/bench/mandelbrot.py: -------------------------------------------------------------------------------- 1 | """mandelbrot benchmark""" 2 | from time import time 3 | 4 | def pprint(arr, w): 5 | x = [] 6 | for a in arr: 7 | x.append(a) 8 | if len(x) >= w: 9 | print( [ round(y,2) for y in x] ) 10 | x = [] 11 | 12 | def mandelbrot_numpy(size=512, exit_limit=100): 13 | img_array = numpy.zeros([size, size], int) 14 | for y in range(size): 15 | for x in range(size): 16 | c = complex(x / float(size) * 4 - 2, 17 | y / float(size) * 4 - 2) 18 | z = c 19 | for i in range(exit_limit): 20 | z = (z**2) + c 21 | img_array[y, x] += 1 22 | if abs(z) > 2: 23 | # z is escaping to infinity, so point is not in set 24 | break 25 | else: 26 | # if loop is exausted, point is inside the set 27 | img_array[y, x] = 0 28 | return img_array 29 | 30 | 31 | def main(): 32 | 33 | @returns( array=[512,512] ) 34 | @typedef( x=float, y=float, tempX=float, i=int, runaway=int, c=vec2) 35 | @gpu.main 36 | def gpufunc(): 37 | c = get_global_id() 38 | x = 0.0 39 | y = 0.0 40 | tempX = 0.0 41 | i = 0 42 | runaway = 0 43 | for i in range(100): 44 | tempX = x * x - y * y + float(c.x) 45 | y = 2.0 * x * y + float(c.y) 46 | x = tempX 47 | if runaway == 0 and x * x + y * y > 100.0: 48 | runaway = i 49 | 50 | return float(runaway) * 0.01 51 | 52 | start = time() 53 | 54 | if PYTHON == 'PYTHONJS': 55 | res = gpufunc() 56 | #pprint(res, 32) 57 | else: 58 | res = mandelbrot_numpy() 59 | 60 | print(time()-start) 61 | -------------------------------------------------------------------------------- /regtests/bench/new_list.py: -------------------------------------------------------------------------------- 1 | '''new list micro benchmark''' 2 | 3 | from time import time 4 | 5 | def main(): 6 | if PYTHON=='PYTHONJS': 7 | pythonjs.configure( direct_operator='+' ) 8 | pythonjs.configure( direct_keys=True ) 9 | pass 10 | 11 | times = [] 12 | a = [] 13 | for i in range(10): 14 | t0 = time() 15 | for j in range(100000): 16 | b = [1,2,3,4,5,6,7,8,9] 17 | a.append( b ) 18 | tk = time() 19 | times.append(tk - t0) 20 | avg = sum(times) / len(times) 21 | print(avg) 22 | 23 | 24 | -------------------------------------------------------------------------------- /regtests/bench/operator_overloading-typed-stack.py: -------------------------------------------------------------------------------- 1 | ''' 2 | bretts simple operator overloading benchmark 3 | ''' 4 | 5 | from time import clock 6 | from runtime import * 7 | 8 | with stack: 9 | class Vector: 10 | def __init__(self, x:double, y:double, z:double): 11 | self.x = x 12 | self.y = y 13 | self.z = z 14 | 15 | def __add__(self, other:Vector) ->self: 16 | return Vector(self.x+other.x, self.y+other.y, self.z+other.z) 17 | 18 | def __mul__(self, other:Vector) ->self: 19 | return Vector(self.x*other.x, self.y*other.y, self.z*other.z) 20 | 21 | 22 | #def benchmark(n) ->[][]Vector: 23 | def benchmark(n): 24 | a = [ Vector(i*0.09,i*0.05, i*0.01) for i in range(n)] 25 | b = [ Vector(i*0.08,i*0.04, i*0.02) for i in range(n)] 26 | c = []Vector() 27 | d = []Vector() 28 | 29 | for j in range(n): 30 | u = a[j] 31 | v = b[j] 32 | c.append( u+v ) 33 | d.append( u*v ) 34 | 35 | #return [][]Vector(c,d) 36 | #return c, d 37 | 38 | POINTS = 100000 39 | 40 | def test(arg) ->[]double: 41 | times = []double() 42 | for i in range(arg): 43 | t0 = clock() 44 | benchmark(POINTS) 45 | #o = benchmark(POINTS) 46 | tk = clock() 47 | times.append(tk - t0) 48 | return times 49 | 50 | 51 | def main(): 52 | times = test( 3 ) 53 | avg = sumd(times) / len(times) 54 | print( avg ) 55 | 56 | -------------------------------------------------------------------------------- /regtests/bench/operator_overloading-typed.py: -------------------------------------------------------------------------------- 1 | ''' 2 | bretts simple operator overloading benchmark 3 | ''' 4 | 5 | from time import clock 6 | from runtime import * 7 | 8 | 9 | class Vector: 10 | def __init__(self, x:double, y:double, z:double): 11 | self.x = x 12 | self.y = y 13 | self.z = z 14 | 15 | def __add__(self, other:Vector) ->self: 16 | return Vector(self.x+other.x, self.y+other.y, self.z+other.z) 17 | 18 | def __mul__(self, other:Vector) ->self: 19 | return Vector(self.x*other.x, self.y*other.y, self.z*other.z) 20 | 21 | 22 | #def benchmark(n) ->[][]Vector: 23 | def benchmark(n): 24 | a = [ Vector(i*0.09,i*0.05, i*0.01) for i in range(n)] 25 | b = [ Vector(i*0.08,i*0.04, i*0.02) for i in range(n)] 26 | c = []Vector() 27 | d = []Vector() 28 | 29 | for j in range(n): 30 | u = a[j][...] 31 | v = b[j] 32 | c.append( u+v ) 33 | d.append( u*v ) 34 | 35 | #return [][]Vector(c,d) 36 | #return c, d 37 | 38 | POINTS = 100000 39 | 40 | def test(arg) ->[]double: 41 | times = []double() 42 | for i in range(arg): 43 | t0 = clock() 44 | benchmark(POINTS) 45 | #o = benchmark(POINTS) 46 | tk = clock() 47 | times.append(tk - t0) 48 | return times 49 | 50 | 51 | def main(): 52 | times = test( 3 ) 53 | avg = sumd(times) / len(times) 54 | print( avg ) 55 | 56 | -------------------------------------------------------------------------------- /regtests/bench/operator_overloading.py: -------------------------------------------------------------------------------- 1 | ''' 2 | bretts simple operator overloading benchmark 3 | ''' 4 | 5 | from time import clock 6 | from runtime import * 7 | 8 | def main(): 9 | times = test( 3 ) 10 | avg = sum(times) / len(times) 11 | print( avg ) 12 | 13 | 14 | class Vector: 15 | def __init__(self, x,y,z): 16 | self.x = x 17 | self.y = y 18 | self.z = z 19 | 20 | def __add__(self, other): 21 | return Vector(self.x+other.x, self.y+other.y, self.z+other.z) 22 | 23 | def __mul__(self, other): 24 | return Vector(self.x*other.x, self.y*other.y, self.z*other.z) 25 | 26 | 27 | def benchmark(n): 28 | a = [ Vector(i*0.09,i*0.05, i*0.01) for i in range(n)] 29 | b = [ Vector(i*0.08,i*0.04, i*0.02) for i in range(n)] 30 | c = [] 31 | d = [] 32 | for j in range(n): 33 | with oo: 34 | u = a[j] 35 | v = b[j] 36 | c.append( u+v ) 37 | d.append( u*v ) 38 | 39 | return [c,d] 40 | 41 | POINTS = 100000 42 | 43 | def test(arg): 44 | times = [] 45 | for i in range(arg): 46 | t0 = clock() 47 | o = benchmark(POINTS) 48 | tk = clock() 49 | times.append(tk - t0) 50 | return times 51 | 52 | 53 | main() -------------------------------------------------------------------------------- /regtests/bench/operator_overloading_functor.py: -------------------------------------------------------------------------------- 1 | ''' 2 | bretts simple operator overloading benchmark 3 | ''' 4 | 5 | from time import clock 6 | from runtime import * 7 | 8 | def main(): 9 | times = test( 3 ) 10 | avg = sum(times) / len(times) 11 | print( avg ) 12 | 13 | UID = 0 14 | class Vector: 15 | def __init__(self, x,y,z): 16 | global UID 17 | UID += 1 18 | self.id = UID 19 | self.x = x 20 | self.y = y 21 | self.z = z 22 | 23 | def add(self, other): 24 | return Vector(self.x+other.x, self.y+other.y, self.z+other.z) 25 | 26 | def mul(self, other): 27 | return Vector(self.x*other.x, self.y*other.y, self.z*other.z) 28 | 29 | def __call__(self): 30 | return self.id 31 | 32 | def benchmark(n): 33 | a = [ Vector(i*0.09,i*0.05, i*0.01) for i in range(n)] 34 | b = [ Vector(i*0.08,i*0.04, i*0.02) for i in range(n)] 35 | c = {} 36 | for j in range(n): 37 | u = a[j] 38 | v = b[j] 39 | c[u()] = u.add(v) 40 | c[v()] = u.mul(v) 41 | return c 42 | 43 | POINTS = 10000 44 | 45 | def test(arg): 46 | times = [] 47 | for i in range(arg): 48 | t0 = clock() 49 | o = benchmark(POINTS) 50 | tk = clock() 51 | times.append(tk - t0) 52 | return times 53 | 54 | 55 | main() -------------------------------------------------------------------------------- /regtests/bench/operator_overloading_nonfunctor.py: -------------------------------------------------------------------------------- 1 | ''' 2 | bretts simple operator overloading benchmark 3 | ''' 4 | 5 | from time import clock 6 | from runtime import * 7 | 8 | def main(): 9 | times = test( 3 ) 10 | avg = sum(times) / len(times) 11 | print( avg ) 12 | 13 | UID = 0 14 | class Vector: 15 | def __init__(self, x,y,z): 16 | global UID 17 | UID += 1 18 | self.id = UID 19 | self.x = x 20 | self.y = y 21 | self.z = z 22 | 23 | def add(self, other): 24 | return Vector(self.x+other.x, self.y+other.y, self.z+other.z) 25 | 26 | def mul(self, other): 27 | return Vector(self.x*other.x, self.y*other.y, self.z*other.z) 28 | 29 | def call(self): 30 | return self.id 31 | 32 | def benchmark(n): 33 | a = [ Vector(i*0.09,i*0.05, i*0.01) for i in range(n)] 34 | b = [ Vector(i*0.08,i*0.04, i*0.02) for i in range(n)] 35 | c = {} 36 | for j in range(n): 37 | u = a[j] 38 | v = b[j] 39 | c[u.call()] = u.add(v) 40 | c[v.call()] = u.mul(v) 41 | return c 42 | 43 | POINTS = 10000 44 | 45 | def test(arg): 46 | times = [] 47 | for i in range(arg): 48 | t0 = clock() 49 | o = benchmark(POINTS) 50 | tk = clock() 51 | times.append(tk - t0) 52 | return times 53 | 54 | 55 | main() -------------------------------------------------------------------------------- /regtests/bench/recursive_fib-typed-go.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Fibonacci Sequence 3 | ''' 4 | 5 | from time import clock 6 | 7 | def F(n:int) ->int: 8 | if n == 0: return 0 9 | elif n == 1: return 1 10 | else: return F(n-1)+F(n-2) 11 | 12 | def main(): 13 | start = clock() 14 | _ = F( 32 ) 15 | print(clock()-start) 16 | 17 | -------------------------------------------------------------------------------- /regtests/bench/recursive_fib-typed.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Fibonacci Sequence 3 | ''' 4 | 5 | from time import clock 6 | 7 | def F(n:int) ->int: 8 | if n == 0: return 0 9 | elif n == 1: return 1 10 | else: return F(n-1)+F(n-2) 11 | 12 | def main(): 13 | start = clock() 14 | a = F( 32 ) 15 | print(clock()-start) 16 | 17 | 18 | -------------------------------------------------------------------------------- /regtests/bench/recursive_fib.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Fibonacci Sequence 3 | ''' 4 | 5 | from time import clock 6 | 7 | def F(n): 8 | if n == 0: return 0 9 | elif n == 1: return 1 10 | else: return F(n-1)+F(n-2) 11 | 12 | def main(): 13 | start = clock() 14 | a = F( 32 ) 15 | print(clock()-start) 16 | 17 | 18 | main() -------------------------------------------------------------------------------- /regtests/bench/simd_float32vec.py: -------------------------------------------------------------------------------- 1 | """simd float32vec micro benchmark""" 2 | from time import time 3 | from random import random 4 | 5 | ## SIMD in dart broken down into multiple float32x4 instances, with multiply implemented by looping 6 | ## over each element is slower than CPython with NumPy for an array larger than 32 elements. 7 | ## 64 elements runs about half the speed of NumPy in CPython. 8 | 9 | def main(): 10 | ARRAY_SIZE = 32 ## note, size must be divisible by 4 11 | x = [] 12 | y = [] 13 | z = [] 14 | for i in range( ARRAY_SIZE ): 15 | x.append( random()+0.5 ) 16 | y.append( random()+0.5 ) 17 | z.append( random()+0.5 ) 18 | 19 | a = numpy.array( x, dtype=numpy.float32 ) 20 | b = numpy.array( y, dtype=numpy.float32 ) 21 | c = numpy.array( z, dtype=numpy.float32 ) 22 | 23 | ## start benchmark 24 | start = time() 25 | 26 | arr = [] 27 | for i in range(20000): 28 | arr.append( a*b*c ) 29 | 30 | print(time()-start) -------------------------------------------------------------------------------- /regtests/bench/simd_float32x4.py: -------------------------------------------------------------------------------- 1 | """simd float32x4 micro benchmark""" 2 | from time import time 3 | 4 | def main(): 5 | start = time() 6 | float32x4 a = numpy.array( [1.0001, 1.0002, 1.0003, 1.0004], dtype=numpy.float32 ) 7 | float32x4 b = numpy.array( [1.00009, 1.00008, 1.00007, 1.00006], dtype=numpy.float32 ) 8 | float32x4 c = numpy.array( [1.00005, 1.00004, 1.00003, 1.00002], dtype=numpy.float32 ) 9 | 10 | arr = [] 11 | for i in range(20000): 12 | c *= a*b 13 | arr.append( a*b*c ) 14 | 15 | print(time()-start) -------------------------------------------------------------------------------- /regtests/bench/thread_collision-typed.py: -------------------------------------------------------------------------------- 1 | ''' 2 | multi-threading 3 | ''' 4 | 5 | from time import clock 6 | THREADS=2 7 | 8 | A = 0 9 | B = 0 10 | C = 0 11 | 12 | def test_globals(): 13 | global A, B, C 14 | for i in range(1024*1024): 15 | A += 1 16 | B += 2 17 | C = A + B 18 | 19 | def test_globals_tm(): 20 | global A, B, C 21 | for i in range(1024*1024): 22 | with atomic: 23 | A += 1 24 | B += 2 25 | C = A + B 26 | 27 | def test_nosync(): 28 | global A,B,C 29 | A = 0 30 | B = 0 31 | C = 0 32 | 33 | threads = []std::thread() 34 | for i in range(THREADS): 35 | t = spawn( test_globals ) 36 | threads.append( t ) 37 | 38 | for t in threads: 39 | t.join() 40 | 41 | print A 42 | print B 43 | print C 44 | 45 | 46 | def main(): 47 | print 'testing transactional atomic' 48 | starttime = clock() 49 | 50 | tmthreads = []std::thread() 51 | for i in range(THREADS): 52 | t = spawn( test_globals_tm ) 53 | tmthreads.append( t ) 54 | 55 | for t in tmthreads: 56 | t.join() 57 | 58 | print clock()-starttime 59 | 60 | print 'A:', A 61 | print 'B:', B 62 | print 'C:', C 63 | -------------------------------------------------------------------------------- /regtests/bench/thread_collision.py: -------------------------------------------------------------------------------- 1 | ''' 2 | multi-threading (python3 version) 3 | https://docs.python.org/3/library/threading.html 4 | ''' 5 | 6 | from time import clock 7 | import threading 8 | 9 | THREADS=2 10 | lock = threading.Lock() 11 | 12 | A = 0 13 | B = 0 14 | C = 0 15 | 16 | def test_globals(): 17 | global A, B, C 18 | for i in range(1024*1024): 19 | lock.acquire() 20 | A += 1 21 | B += 2 22 | C = A + B 23 | lock.release() 24 | 25 | 26 | def main(): 27 | print( 'starting threading test') 28 | starttime = clock() 29 | threads = [] 30 | for i in range(THREADS): 31 | t = threading.Thread( target=test_globals, args=() ) 32 | t.start() 33 | threads.append( t ) 34 | 35 | for t in threads: 36 | t.join() 37 | 38 | print( clock()-starttime) 39 | print('A:', A) 40 | print('B:', B) 41 | print('C:', C) 42 | 43 | main() -------------------------------------------------------------------------------- /regtests/bench/thread_shared_vector-pypy.py: -------------------------------------------------------------------------------- 1 | ''' 2 | multi-threading (pypy STM version) 3 | note: creating too many TransactionQueue's in a loop can cause freeze. 4 | ''' 5 | 6 | from time import clock 7 | import transaction 8 | 9 | THREADS=2 10 | Checked = transaction.stmset() 11 | Primes = transaction.stmset() 12 | 13 | def is_prime(n): 14 | hits = 0 15 | for x in range(2, n): 16 | for y in range(2, n): 17 | if x*y == n: 18 | hits += 1 19 | if hits > 1: 20 | return False 21 | return True 22 | 23 | def findprimes(start, end): 24 | for i in range(start, end): 25 | if i not in Checked: 26 | Checked.add(i) 27 | if is_prime(i): 28 | Primes.add(i) 29 | 30 | def main(): 31 | print( 'starting threading test') 32 | starttime = clock() 33 | threads = [] 34 | start = 0 35 | #for i in range(THREADS): ## slower than TransactionQueue 36 | # t = transaction.thread.start_new_thread( findprimes, args=(start, 1000,) ) 37 | # threads.append( t ) 38 | # start += 500 39 | 40 | tq = transaction.TransactionQueue() 41 | for i in range(1000): 42 | def func(num): 43 | if is_prime(num): 44 | Primes.add(num) 45 | tq.add(func, i) 46 | #if i == 500: tq.run() 47 | tq.run() 48 | 49 | #while len(Primes) != 181: 50 | # #print len(Primes) 51 | # pass 52 | assert len(Primes)==181 53 | 54 | print( clock()-starttime) 55 | print(Primes) 56 | 57 | main() -------------------------------------------------------------------------------- /regtests/bench/thread_shared_vector-typed-stack.py: -------------------------------------------------------------------------------- 1 | ''' 2 | multi-threading (pythia stack lock/STM free version) 3 | ''' 4 | 5 | from time import clock 6 | from time import sleep 7 | 8 | THREADS=2 9 | macro( N=1000 ) 10 | with stack: 11 | let Checked : [N]bool 12 | let Primes : [N]bool 13 | 14 | def is_prime(n:int) ->bool: 15 | hits = 0 16 | for x in range(2, n): 17 | for y in range(2, n): 18 | if x*y == n: 19 | hits += 1 20 | if hits > 1: 21 | return False 22 | return True 23 | 24 | def findprimes(start:int, end:int): 25 | invec = False 26 | ispri = False 27 | found = 0 28 | for i in range(start, end): 29 | invec = Checked[i] 30 | if not invec: 31 | Checked[i] = True 32 | ispri = is_prime(i) 33 | if ispri: 34 | #found += 1 35 | Primes[i] = True 36 | 37 | #print 'thread found:', found 38 | 39 | def main(): 40 | print( 'starting shared vector test') 41 | starttime = clock() 42 | threads = []std::thread() 43 | start = 0 44 | for i in range(THREADS): 45 | t = spawn(findprimes(start, 1000)) 46 | threads.append( t ) 47 | start += 500 48 | 49 | for t in threads: 50 | t.join() 51 | 52 | p = []int() 53 | with stack: 54 | for i in range(N): 55 | if Primes[i]: 56 | p->push_back(i) 57 | #print i 58 | 59 | print( clock()-starttime) 60 | assert len(p)==181 61 | -------------------------------------------------------------------------------- /regtests/bench/thread_shared_vector.py: -------------------------------------------------------------------------------- 1 | ''' 2 | multi-threading (python3 version) 3 | https://docs.python.org/3/library/threading.html 4 | ''' 5 | 6 | from time import clock 7 | import threading 8 | 9 | THREADS=2 10 | Checked = [] 11 | Primes = [] 12 | 13 | def is_prime(n): 14 | hits = 0 15 | for x in range(2, n): 16 | for y in range(2, n): 17 | if x*y == n: 18 | hits += 1 19 | if hits > 1: 20 | return False 21 | return True 22 | 23 | def findprimes(start, end): 24 | for i in range(start, end): 25 | if i not in Checked: 26 | Checked.append(i) 27 | if is_prime(i): 28 | Primes.append(i) 29 | 30 | def main(): 31 | print( 'starting threading test') 32 | starttime = clock() 33 | threads = [] 34 | start = 0 35 | for i in range(THREADS): 36 | t = threading.Thread( target=findprimes, args=(start, 1000,) ) 37 | t.start() 38 | threads.append( t ) 39 | start += 500 40 | 41 | for t in threads: 42 | t.join() 43 | 44 | print( clock()-starttime) 45 | print(Primes) 46 | 47 | main() -------------------------------------------------------------------------------- /regtests/bench/typed_int.py: -------------------------------------------------------------------------------- 1 | """int static type""" 2 | from time import time 3 | 4 | def F(i, n, arr): 5 | int i 6 | list arr 7 | while i < n: 8 | 9 | arr.append( i*2 ) 10 | arr.append( i*4 ) 11 | arr.append( i*8 ) 12 | arr.append( i*16 ) 13 | arr.append( i*32 ) 14 | arr.append( i*64 ) 15 | arr.append( i*128 ) 16 | arr.append( i*256 ) 17 | arr.append( i*512 ) 18 | arr.append( i*1024 ) 19 | arr.append( i*2048 ) 20 | arr.append( i*4096 ) 21 | 22 | arr.append( i//2 ) 23 | arr.append( i//4 ) 24 | arr.append( i//8 ) 25 | arr.append( i//16 ) 26 | arr.append( i//32 ) 27 | arr.append( i//64 ) 28 | arr.append( i//128 ) 29 | arr.append( i//256 ) 30 | arr.append( i//512 ) 31 | arr.append( i//1024 ) 32 | arr.append( i//2048 ) 33 | arr.append( i//4096 ) 34 | 35 | for x in range(100): 36 | arr.append( i+x ) 37 | 38 | i += 1 39 | 40 | 41 | def main(): 42 | start = time() 43 | F(0, 10000, []) 44 | F(0, 10000, []) 45 | F(0, 10000, []) 46 | print( time()-start ) 47 | -------------------------------------------------------------------------------- /regtests/bench/untyped_int.py: -------------------------------------------------------------------------------- 1 | """int static type""" 2 | from time import time 3 | 4 | def F(i, n, arr): 5 | 6 | while i < n: 7 | 8 | arr.append( i*2 ) 9 | arr.append( i*4 ) 10 | arr.append( i*8 ) 11 | arr.append( i*16 ) 12 | arr.append( i*32 ) 13 | arr.append( i*64 ) 14 | arr.append( i*128 ) 15 | arr.append( i*256 ) 16 | arr.append( i*512 ) 17 | arr.append( i*1024 ) 18 | arr.append( i*2048 ) 19 | arr.append( i*4096 ) 20 | 21 | arr.append( i//2 ) 22 | arr.append( i//4 ) 23 | arr.append( i//8 ) 24 | arr.append( i//16 ) 25 | arr.append( i//32 ) 26 | arr.append( i//64 ) 27 | arr.append( i//128 ) 28 | arr.append( i//256 ) 29 | arr.append( i//512 ) 30 | arr.append( i//1024 ) 31 | arr.append( i//2048 ) 32 | arr.append( i//4096 ) 33 | 34 | for x in range(100): 35 | arr.append( i+x ) 36 | 37 | i += 1 38 | 39 | 40 | def main(): 41 | start = time() 42 | F(0, 10000, []) 43 | F(0, 10000, []) 44 | F(0, 10000, []) 45 | print( time()-start ) 46 | -------------------------------------------------------------------------------- /regtests/bench/webclgl_array_mult.py: -------------------------------------------------------------------------------- 1 | """big array mult""" 2 | from time import time 3 | from random import random 4 | 5 | ARRAY_SIZE = 1024*1024*4 6 | 7 | @returns( array=ARRAY_SIZE ) 8 | @gpu.main 9 | def myfunc(A, B, C, D): 10 | float* A 11 | float* B 12 | float* C 13 | float* D 14 | vec2 n = get_global_id() ## WebCL API 15 | return A[n] * B[n] * C[n] * D[n] 16 | 17 | def main(): 18 | 19 | a = [ random() for i in range(ARRAY_SIZE)] 20 | b = [ random() for i in range(ARRAY_SIZE)] 21 | c = [ random() for i in range(ARRAY_SIZE)] 22 | d = [ random() for i in range(ARRAY_SIZE)] 23 | 24 | if PYTHON=='PYTHONJS': 25 | start = time() 26 | res = myfunc( a,b,c,d ) 27 | #print(res) 28 | print( time()-start ) 29 | else: 30 | a = numpy.array(a, dtype=numpy.float32 ) 31 | b = numpy.array(b, dtype=numpy.float32 ) 32 | c = numpy.array(c, dtype=numpy.float32 ) 33 | d = numpy.array(d, dtype=numpy.float32 ) 34 | start = time() 35 | res = a * b * c * d 36 | print( time()-start ) 37 | -------------------------------------------------------------------------------- /regtests/bench/webworker_single.py: -------------------------------------------------------------------------------- 1 | ''' 2 | webworker single 3 | ''' 4 | 5 | from time import time 6 | from time import sleep 7 | import threading 8 | 9 | 10 | def main(): 11 | if PYTHON=='PYTHONJS': 12 | pythonjs.configure( direct_operator='+' ) 13 | pass 14 | 15 | 16 | starttime = time() 17 | n = 3000 18 | seq = [] 19 | cache = [] 20 | 21 | w1 = threading.start_webworker( worker, (0, n, seq, cache) ) 22 | sleep(1.0) 23 | 24 | testtime = time()-starttime 25 | primes_per_sec = len(seq) * (1.0 / testtime) 26 | 27 | print(primes_per_sec) 28 | print('#total test time: %s' %testtime) 29 | print('-----main exit') 30 | 31 | 32 | with webworker: 33 | def worker(start, end, seq, cache): 34 | print('------enter worker------') 35 | for i in range(start, end): 36 | if i in cache: 37 | #continue ## TODO - fix continue 38 | pass 39 | else: 40 | cache.append( i ) 41 | if is_prime(i): 42 | seq.append( i ) 43 | print('#worker reached: %s' %i) 44 | 45 | def is_prime(n): 46 | hits = 0 47 | for x in range(2, n): 48 | for y in range(2, n): 49 | if x*y == n: 50 | hits += 1 51 | if hits > 1: 52 | return False 53 | return True 54 | 55 | -------------------------------------------------------------------------------- /regtests/bench/webworkers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | loop and add (integer) 3 | ''' 4 | 5 | from time import time 6 | from time import sleep 7 | import threading 8 | 9 | def main(): 10 | if PYTHON=='PYTHONJS': 11 | pythonjs.configure( direct_operator='+' ) 12 | pass 13 | 14 | start = time() 15 | n = 2000 16 | seq = [] 17 | #cache = {0:True, 1:True, 2:True, 3:True} 18 | cache = [] 19 | 20 | #w = worker(n,seq, cache) 21 | w1 = threading.start_webworker( worker, (0, n, seq, cache) ) 22 | w2 = threading.start_webworker( worker, (10, n, seq, cache) ) 23 | #w3 = threading.start_webworker( worker, (400, n, seq, cache) ) 24 | sleep(1.0) 25 | 26 | testtime = time()-start 27 | primes_per_sec = len(seq) * (1.0 / testtime) 28 | 29 | #print('#%s' %len(seq)) 30 | #seq.sort() ## TODO fix sort for numbers 31 | print(primes_per_sec) 32 | print('#total test time: %s' %testtime) 33 | print('-----main exit') 34 | 35 | 36 | with webworker: 37 | def worker(start, end, seq, cache): 38 | print('------enter worker------') 39 | for i in range(start, end): 40 | if i in cache: 41 | #continue ## TODO - fix continue 42 | pass 43 | else: 44 | cache.append( i ) 45 | if is_prime(i): 46 | seq.append( i ) 47 | print('#worker reached: %s' %i) 48 | 49 | def is_prime(n): 50 | hits = 0 51 | for x in range(2, n): 52 | for y in range(2, n): 53 | if x*y == n: 54 | hits += 1 55 | if hits > 1: 56 | return False 57 | return True 58 | 59 | -------------------------------------------------------------------------------- /regtests/c++/array_of_arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | array of arrays 3 | ''' 4 | 5 | def main(): 6 | ## variable size vector of vectors, 7 | ## None is allowed as a sub-vector because each sub-vector is wrapped by std::shared_ptr 8 | arr = [][]int( 9 | [1,2,3], 10 | [4,5,6,7,8], 11 | None, 12 | #(x*x for x in range(4)), ## TODO fix listcomps 13 | (x for x in range(20)), 14 | ) 15 | 16 | a,b,c = arr[0] 17 | assert a==1 18 | assert b==2 19 | assert c==3 20 | 21 | for vec in arr: 22 | print vec 23 | if vec is not None: 24 | x,y,z = vec 25 | print x,y,z 26 | 27 | assert len(arr)==4 28 | assert len(arr[0])==3 29 | assert len(arr[1])==5 30 | assert len(arr[3])==20 31 | assert arr[2] is None 32 | 33 | v = 1 34 | for i in arr[0]: 35 | assert i==v 36 | v+=1 37 | 38 | sub = arr[1] 39 | v = sub[0] 40 | for i in sub: 41 | assert i == v 42 | v+=1 43 | 44 | v = 0 45 | for i in arr[3]: 46 | assert i==v 47 | v+=1 48 | 49 | arr[3][0] = 1000 50 | arr[3][1] = 1001 51 | 52 | assert arr[3][0] == 1000 53 | assert arr[3][1] == 1001 54 | 55 | print 'OK' -------------------------------------------------------------------------------- /regtests/c++/array_of_arrays_objects.py: -------------------------------------------------------------------------------- 1 | ''' 2 | array of arrays objects 3 | ''' 4 | 5 | class A: 6 | def __init__(self, id:int): 7 | self.id = id 8 | 9 | def method(self): 10 | print(self.id) 11 | 12 | def main(): 13 | a1 = A(1) 14 | a2 = A(2) 15 | a3 = A(3) 16 | 17 | arr = [][]A( 18 | [a1,a2,a3, A(4)], 19 | [a1,None], 20 | None, 21 | ) 22 | print('length of array: ', len(arr)) 23 | print( 'len subarray 0: ', len(arr[0]) ) 24 | print( 'len subarray 1: ', len(arr[1]) ) 25 | print('subarray 2 is nullptr: ',arr[2] ) 26 | print('subarray 0 ptr addr: ', arr[0]) 27 | 28 | arr[0][2].method() -------------------------------------------------------------------------------- /regtests/c++/array_slice_assignment.py: -------------------------------------------------------------------------------- 1 | ''' 2 | array slice assignment syntax 3 | ''' 4 | 5 | def somefunc(): 6 | a = [1,2,3,4,5] 7 | assert len(a)==5 8 | b = [6,7,8,9,10] 9 | assert len(b)==5 10 | c = [100, 200] 11 | 12 | print('len a:', len(a)) 13 | #for i in a: 14 | # print i 15 | 16 | print 'slice assign front' 17 | lena = len(a) 18 | two = 2 19 | a[:two+1] = b 20 | print('len a:', len(a)) 21 | assert len(a)==(lena-(two+1))+len(b) 22 | #assert len(a)==8 23 | for i in a: print i 24 | assert a[0]==6 25 | assert a[5]==4 26 | assert a[6]==5 27 | 28 | print 'slice assign back' 29 | b[2:] = c 30 | for i in b: 31 | print i 32 | assert b[0]==6 33 | assert b[1]==7 34 | assert b[2]==100 35 | assert b[3]==200 36 | print 'slice out of bounds' 37 | print a 38 | a[:100] = b 39 | for v in a: 40 | print v 41 | print 'len a:', len(a) 42 | 43 | def stackfunc(): 44 | print 'testing stack allocated arrays' 45 | with stack: 46 | x = [5]int(1,2,3,4,5) 47 | assert len(x)==5 48 | y = [5]int(6,7,8,9,10) 49 | assert len(y)==5 50 | 51 | z = y[3:] 52 | assert len(z)==2 53 | x[3:] = z 54 | 55 | for item in x: 56 | print item 57 | 58 | assert x[0]==1 59 | assert x[1]==2 60 | assert x[2]==3 61 | assert x[3]==9 62 | assert x[4]==10 63 | 64 | def main(): 65 | somefunc() 66 | stackfunc() 67 | 68 | #main() -------------------------------------------------------------------------------- /regtests/c++/block_scope.py: -------------------------------------------------------------------------------- 1 | ''' 2 | variable block scope 3 | http://stackoverflow.com/questions/6167923/block-scope-in-python 4 | ''' 5 | 6 | def main(): 7 | for x in range(3): 8 | print x 9 | y = x 10 | 11 | ## below is valid in python, but not in pythia. 12 | #assert x==2 13 | #assert y==x 14 | 15 | ## note because `y` above is block scoped inside the for loop, 16 | ## the type of `y` can be changed here. 17 | y = 'hi' 18 | print y 19 | 20 | print 'OK' -------------------------------------------------------------------------------- /regtests/c++/chain.py: -------------------------------------------------------------------------------- 1 | ''' 2 | chain 3 | ''' 4 | 5 | class A: 6 | def __init__(self): 7 | let self.val : float = 0 8 | def add(self, a:float) ->self: 9 | self.val += a 10 | return self 11 | def mult(self, a:float) ->self: 12 | self.val *= a 13 | return self 14 | def div(self, a:float) ->self: 15 | self.val /= a 16 | return self 17 | 18 | 19 | def main(): 20 | a = A() 21 | val = a.add(100.0).mult(3.0).div(2.0).val 22 | print(val) 23 | -------------------------------------------------------------------------------- /regtests/c++/chan.py: -------------------------------------------------------------------------------- 1 | """cpp-channel backend - send int over channel""" 2 | 3 | def sender_wrapper(a:int, send: chan int ): 4 | ## `chan T` is an alias for `cpp::channel` 5 | print 'sending' 6 | result = 100 7 | send <- result 8 | 9 | def recv_wrapper(a:int, recver: cpp::channel ) -> int: 10 | ## above namespace and template are given c++ style to recver 11 | print 'receiving' 12 | v = <- recver 13 | return v 14 | 15 | def main(): 16 | print 'enter main' 17 | c = channel(int) ## `channel(T)` translates to: `cpp::channel` 18 | print 'new channel' 19 | ## spawn creates a new std::thread, 20 | ## and joins it at the end of the function. 21 | print 'doing spawn thread' 22 | spawn( sender_wrapper(17, c) ) 23 | print 'done spawning thread' 24 | # Do other work... 25 | x = recv_wrapper(2, c) 26 | print(x) 27 | assert x==100 28 | print 'ok' -------------------------------------------------------------------------------- /regtests/c++/classmethod.py: -------------------------------------------------------------------------------- 1 | ''' 2 | class methods 3 | ''' 4 | class A: 5 | def __init__(self, x:int, y:int): 6 | self.x = x 7 | self.y = y 8 | 9 | @classmethod 10 | def foo(self): 11 | print('my classmethod') 12 | 13 | @classmethod 14 | def bar(self, a:int) ->int: 15 | return a+1000 16 | 17 | def main(): 18 | x = A(1,2) 19 | x.foo() 20 | A.foo() 21 | print x.bar( 100 ) 22 | y = A.bar(200) 23 | print(y) 24 | -------------------------------------------------------------------------------- /regtests/c++/cyclic_simple.py: -------------------------------------------------------------------------------- 1 | ''' 2 | detect cyclic parent/child, and insert weakref 3 | ''' 4 | class Parent: 5 | def __init__(self, children:[]Child ): 6 | self.children = children 7 | 8 | class Child: 9 | def __init__(self, parent:Parent ): 10 | self.parent = parent 11 | 12 | def foo(self) ->int: 13 | par = self.parent 14 | if par is not None: 15 | return 1 16 | else: 17 | print('parent is gone..') 18 | 19 | def bar(self): 20 | print self.parent.children 21 | 22 | def make_child(p:Parent) -> Child: 23 | c = Child(p) 24 | p.children.push_back(c) 25 | return c 26 | 27 | 28 | def main(): 29 | children = []Child() 30 | p = Parent( children ) 31 | c1 = make_child(p) 32 | c2 = make_child(p) 33 | print c1.foo() 34 | c1.bar() 35 | del p 36 | print c1.foo() 37 | #uncomment to segfault##c1.bar() -------------------------------------------------------------------------------- /regtests/c++/free_memory.py: -------------------------------------------------------------------------------- 1 | ''' 2 | delete pointer 3 | ''' 4 | class A: 5 | def __init__(self, x:int ): 6 | self.x = x 7 | def __del__(self): 8 | print( 'goodbye') 9 | 10 | def main(): 11 | a = A(1) 12 | print a 13 | del a 14 | print 'done' 15 | -------------------------------------------------------------------------------- /regtests/c++/generics.py: -------------------------------------------------------------------------------- 1 | ''' 2 | generic functions 3 | ''' 4 | 5 | def myfunc( x:int ): 6 | print( x * 100 ) 7 | 8 | def myfunc( x:string ): 9 | print( x + 'world' ) 10 | 11 | def main(): 12 | myfunc( 10 ) 13 | myfunc( 'hello' ) 14 | -------------------------------------------------------------------------------- /regtests/c++/generics_array_subclasses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | generics classes with common base. 3 | ''' 4 | class A: 5 | def __init__(self, x:int): 6 | self.x = x 7 | 8 | def method1(self) -> int: 9 | return self.x 10 | def getname(self) -> string: 11 | return self.__class__ 12 | 13 | class B(A): 14 | def method1(self) ->int: 15 | return self.x * 2 16 | def method2(self, y:int): 17 | print( self.x + y ) 18 | 19 | class C(A): 20 | def method1(self) ->int: 21 | return self.x + 200 22 | 23 | def say_hi(self): 24 | print('hi from C') 25 | 26 | 27 | def my_generic( g:A ) ->int: 28 | return g.method1() 29 | 30 | 31 | def main(): 32 | a = A( 1 ) 33 | b = B( 200 ) 34 | c = C( 3000 ) 35 | 36 | print(a.__class__) 37 | print(b.__class__) 38 | print(c.__class__) 39 | print('- - - - - - -') 40 | 41 | arr = []A( a,b,c ) 42 | for item in arr: 43 | ## just prints 100's because c++ runtime method dispatcher thinks item 44 | ## is of class type `A` 45 | print(item.__class__) 46 | print( my_generic(item) ) 47 | 48 | print('- - - - - - -') 49 | 50 | for item in arr: 51 | print(item.getname()) 52 | print(item.x) 53 | 54 | ## to get to the real subclasses, we need if-isinstance 55 | if isinstance(item, B): 56 | print('item is B') 57 | item.method2( 20 ) 58 | 59 | if isinstance(item, C): 60 | print('item is C') 61 | item.say_hi() 62 | 63 | -------------------------------------------------------------------------------- /regtests/c++/generics_subclasses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | generics classes with common base. 3 | ''' 4 | class A: 5 | def __init__(self, x:int): 6 | self.x = x 7 | 8 | def method1(self) -> int: 9 | return self.x 10 | 11 | class B(A): 12 | 13 | def method1(self) ->int: 14 | return self.x * 2 15 | 16 | class C(A): 17 | 18 | def method1(self) ->int: 19 | return self.x + 200 20 | 21 | class D: 22 | def __init__(self, x:int): 23 | self.x = x 24 | 25 | def method1(self) -> int: 26 | return self.x 27 | 28 | ## c++14 is able to deduce all the different subclass types 29 | ## that are passed to `my_generic`, a static type is not defined for `g` 30 | def my_generic( g ) ->int: 31 | return g.method1() 32 | 33 | def my_generic2( g1, g2) ->int: 34 | return g1.method1() * g2.method1() 35 | 36 | def my_generic3( g1, g2, g3 ) ->int: 37 | return g1.method1() * g2.method1() * g3.method1() 38 | 39 | def main(): 40 | a = A( 100 ) 41 | b = B( 100 ) 42 | c = C( 100 ) 43 | 44 | x = my_generic( a ) 45 | assert a.x == x 46 | print(x) 47 | 48 | y = my_generic( b ) 49 | assert y==200 50 | print(y) 51 | 52 | z = my_generic( c ) 53 | assert z==300 54 | print(z) 55 | print('----------------') 56 | print( my_generic2(a,b)) 57 | print( my_generic2(b,c)) 58 | print( my_generic2(c,b)) 59 | print( my_generic2(b,b)) 60 | 61 | print('----------------') 62 | print( my_generic3(a,b,c)) 63 | print( my_generic3(b,c,a)) 64 | print( my_generic3(c,b,a)) 65 | print( my_generic3(b,b,b)) 66 | -------------------------------------------------------------------------------- /regtests/c++/globals.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple globals 3 | ''' 4 | 5 | class A: pass 6 | 7 | let a : A = None 8 | b = 0 9 | 10 | def check_globals(): 11 | print('a addr:', a) ## should not print `0` 12 | print('b value:', b) 13 | 14 | def main(): 15 | global a, b 16 | check_globals() 17 | a = A() 18 | print(a) 19 | print(a.__class__) 20 | b = 100 21 | check_globals() 22 | -------------------------------------------------------------------------------- /regtests/c++/if_else.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple if/else 3 | ''' 4 | 5 | 6 | def main(): 7 | a = 'x' 8 | if a == 'x': 9 | print('a ok') 10 | else: 11 | print('not a ok') 12 | b = 'y' 13 | if b == 'x': 14 | print('b ok') 15 | else: 16 | print('b not ok') 17 | -------------------------------------------------------------------------------- /regtests/c++/if_none.py: -------------------------------------------------------------------------------- 1 | ''' 2 | if a is None 3 | ''' 4 | 5 | with stack: 6 | class A: 7 | def __init__(self): 8 | print 'new class A' 9 | def is_initialized(self) -> bool: 10 | return self.__initialized__ 11 | 12 | def test(): 13 | a = A() 14 | print a.is_initialized() 15 | assert a.is_initialized() 16 | if a is not None: 17 | print 'a is not None' 18 | a = None 19 | assert a is None 20 | 21 | let b:A = None 22 | print b.is_initialized() 23 | if b is None: 24 | print 'b is acting like a nullptr' 25 | 26 | assert b.is_initialized() is False 27 | c = A() 28 | ## test that ensures `a` can be restored from nullptr back to an object. 29 | a = c 30 | 31 | def main(): 32 | test() -------------------------------------------------------------------------------- /regtests/c++/let_styles.py: -------------------------------------------------------------------------------- 1 | ''' 2 | let syntax inspired by rust. 3 | cdef syntax borrowed from cython. 4 | ''' 5 | 6 | macro( NUM=100 ) ## becomes `#define NUM 100` 7 | 8 | class Foo(): 9 | def __init__(self): 10 | let self.data : [NUM]int 11 | 12 | let Foos: []Foo 13 | 14 | let TwentyFoos : [20]Foo 15 | 16 | mycomp = []int() 17 | twentyints = [20]int() 18 | 19 | gFoo = Foo() 20 | 21 | 22 | def main(): 23 | cdef int a=1 24 | cdef int b=2 25 | cdef int *myptr 26 | assert a+b==3 27 | a = 10 28 | assert a+b==12 29 | 30 | print gFoo 31 | 32 | print 'len mycomp:', len(mycomp) 33 | assert len(mycomp)==0 34 | 35 | mycomp2 = []int() 36 | mycomp2.append( 10 ) 37 | print 'len mycomp2:', len(mycomp2) 38 | assert len(mycomp2)==1 39 | 40 | print Foos 41 | 42 | print len(Foos) 43 | assert len(Foos) == 0 44 | 45 | f = Foo() 46 | assert len(f.data)==NUM 47 | f.data[0] = 12 48 | print f.data[0] 49 | 50 | Foos.push_back(f) 51 | print len(Foos) 52 | assert len(Foos)==1 53 | 54 | print len(TwentyFoos) 55 | TwentyFoos[0] = f 56 | print TwentyFoos[0] 57 | -------------------------------------------------------------------------------- /regtests/c++/listcomp.py: -------------------------------------------------------------------------------- 1 | ''' 2 | list comprehension 3 | ''' 4 | 5 | 6 | def main(): 7 | a = []int( x*2 for x in range(10) ) 8 | print(len(a)) 9 | for item in a: 10 | print(item) 11 | 12 | ## TODO fix slice copy: 13 | ## *** Error in `/tmp/listcomp': free(): invalid pointer: 0x000000000216d218 *** 14 | #b = [][]int( a[:] for i in range(4) ) 15 | #print(len(b)) 16 | #print(b[0]) 17 | #print(b[1]) 18 | #print(b[2]) 19 | #print(b[3]) 20 | -------------------------------------------------------------------------------- /regtests/c++/math.py: -------------------------------------------------------------------------------- 1 | ''' 2 | basic math 3 | ''' 4 | 5 | def main(): 6 | sixteen = 2**4 7 | print sixteen 8 | assert sixteen == 16 9 | 10 | c = complex(1,2) 11 | print c -------------------------------------------------------------------------------- /regtests/c++/named_params.py: -------------------------------------------------------------------------------- 1 | ''' 2 | keyword arguments 3 | ''' 4 | 5 | def f1( a=1 ) -> int: 6 | return a*2 7 | 8 | ## this break rust because the global kwargs-type then requires `b` and `__use__b` 9 | ## but the caller only gives `a` and `__use__a` 10 | def f2( a=1, b=2 ) -> int: 11 | return a + b 12 | 13 | def main(): 14 | print( f1(a=100) ) 15 | #print( f2(a=100, b=200) ) ## TODO fix in c++ 16 | -------------------------------------------------------------------------------- /regtests/c++/pointers_returns_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | returns pointer to array 3 | ''' 4 | 5 | def make_array() -> std::vector*: 6 | arr = new([]int( 1,2,3,4 )) 7 | return arr 8 | 9 | def test_array( arr:std::vector* ): 10 | print( arr[0] ) 11 | print( arr[1] ) 12 | print( arr[2] ) 13 | print( arr[3] ) 14 | 15 | 16 | with pointers: 17 | def Pmake_array() -> []int: 18 | arr = new([]int( 1,2,3,4 )) 19 | return arr 20 | 21 | def Ptest_array( arr:[]int ): 22 | print( arr[0] ) 23 | print( arr[1] ) 24 | print( arr[2] ) 25 | print( arr[3] ) 26 | 27 | def test(): 28 | a = make_array() 29 | print('arr length:', len(a)) 30 | test_array(a) 31 | 32 | 33 | def test_pointers(): 34 | a = Pmake_array() 35 | print('arr length:', len(a)) 36 | Ptest_array(a) 37 | 38 | def main(): 39 | test() 40 | test_pointers() 41 | -------------------------------------------------------------------------------- /regtests/c++/pointers_returns_array2D.py: -------------------------------------------------------------------------------- 1 | ''' 2 | returns array of arrays 3 | ''' 4 | 5 | with pointers: 6 | def make_array() -> [][]int: 7 | arr = new( 8 | [][]int( 9 | (1,2,3), 10 | (4,5,6,7,8) 11 | ) 12 | ) 13 | return arr 14 | 15 | def test_array( arr:[][]int ): 16 | assert arr[0][0] == 1 17 | 18 | def main(): 19 | a = make_array() 20 | print( len(a)) 21 | assert len(a)==2 22 | assert len(a[0])==3 23 | assert len(a[1])==5 24 | test_array(a) 25 | print 'ok' -------------------------------------------------------------------------------- /regtests/c++/print_classname.py: -------------------------------------------------------------------------------- 1 | ''' 2 | returns subclasses 3 | ''' 4 | class A: 5 | def __init__(self, x:int): 6 | self.x = x 7 | 8 | def method(self) -> int: 9 | return self.x 10 | 11 | class B(A): 12 | 13 | def foo(self) ->int: 14 | return self.x * 2 15 | 16 | class C(A): 17 | 18 | def bar(self) ->int: 19 | return self.x + 200 20 | 21 | 22 | def main(): 23 | a = A(0) 24 | b = B(1) 25 | c = C(2) 26 | print(a.getclassname()) 27 | print(b.getclassname()) 28 | print(c.getclassname()) 29 | 30 | 31 | -------------------------------------------------------------------------------- /regtests/c++/returns_array2D.py: -------------------------------------------------------------------------------- 1 | ''' 2 | returns array of arrays 3 | ''' 4 | def make_array() -> [][]int: 5 | arr = [][]int( 6 | (1,2,3), 7 | (4,5,6,7,8) 8 | ) 9 | return arr 10 | 11 | def test_array( arr:[][]int ): 12 | print( arr[0][0] ) 13 | 14 | def main(): 15 | a = make_array() 16 | print( len(a)) 17 | print( len(a[0]) ) 18 | print( len(a[1]) ) 19 | 20 | test_array(a) -------------------------------------------------------------------------------- /regtests/c++/returns_object.py: -------------------------------------------------------------------------------- 1 | ''' 2 | return a class instance 3 | ''' 4 | with pointers: 5 | class A: 6 | def __init__(self, x:int, y:int): 7 | self.x = x 8 | self.y = y 9 | 10 | def create_A() -> A: 11 | #a = A(1,2) ## not valid because `a` gets free`ed when function exists 12 | a = new A(1,2) ## using `new` the user must manually free the object later 13 | return a 14 | 15 | def main(): 16 | x = create_A() 17 | print(x) 18 | print(x.x) 19 | print(x.y) 20 | -------------------------------------------------------------------------------- /regtests/c++/subscript.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple subscript 3 | ''' 4 | 5 | 6 | def main(): 7 | a = []int(1,2,3) 8 | index = 0 9 | a[ index ] = 100 10 | print(a[index]) 11 | 12 | s = "hello world" 13 | print(s) 14 | print(s[0]) 15 | print(s[1]) 16 | print(s[2]) 17 | print(s[3]) 18 | if s[0]=='h': 19 | print('ok') 20 | else: 21 | print('error') 22 | -------------------------------------------------------------------------------- /regtests/c++/try_except_finally.py: -------------------------------------------------------------------------------- 1 | ''' 2 | c++ finally 3 | ''' 4 | 5 | def myfunc(): 6 | 7 | a = False 8 | try: 9 | raise RuntimeError('oops') 10 | except RuntimeError: 11 | print 'caught RuntimeError OK' 12 | a = True 13 | 14 | assert a == True 15 | 16 | 17 | c = False 18 | try: 19 | raise IOError('my ioerror') 20 | 21 | except IOError as err: 22 | print 'caught my ioerr' 23 | print err.what() 24 | #raise err ## rethrow works ok 25 | c = True 26 | assert c == True 27 | 28 | 29 | b = False 30 | 31 | try: 32 | print('trying something that will fail...') 33 | print('some call that fails at runtime') 34 | f = open('/tmp/nosuchfile') 35 | except RuntimeError: 36 | print 'this should not happen' 37 | except IOError: 38 | print 'CAUGHT IOError OK' 39 | ## it is ok to raise or return in the except block, 40 | ## the finally block will be run before any of this happens 41 | #raise RuntimeError('rethrowing error') ## this works 42 | return 43 | 44 | except: 45 | print('CAUGHT UNKNOWN EXECEPTION') 46 | ## raise another exception 47 | raise RuntimeError('got unknown exception') 48 | finally: 49 | print('FINALLY') 50 | b = True 51 | 52 | assert b == True 53 | 54 | 55 | 56 | 57 | 58 | def main(): 59 | myfunc() 60 | -------------------------------------------------------------------------------- /regtests/c++/untyped_args.py: -------------------------------------------------------------------------------- 1 | def foo( a ): 2 | return a+1 3 | 4 | def main(): 5 | x = foo(2) 6 | assert x==3 7 | -------------------------------------------------------------------------------- /regtests/c++/while.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple while loops 3 | ''' 4 | 5 | 6 | def main(): 7 | i = 10 8 | while i > 0: 9 | i -= 1 10 | 11 | print(i) -------------------------------------------------------------------------------- /regtests/calling/args.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """simple function call""" 3 | def f(a, b, c): 4 | return a+b+c 5 | 6 | def main(): 7 | assert( f(1,2,3) == 6) 8 | 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /regtests/calling/keyword.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """keywords""" 3 | def f(a, b=None, c=None): 4 | return (a+b) * c 5 | 6 | 7 | def main(): 8 | print 'testing keywords' 9 | print f(1, b=2, c=3) 10 | print f(1, c=3, b=2) 11 | assert( f(1, b=2, c=3) == 9) 12 | assert( f(1, c=3, b=2) == 9) 13 | print 'ok' 14 | main() 15 | -------------------------------------------------------------------------------- /regtests/calling/lambda.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """lambda function""" 3 | 4 | def get_lambda(): 5 | return lambda x,y: x+y 6 | 7 | def get_lambdas(): 8 | return [lambda a,b: a+b, lambda x,y: x+y] 9 | 10 | def call_lambda( F ): 11 | return F() 12 | 13 | def call_lambda2( callback=None ): 14 | return callback() 15 | 16 | def main(): 17 | f = lambda a,b: a+b 18 | assert( f(1,2) == 3 ) 19 | 20 | assert( (lambda a,b: a+b)(1,2) == 3 ) 21 | 22 | assert( get_lambda()(1,2) == 3 ) 23 | 24 | funcs = get_lambdas() 25 | assert( funcs[0](1,2) == 3 ) 26 | assert( funcs[1](1,2) == 3 ) 27 | 28 | funcs = [lambda a,b: a+b, lambda x,y: x+y] 29 | assert( funcs[0](1,2) == 3 ) 30 | assert( funcs[1](1,2) == 3 ) 31 | 32 | d = { 'x':lambda a,b: a+b } 33 | assert( d['x'](1,2) == 3 ) 34 | 35 | e = ( lambda a,b: a+b, lambda x,y: x+y ) 36 | assert( e[0](1,2) == 3 ) 37 | assert( e[1](1,2) == 3 ) 38 | 39 | r = call_lambda( lambda : int(100) ) 40 | assert( r==100 ) 41 | 42 | 43 | r = call_lambda2( callback = lambda : int(200) ) 44 | assert( r==200 ) 45 | main() 46 | -------------------------------------------------------------------------------- /regtests/calling/param_name.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """Function call with the name of a parameter without default value""" 3 | def f1(a): 4 | return a 5 | 6 | def f2(a=1, b=2): 7 | return a + b 8 | 9 | def main(): 10 | print 'testing calling named parameters' 11 | assert f1(10)==10 12 | assert f2() ==3 13 | assert f2(a=100) == 102 14 | assert f2(b=500) == 501 15 | 16 | ## GOTCHA: calling a function that expects a named keyword parameter, 17 | ## and not giving any named parameters is not valid in Rusthon. 18 | ## this works in regular python, but it is bad-style, 19 | ## and would be slow to support in javascript. 20 | #assert( f2( 100 ) == 102 ) 21 | 22 | 23 | ## GOTCHA: below is valid in Python, but not in Rusthon, 24 | ## this is bad-style because the caller is enforcing 25 | ## a naming convention on the function, and in typical 26 | ## python code named parameters are only used when 27 | ## the function has been defined with named keywords. 28 | ## allowing this would also allow for bad-style that 29 | ## would break when calling js functions from external libs. 30 | #assert( f1( a=100 ) == 100 ) 31 | 32 | print 'ok' 33 | 34 | main() 35 | -------------------------------------------------------------------------------- /regtests/calling/starargs.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """unpack starargs""" 3 | def f(x, a, b, c): 4 | return x+a+b+c 5 | 6 | def f2(x,y,z, w=0): 7 | return x+y+z+w 8 | 9 | def main(): 10 | a = [1,1,1] 11 | assert( f(1, *a) == 4) 12 | 13 | assert( f2(*a, w=10) == 13) 14 | 15 | b = [1,1] 16 | assert( f2(100, *b, w=10) == 112) 17 | 18 | main() 19 | -------------------------------------------------------------------------------- /regtests/calling/variable_args.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """variable args""" 3 | def f(a, *args): 4 | print '*args' 5 | print args 6 | c = a 7 | for b in args: 8 | c += b 9 | return c 10 | 11 | def main(): 12 | print 'testing calling function that takes *args' 13 | assert( f(1, 2, 3, 3) == 9) 14 | print 'ok' 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /regtests/calling/variable_kwargs.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """variable keywords""" 3 | 4 | def f2(**kw): 5 | a = 0 6 | for key in iter(kw): 7 | a += kw[key] 8 | return a 9 | 10 | def main(): 11 | 12 | assert( f2(x=1,y=2) == 3 ) 13 | main() 14 | -------------------------------------------------------------------------------- /regtests/calling/variable_kwargs_class.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """variable keywords""" 3 | class A: 4 | def f2(self, **kw): 5 | a = 0 6 | for key in kw.keys(): 7 | a += kw[key] 8 | return a 9 | 10 | def main(): 11 | a = A() 12 | assert( a.f2(x=1,y=2) == 3 ) 13 | main() 14 | -------------------------------------------------------------------------------- /regtests/calling/variable_kwargs_class_init.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """variable keywords""" 3 | class A: 4 | def __init__(self, **kw): 5 | a = 0 6 | for key in iter(kw): 7 | a += kw[key] 8 | self.value = a 9 | 10 | def main(): 11 | a = A(x=1,y=2) 12 | assert( a.value == 3 ) 13 | main() 14 | -------------------------------------------------------------------------------- /regtests/class/__add__.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """custom addition""" 3 | 4 | class A: 5 | def __init__(self): 6 | self.x = 5 7 | def __add__(self, other): 8 | return self.x + other.x 9 | 10 | 11 | def main(): 12 | print 'testing __add__ operator overloading' 13 | a = A() 14 | b = A() 15 | with oo: 16 | c = a + b 17 | assert( c == 10 ) 18 | print 'ok' 19 | 20 | main() 21 | -------------------------------------------------------------------------------- /regtests/class/__call__.py: -------------------------------------------------------------------------------- 1 | """custom callable""" 2 | from runtime import * 3 | 4 | class A: 5 | def __init__(self): 6 | self.x = 5 7 | 8 | def __call__(self): 9 | print self.x 10 | return 'XXX' 11 | 12 | def foo(self): 13 | return self.x 14 | 15 | 16 | def main(): 17 | print 'testing __call__' 18 | a = A() 19 | assert a.x == 5 20 | assert a() == 'XXX' 21 | assert a.__call__() == 'XXX' 22 | assert a.foo() == 5 23 | assert isinstance(a, A) 24 | print 'ok' 25 | 26 | main() -------------------------------------------------------------------------------- /regtests/class/__getattr__.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | __getattr__, @property, and class attributes 4 | ''' 5 | class A: 6 | X = 'A' 7 | 8 | ## not allowed - will raise SyntaxError at compile time ## 9 | def __getattr__(self, name): 10 | if name == 'hello': 11 | return 100 12 | elif name == 'world': 13 | return 200 14 | else: 15 | return 300 16 | 17 | class B(A): 18 | Y = 'B' 19 | 20 | @property 21 | def y(self): 22 | return self._y 23 | 24 | class C( B ): 25 | Z = 'C' 26 | 27 | def __init__(self, x,y,z): 28 | self.x = x 29 | self._y = y 30 | self._z = z 31 | 32 | @property 33 | def z(self): 34 | return self._z 35 | 36 | 37 | 38 | def main(): 39 | a = C(1,2,3) 40 | ## GOTCHA: this is not allowed in Rusthon, 41 | ## class variables can only be used on the classes, 42 | ## not on the instances. 43 | #assert( a.X == 'A' ) 44 | #assert( a.Y == 'B' ) 45 | #assert( a.Z == 'C' ) 46 | 47 | assert( A.X == 'A' ) 48 | assert( B.Y == 'B' ) 49 | assert( C.Z == 'C' ) 50 | 51 | 52 | assert( a.x == 1 ) 53 | #assert( a.y == 2 ) ## TODO fix me 54 | assert( a.z == 3 ) 55 | 56 | ## GOTCHA: __getattr__ is not allowed in Rusthon 57 | #b = a.hello 58 | #assert( b == 100 ) 59 | #assert( a.world == 200 ) 60 | #assert( a.XXX == 300 ) 61 | 62 | main() 63 | -------------------------------------------------------------------------------- /regtests/class/__mul__.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """custom multiplication""" 3 | 4 | class A: 5 | def __init__(self): 6 | self.x = 5 7 | def __mul__(self, other): 8 | return self.x * other.x 9 | 10 | 11 | def main(): 12 | a = A() 13 | b = A() 14 | with operator_overloading: 15 | c = a * b 16 | assert( c == 25 ) 17 | 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /regtests/class/attr.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """instance and class attributes""" 3 | 4 | class A: 5 | g = 6 6 | def __init__(self): 7 | self.b = 5 8 | 9 | a = None 10 | def main(): 11 | a = A() 12 | 13 | assert(a.b == 5) 14 | 15 | ## this is valid in regular CPython, but not in PythonJS, 16 | ## the variable `g` is only attached to the class Object, 17 | ## not the instance. The builtin `getattr` is smart enough 18 | ## to check the class object for the attribute, and return 19 | ## it if it finds it on the class. 20 | #assert(a.g == 6) 21 | 22 | try: 23 | x = a.c 24 | assert(not 'No exception: on undefined attribute') 25 | except AttributeError: 26 | pass 27 | 28 | b = a 29 | assert(getattr(b, 'b') == 5) 30 | assert(getattr(b, 'g') == 6) 31 | try: 32 | getattr(b, 'c') 33 | assert(not 'No exception: getattr on undefined attribute') 34 | except AttributeError: 35 | pass 36 | 37 | b.g = 100 38 | assert( A.g == 6) 39 | main() 40 | -------------------------------------------------------------------------------- /regtests/class/init_keyword.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | test __init__ with keyword arg 4 | ''' 5 | 6 | def main(): 7 | class Cell: 8 | def __init__(self, x=1): 9 | self.x = x 10 | 11 | a = Cell(x=2) 12 | assert(a.x == 2) 13 | main() 14 | -------------------------------------------------------------------------------- /regtests/class/isinstance.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | builtin isinstance 4 | ''' 5 | class A(): 6 | pass 7 | 8 | class B: 9 | pass 10 | 11 | def main(): 12 | print 'testing isinstance' 13 | a = A() 14 | b = B() 15 | assert( isinstance(a,A)==True ) 16 | assert( isinstance(a,B)==False ) 17 | assert( isinstance(a,dict)==False ) 18 | 19 | assert( isinstance(b,B)==True ) 20 | assert( isinstance(b,A)==False ) 21 | 22 | c = [1,2] 23 | assert( isinstance(c, list)==True ) 24 | assert( isinstance(c, dict)==False ) 25 | assert( isinstance(c, A)==False ) 26 | 27 | d = {'a':1, 'b':2} 28 | assert( isinstance(d, dict)==True ) 29 | assert( isinstance(d, A)==False ) 30 | 31 | print 'ok' 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /regtests/class/mi.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | multiple inheritance 4 | ''' 5 | class A: 6 | def foo(self) -> int: 7 | return 1 8 | 9 | class B: 10 | def bar(self) -> int: 11 | return 2 12 | 13 | class C( A, B ): 14 | def call_foo_bar(self) -> int: 15 | a = self.foo() 16 | a += self.bar() 17 | return a 18 | 19 | ## extend foo ## 20 | def foo(self) -> int: 21 | #a = A.foo(self) ## TODO fix me, or support `super` 22 | a = A.prototype.foo(self) ## workaround 23 | a += 100 24 | return a 25 | 26 | def main(): 27 | a = A() 28 | assert( a.foo()==1 ) 29 | b = B() 30 | assert( b.bar()==2 ) 31 | 32 | c = C() 33 | assert( c.foo()==101 ) 34 | assert( c.bar()==2 ) 35 | 36 | assert( c.call_foo_bar()==103 ) 37 | 38 | main() 39 | -------------------------------------------------------------------------------- /regtests/class/mi__getattr__.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | __getattr__ and @property 4 | ''' 5 | class Root: 6 | def __getattr__(self, name): 7 | if name == 'x': 8 | return self._x 9 | elif name == 'y': 10 | return self._y 11 | else: 12 | return name 13 | 14 | class A( Root ): 15 | def __init__(self): 16 | self._x = 1 17 | self._y = 2 18 | 19 | class B( A ): 20 | @property 21 | def w(self): 22 | return 'XXX' 23 | 24 | def unknown(u): 25 | return u 26 | 27 | 28 | 29 | def main(): 30 | a = A() 31 | b = unknown( a ) 32 | assert( b.x==1 ) 33 | assert( b.y==2 ) 34 | assert( b.z=='z' ) 35 | assert( b.w=='w' ) 36 | 37 | c = B() 38 | d = unknown( c ) 39 | assert( d.x==1 ) 40 | assert( d.y==2 ) 41 | assert( d.z=='z' ) 42 | assert( d.w=='XXX' ) 43 | 44 | main() 45 | -------------------------------------------------------------------------------- /regtests/class/mi_override.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | multiple inheritance 4 | ''' 5 | class A: 6 | def foo(self) -> int: 7 | return 1 8 | 9 | class B: 10 | def bar(self) -> int: 11 | return 2 12 | 13 | class C( A, B ): 14 | def call_foo_bar(self) -> int: 15 | a = self.foo() 16 | a += self.bar() 17 | return a 18 | 19 | ## override foo ## 20 | def foo(self) -> int: 21 | return 100 22 | 23 | def main(): 24 | a = A() 25 | assert( a.foo()==1 ) 26 | b = B() 27 | assert( b.bar()==2 ) 28 | 29 | c = C() 30 | assert( c.foo()==100 ) 31 | assert( c.bar()==2 ) 32 | 33 | assert( c.call_foo_bar()==102 ) 34 | 35 | main() 36 | -------------------------------------------------------------------------------- /regtests/class/simple.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """simple class""" 3 | 4 | class A: 5 | def __init__(self): 6 | self.x = 5 7 | 8 | def main(): 9 | a = A() 10 | assert(a.x == 5) 11 | 12 | main() 13 | -------------------------------------------------------------------------------- /regtests/dict/contains.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """key in dict""" 3 | 4 | def main(): 5 | ## mixing string keys and number keys in a dict literal 6 | ## is allowed in python, but not in Rusthon 7 | #a = {'2': 22, 3:33} 8 | #assert( '2' in a ) 9 | #assert( 3 in a ) 10 | 11 | a = {2: 22, 3:33} 12 | assert( 2 in a ) 13 | assert( 3 in a ) 14 | 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /regtests/dict/dict_comprehension.py: -------------------------------------------------------------------------------- 1 | ''' 2 | dict comprehensions 3 | ''' 4 | 5 | 6 | 7 | def main(): 8 | m = { a:'xxx' for a in range(10)} 9 | print(m) 10 | -------------------------------------------------------------------------------- /regtests/dict/if_empty.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """if empty dict then false""" 3 | 4 | ## if mydict: will not work, 5 | ## workaround: `if len(d.keys())` 6 | 7 | def main(): 8 | d = {} 9 | #print __jsdict_keys(d) 10 | if d.keys().length: 11 | err1 = 1 12 | else: 13 | err1 = 0 14 | 15 | if len({}.keys()): 16 | err2 = 1 17 | else: 18 | err2 = 0 19 | 20 | d['x'] = 'xxx' 21 | if len(d.keys()): 22 | err3 = 0 23 | else: 24 | err3 = 1 25 | 26 | assert( err1 == 0 ) 27 | assert( err2 == 0 ) 28 | assert( err3 == 0 ) 29 | 30 | main() 31 | -------------------------------------------------------------------------------- /regtests/dict/init.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """Defined with {}""" 3 | def f(): 4 | pass 5 | class G(object): 6 | pass 7 | 8 | def main(): 9 | g = G() 10 | a = {2: 22, 3:33, f:44, G:55, g:66} 11 | assert(a[2] == 22) 12 | assert(a[3] == 33) 13 | #assert(a[f] == 44) 14 | #assert(a[G] == 55) 15 | #assert(a[g] == 66) 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /regtests/dict/keys.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """dict.keys() and iter""" 3 | 4 | def main(): 5 | a = {'foo':'bar'} 6 | keys = a.keys() 7 | assert( 'foo' in keys ) 8 | 9 | print 'testing iter over dict' 10 | ## this is not allowed, a must be wrapped with `iter(a)` 11 | #for key in a: 12 | print a 13 | for key in iter(a): 14 | print key 15 | print a[key] 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /regtests/dict/tuple_keys.py: -------------------------------------------------------------------------------- 1 | """dict tuple key""" 2 | 3 | class A: pass 4 | class B: 5 | def __init__(self): 6 | pass 7 | 8 | def main(): 9 | s = ("1", "2", "3") 10 | a = (1,2,3) 11 | b = (1,2,3) 12 | c = ( a, b, 'XXX' ) 13 | d = ('1', 2, 3) 14 | 15 | D = { d:100, s: 11, a: 22, c:44 } 16 | TestError( D[ d ] == 100) 17 | TestError( D[ s ] == 11) 18 | TestError( D[ a ] == 22) 19 | TestError( D[ b ] == 22) 20 | TestError( D[ c ] == 44) 21 | 22 | aa = A() 23 | bb = B() 24 | ab = ( A(), B() ) 25 | D2 = { aa: 'hello', bb: 'world', ab:'XXX' } 26 | TestError( D2[aa]=='hello' ) 27 | TestError( D2[bb]=='world' ) 28 | TestError( D2[ab]=='XXX') 29 | 30 | r = { s:1, a:aa } 31 | r2 = {} 32 | for x in [ s, a ]: 33 | r2[ x ] = r[ x ] 34 | TestError( r[s] is r2[s] ) -------------------------------------------------------------------------------- /regtests/exceptions/AttributeError.py: -------------------------------------------------------------------------------- 1 | """catch AttributeError""" 2 | 3 | class A: pass 4 | 5 | def main(): 6 | a = A() 7 | b = False 8 | try: 9 | b = a.xxx 10 | except AttributeError: 11 | b = True 12 | 13 | TestError( b == True ) 14 | -------------------------------------------------------------------------------- /regtests/exceptions/KeyError.py: -------------------------------------------------------------------------------- 1 | """catch KeyError""" 2 | 3 | def main(): 4 | D = {} 5 | a = False 6 | try: 7 | a = D['XXX'] 8 | except KeyError: 9 | a = True 10 | 11 | TestError( a == True ) 12 | -------------------------------------------------------------------------------- /regtests/go/array_of_objects.py: -------------------------------------------------------------------------------- 1 | '''array of objects''' 2 | class A: 3 | def foo(self) -> string: 4 | return 'xxxx' 5 | class B(A): 6 | def foo(self) -> string: 7 | return 'hello' 8 | class C(A): 9 | def foo(self) -> string: 10 | return 'world' 11 | 12 | 13 | def push( arr:[]int, x:int ): 14 | arr.append( x ) 15 | 16 | #def push2( arr:[]*A, x:*A ): 17 | # arr.append( x ) 18 | 19 | @generic 20 | def my_generic( s:A ): 21 | print( s.foo() ) 22 | 23 | 24 | def main(): 25 | arr = []int() 26 | arr.append(1) 27 | push( arr, 100) 28 | assert len(arr)==2 29 | print(arr) 30 | 31 | a1 = A(); a2 = A(); a3 = A() 32 | obarr = []A( a1, a2 ) 33 | print(obarr) 34 | 35 | print a3 36 | #push2( obarr, a3 ) 37 | #print(obarr) 38 | #TestError( len(obarr)==3 ) 39 | 40 | b1 = B() 41 | print(b1) 42 | #obarr.append( b1 ) ## fails because subclasses can not be cast to their base class 43 | 44 | ################################################# 45 | barr = []B( b1, ) ## todo single item array should not require `,` 46 | c1 = C() 47 | barr.append( c1 ) 48 | print(barr) 49 | 50 | bb = barr[0] 51 | print('bb:', bb) 52 | print(bb.foo()) 53 | 54 | cc = barr[1] 55 | print('cc:', cc) 56 | print(cc.foo()) 57 | 58 | #ccc = go.type_assert( cc, C ) 59 | #print(ccc.foo()) 60 | 61 | print('----testing generic----') 62 | for subclass in barr: 63 | print('subclass in bar:', subclass) 64 | my_generic(subclass) -------------------------------------------------------------------------------- /regtests/go/arrays.py: -------------------------------------------------------------------------------- 1 | """array types""" 2 | 3 | def test_pass_array_as_arg( arr:[]int ): 4 | arr.append( 5 ) 5 | 6 | def main(): 7 | a = []int(1,2,3) 8 | print a 9 | assert a[0]==1 10 | assert len(a)==3 11 | a.append( 4 ) 12 | assert len(a)==4 13 | 14 | test_pass_array_as_arg( a ) 15 | assert len(a)==5 16 | 17 | b = [2]int(100,200) 18 | assert b[0]==100 19 | assert b[1]==200 20 | 21 | c = a[:2] 22 | assert len(c)==2 23 | 24 | d = range(10) 25 | assert len(d)==10 26 | d.append(99) 27 | assert len(d)==11 28 | 29 | e = range(2,10) 30 | assert len(e)==8 31 | 32 | f = range(2,10, 2) 33 | assert len(f)==4 34 | 35 | print 'testing 2d array' 36 | s = [][]int() 37 | print s 38 | 39 | print 'OK' 40 | -------------------------------------------------------------------------------- /regtests/go/callback_in_class.py: -------------------------------------------------------------------------------- 1 | ''' 2 | callback in class 3 | ''' 4 | class A: 5 | def __init__(self, cb:func(int)(int), x:int, y:int, z:int=1): 6 | let self.x : int = x 7 | let self.y : int = y 8 | let self.z : int = z 9 | let self.callback : func(int)(int) = cb 10 | 11 | def call(self, a:int ) -> int: 12 | return self.callback( a + self.x + self.y + self.z ) 13 | 14 | def mycb( x:int ) ->int: 15 | return x + 1000 16 | 17 | def main(): 18 | a = A( 19 | mycb, 20 | 100, 21 | 200, 22 | z=300 23 | ) 24 | #print( a.x ) 25 | #print( a.y ) 26 | #print( a.z ) 27 | 28 | assert a.call(-600)==1000 29 | print 'ok' 30 | 31 | -------------------------------------------------------------------------------- /regtests/go/chan.py: -------------------------------------------------------------------------------- 1 | """send int over channel""" 2 | 3 | def wrapper(a:int, c: chan int): 4 | result = 100 5 | c <- result 6 | 7 | def main(): 8 | c = channel(int) 9 | 10 | spawn( wrapper(17, c) ) 11 | 12 | # Do other work in the current goroutine until the channel has a result. 13 | 14 | x = <-c 15 | print(x) 16 | assert x==100 17 | -------------------------------------------------------------------------------- /regtests/go/class.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple class 3 | ''' 4 | class A: 5 | { 6 | x:int, 7 | y:int, 8 | z:int, 9 | } 10 | def __init__(self, x:int, y:int, z:int=1): 11 | self.x = x 12 | self.y = y 13 | self.z = z 14 | 15 | def mymethod(self, m:int) -> int: 16 | return self.x * m 17 | 18 | def call_method( cb:func(int)(int), mx:int ) ->int: 19 | return cb(mx) 20 | 21 | def main(): 22 | a = A( 100, 200, z=9999 ) 23 | print( a.x ) 24 | print( a.y ) 25 | print( a.z ) 26 | 27 | b = a.mymethod(3) 28 | print( b ) 29 | 30 | c = call_method( a.mymethod, 4 ) 31 | print( c ) -------------------------------------------------------------------------------- /regtests/go/func_calls.py: -------------------------------------------------------------------------------- 1 | """function call""" 2 | def f(a:int, b:int, c:int) ->int: 3 | print 'testing f: plain args' 4 | return a+b+c 5 | 6 | def f2(a:int=1, b:int=2, c:int=3) ->int: 7 | print 'testing f2: keyword args' 8 | return a+b+c 9 | 10 | def f3( *args:int ) ->int: 11 | print 'testing f3: star args' 12 | return args[0] + args[1] + args[2] 13 | 14 | 15 | def main(): 16 | assert f(1,2,3) == 6 17 | 18 | x = f2( b=100 ) 19 | assert x==104 20 | 21 | arr = [1,2,3] 22 | y = f3( *arr ) 23 | assert y==6 -------------------------------------------------------------------------------- /regtests/go/generics_init.py: -------------------------------------------------------------------------------- 1 | ''' 2 | passing generic attribute to method 3 | ''' 4 | class BaseX: 5 | def __init__(self, f:bool): 6 | self.flag = f 7 | self.ob = None 8 | 9 | #def get(self) ->BaseA: 10 | #S return self.ob 11 | 12 | 13 | class BaseA: 14 | def __init__(self, x:int, g:BaseX): 15 | self.x = x 16 | self.g = g 17 | 18 | def foo( self ) -> self: 19 | return self.bar( self.g ) 20 | 21 | def bar(self, g:BaseX) -> self: 22 | #if g.flag: 23 | # return go.type_assert(g.ob, self) 24 | #else: 25 | return self 26 | 27 | 28 | class B( BaseA ): pass 29 | class C( BaseA ): pass 30 | 31 | 32 | class X( BaseX ): pass 33 | class Y( BaseX ): pass 34 | 35 | 36 | def main(): 37 | x = X(true) 38 | y = Y(false) 39 | b1 = B(1, x) 40 | b2 = B(2, y) 41 | 42 | x.ob = b2 43 | y.ob = b1 44 | 45 | print( b1.foo() ) -------------------------------------------------------------------------------- /regtests/go/generics_methods.py: -------------------------------------------------------------------------------- 1 | class G: 2 | def method(self): 3 | print 'calling G.method' 4 | print 'hi' 5 | 6 | class H( G ): 7 | def method(self): 8 | print 'calling H.method' 9 | print 'world' 10 | 11 | class A: 12 | @generic 13 | def __init__(self, a:G): 14 | print 'A.__init__' 15 | print(a) 16 | self.x = a 17 | 18 | def call(self): 19 | print 'A.call' 20 | self.f( self.x ) 21 | 22 | @generic 23 | def f(self, a:G): 24 | print 'A.f' 25 | print(a) 26 | 27 | 28 | class B( A ): 29 | @generic 30 | def f(self, g:G): 31 | print 'B.f' 32 | g.method() 33 | 34 | 35 | 36 | def main(): 37 | g = G() 38 | h = H() 39 | b1 = B( g ) 40 | b2 = B( h ) 41 | 42 | print('----------test1 b1 (g)') 43 | b1.call() 44 | print('----------test2 b2 (h)') 45 | b2.call() -------------------------------------------------------------------------------- /regtests/go/generics_subclasses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | generics classes with common base. 3 | ''' 4 | class A: 5 | def __init__(self, x:int): 6 | self.x = x 7 | 8 | def method1(self) -> int: 9 | return self.x 10 | 11 | class B(A): 12 | 13 | def method1(self) ->int: 14 | return self.x * 2 15 | 16 | class C(A): 17 | 18 | def method1(self) ->int: 19 | return self.x + 200 20 | 21 | 22 | @generic 23 | def my_generic( g:A ) ->int: 24 | return g.method1() 25 | 26 | def main(): 27 | a = A( 100 ) 28 | b = B( 100 ) 29 | c = C( 100 ) 30 | print a 31 | print b 32 | print c 33 | 34 | x = my_generic( a ) 35 | assert a.x == x 36 | 37 | y = my_generic( b ) 38 | assert y==200 39 | 40 | z = my_generic( c ) 41 | assert z==300 42 | -------------------------------------------------------------------------------- /regtests/go/go_select.py: -------------------------------------------------------------------------------- 1 | """go select""" 2 | 3 | def send_data( A:chan int, B:chan int, X:int, Y:int): 4 | while True: 5 | print('sending data..') 6 | A <- X 7 | B <- Y 8 | 9 | def select_loop(A:chan int, B:chan int, W:chan int) -> int: 10 | print('starting select loop') 11 | y = 0 12 | while True: 13 | print('select loop:',y) 14 | select: 15 | case x = <- A: 16 | y += x 17 | W <- y 18 | case x = <- B: 19 | y += x 20 | W <- y 21 | print('end select loop', y) 22 | return y 23 | 24 | def main(): 25 | a = go.channel(int) 26 | b = go.channel(int) 27 | w = go.channel(int) 28 | 29 | go( 30 | select_loop(a,b, w) 31 | ) 32 | 33 | 34 | go( 35 | send_data(a,b, 5, 10) 36 | ) 37 | 38 | z = 0 39 | while z < 100: 40 | z = <- w 41 | print('main loop', z) 42 | 43 | print('end test') -------------------------------------------------------------------------------- /regtests/go/list_comprehension.py: -------------------------------------------------------------------------------- 1 | ''' 2 | go list comprehensions 3 | ''' 4 | 5 | class A: 6 | def __init__(self, x:int,arr:[]int): 7 | ## note: names of args should match names on struct 8 | self.x = x 9 | self.arr = arr 10 | ## TODO FIXME: allow arg names to be different from internal struct names 11 | #let self.arr : []int = y 12 | 13 | def get(self) ->int: 14 | return self.arr[3] + self.x 15 | 16 | 17 | def F( arr:[]int ): 18 | arr.append( 3 ) 19 | 20 | def main(): 21 | a = []int(x for x in range(3)) 22 | print a 23 | F( a ) 24 | assert len(a)==4 25 | assert a[0]==0 26 | assert a[1]==1 27 | assert a[2]==2 28 | assert a[3]==3 29 | 30 | b = []A( 31 | A(i,a) for i in range(2) 32 | ) 33 | assert b[1].get()==4 34 | print b 35 | -------------------------------------------------------------------------------- /regtests/go/loop_arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | array loop 3 | ''' 4 | 5 | def main(): 6 | 7 | a = [1,2,3] 8 | y = 0 9 | for x in a: 10 | y += x 11 | assert y==6 12 | 13 | z = '' 14 | arr = ['a', 'b', 'c'] 15 | for v in arr: 16 | z += v 17 | assert z == 'abc' 18 | 19 | b = 0 20 | for i in range(10): 21 | b += 1 22 | assert b == 10 23 | 24 | b2 = 0 25 | for i in range(5, 10): 26 | b2 += 1 27 | assert b2 == 5 28 | 29 | 30 | c = '' 31 | d = 0 32 | for i,v in enumerate(arr): 33 | c += v 34 | d += i 35 | assert c == 'abc' 36 | 37 | e = 0 38 | for i in range( len(arr) ): 39 | e += 1 40 | assert e == 3 41 | 42 | s = a[:2] 43 | print('len of s:') 44 | print(len(s)) 45 | assert len(s)==2 46 | 47 | s2 = a[2:] 48 | print('len of s2:') 49 | print(len(s2)) 50 | print(s2[0]) 51 | assert len(s2)==1 52 | 53 | #e = 0 54 | #for i in s: 55 | # e += i 56 | #TestError( e == 3 ) 57 | -------------------------------------------------------------------------------- /regtests/go/loop_map.py: -------------------------------------------------------------------------------- 1 | ''' 2 | map loop 3 | ''' 4 | 5 | def main(): 6 | a = {'x':100, 'y':200} 7 | b = '' 8 | c = 0 9 | for key, value in a: 10 | print( key ) 11 | print( value ) 12 | b += key 13 | c += value 14 | 15 | print( b ) 16 | print( c ) -------------------------------------------------------------------------------- /regtests/go/map_comprehension.py: -------------------------------------------------------------------------------- 1 | ''' 2 | map comprehensions 3 | ''' 4 | 5 | def main(): 6 | m = map[int]string{ 7 | key:'xxx' for key in range(10) 8 | } 9 | assert m[0]=='xxx' 10 | assert m[9]=='xxx' 11 | print m 12 | print m[0] 13 | print m[1] 14 | -------------------------------------------------------------------------------- /regtests/go/maps.py: -------------------------------------------------------------------------------- 1 | """map types""" 2 | 3 | def main(): 4 | a = map[string]int{ 5 | 'x': 1, 6 | 'y': 2, 7 | 'z': 3, 8 | } 9 | 10 | print( a['x'] ) 11 | assert a['x']==1 12 | 13 | b = map[int]string{ 0:'a', 1:'b' } 14 | print( b[0] ) 15 | print( b[1] ) 16 | assert b[0]=='a' 17 | assert b[1]=='b' 18 | 19 | ## infers type of key and value ## 20 | c = {'x':100, 'y':200} 21 | print( c['x'] ) 22 | print( c['y'] ) 23 | 24 | assert c['x']==100 25 | assert c['y']==200 26 | -------------------------------------------------------------------------------- /regtests/go/nested_func.py: -------------------------------------------------------------------------------- 1 | ''' 2 | lambda func 3 | ''' 4 | 5 | def main(): 6 | def F(x:int) ->int: 7 | return x*2 8 | 9 | a = F(10) 10 | print a 11 | assert a==20 12 | -------------------------------------------------------------------------------- /regtests/go/print.py: -------------------------------------------------------------------------------- 1 | """hello world""" 2 | 3 | XXX = 'myglobal' ## this is a static string 4 | 5 | def myprint( a:string, b:string ): 6 | print a + b 7 | 8 | 9 | def main(): 10 | print "hi" 11 | myprint('hello ', 'world') 12 | 13 | ## TODO - should this automatically be converted from a static string to a String with `String.from_str()` 14 | myprint('hi ', str(XXX) ) -------------------------------------------------------------------------------- /regtests/go/subclass.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple class 3 | ''' 4 | class A: 5 | def __init__(self, x:int, y:int, z:int=1): 6 | let self.x : int = x 7 | let self.y : int = y 8 | let self.z : int = z 9 | 10 | def mymethod(self, m:int) -> int: 11 | return self.x * m 12 | 13 | class B(A): 14 | def __init__(self, s:string): 15 | let self.w : string = s 16 | let self.x : int = 1 17 | 18 | def method2(self, v:string) ->string: 19 | print(self.x) 20 | self.w = v 21 | return self.w 22 | 23 | def call_method( cb:func(int)(int), mx:int ) ->int: 24 | return cb(mx) 25 | 26 | def main(): 27 | a = A( 100, 200, z=9999 ) 28 | print( a.x ) 29 | print( a.y ) 30 | print( a.z ) 31 | 32 | b = a.mymethod(3) 33 | print( b ) 34 | 35 | c = call_method( a.mymethod, 4 ) 36 | print( c ) 37 | 38 | x = B('testing...') 39 | print( x.method2('hello world') ) -------------------------------------------------------------------------------- /regtests/go/vars.py: -------------------------------------------------------------------------------- 1 | """var assignment :=, and reassignment =""" 2 | 3 | def main(): 4 | a = 1 5 | print a 6 | a = 2 7 | print a 8 | assert a==2 -------------------------------------------------------------------------------- /regtests/html/date.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /regtests/lang/builtins.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | builtin functions 4 | ''' 5 | 6 | 7 | def main(): 8 | o = ord('x') 9 | assert( o == 120 ) 10 | 11 | n = float('1.1') 12 | assert( n==1.1 ) 13 | 14 | n = float('NaN') 15 | print( n ) 16 | assert( isNaN(n)==True ) 17 | 18 | r = round( 1.1234, 2) 19 | print(r) 20 | assert( str(r) == '1.12' ) 21 | 22 | x = chr(120) 23 | print(x) 24 | assert x == 'x' 25 | 26 | r = round( 100.001, 2) 27 | assert( r == 100 ) 28 | 29 | i = int( 100.1 ) 30 | assert( i == 100 ) 31 | 32 | r = round( 5.49 ) 33 | assert( r == 5 ) 34 | 35 | r = round( 5.49, 1 ) 36 | assert( r == 5.5 ) 37 | 38 | 39 | main() 40 | -------------------------------------------------------------------------------- /regtests/lang/equality.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | == 4 | ''' 5 | # https://github.com/PythonJS/PythonJS/issues/129 6 | 7 | def main(): 8 | assert( 0==0 ) 9 | assert( 1==1 ) 10 | assert( 1.0==1 ) 11 | assert('a'=='a') 12 | 13 | 14 | a = [6] 15 | b = [6] 16 | #t = a==b ## this works in regular python 17 | t1 = a.equals(b) 18 | assert( t1==True ) 19 | 20 | a = (6,) 21 | b = (6,) 22 | #t = a==b 23 | t2 = a.equals(b) 24 | assert( t2==True ) 25 | 26 | t3 = ''==0 ## javascript gotcha, workaround: `len('')==0` 27 | print 'empty string equals zero:' + t3 28 | #assert( t==False ) 29 | 30 | t4 = [1,2].equals([1,2]) 31 | assert( t4==True ) 32 | 33 | t5 = ["1","2"].equals([1,2]) 34 | assert( t5==False ) 35 | 36 | 37 | main() 38 | -------------------------------------------------------------------------------- /regtests/lang/eval.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | eval 4 | ''' 5 | 6 | def foo(): return 42 7 | bar = lambda: 42 8 | 9 | def main(): 10 | eval('a = bar()') # This one works 11 | eval('b = foo()') # 'foo' is undefined in normal mode under NodeJS but works in NodeWebkit and Chrome!? 12 | assert( a==42 ) 13 | assert( b==42 ) 14 | 15 | main() 16 | -------------------------------------------------------------------------------- /regtests/lang/eval_order.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | evaluation order 4 | ''' 5 | # https://github.com/PythonJS/PythonJS/issues/131 6 | 7 | def main(): 8 | a = False and (False or True) 9 | assert( a==False ) 10 | main() 11 | -------------------------------------------------------------------------------- /regtests/lang/func_locals.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | inspect locals of a function at runtime for debugging 4 | ''' 5 | 6 | @locals 7 | def myfunc(value='bar'): 8 | x = 1 9 | y = {foo:value} 10 | @locals 11 | def nested(): 12 | z = 'FOO' 13 | return value + 'NESTED' 14 | 15 | return nested() 16 | 17 | def main(): 18 | print myfunc.locals 19 | print myfunc() 20 | print myfunc.locals 21 | assert myfunc.locals.x == 1 22 | assert myfunc.locals.y.foo=='bar' 23 | myfunc(value='X') 24 | print myfunc.locals 25 | assert myfunc.locals.y.foo=='X' 26 | 27 | print myfunc.locals.nested.locals.z 28 | assert myfunc.locals.nested.locals.z=='FOO' 29 | 30 | main() 31 | -------------------------------------------------------------------------------- /regtests/lang/if_else.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | if/else 4 | ''' 5 | 6 | #def func(x=None, callback=None): 7 | def func(x=False, callback=None ): 8 | a = False 9 | if x: ## can c++ templates support this pythonic style? 10 | a = False 11 | else: 12 | a = True 13 | 14 | assert( a==True ) 15 | 16 | a = False 17 | if callback: 18 | a = True 19 | else: 20 | a = False 21 | assert( a==True ) 22 | 23 | def main(): 24 | a = False 25 | if 1: 26 | a = True 27 | assert( a==True ) 28 | 29 | a = False 30 | if False: 31 | a = False 32 | else: 33 | a = True 34 | 35 | assert( a==True ) 36 | 37 | a = False 38 | if None: 39 | a = False 40 | else: 41 | a = True 42 | 43 | assert( a==True ) 44 | 45 | def cb() ->int: 46 | return 1+1 47 | 48 | func( callback=cb ) 49 | 50 | 51 | 52 | main() 53 | -------------------------------------------------------------------------------- /regtests/lang/if_not.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """if not""" 3 | 4 | def main(): 5 | a = False 6 | b = False 7 | if not a: 8 | b = True 9 | 10 | assert( b == True ) 11 | 12 | a = 0 13 | b = False 14 | if not a: 15 | b = True 16 | 17 | assert( b == True ) 18 | 19 | a = 0.0 20 | b = False 21 | if not a: 22 | b = True 23 | 24 | assert( b == True ) 25 | 26 | a = None 27 | b = False 28 | if not a: 29 | b = True 30 | 31 | assert( b == True ) 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /regtests/lang/importing.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | 3 | try: 4 | import mylib 5 | except: 6 | print 'TODO import mylib' 7 | 8 | ## translates correctly to js, but is syntax error `import` unknown keyword in nodejs. 9 | #from mylib import A,B,MyClass 10 | 11 | #class Sub(mylib.MyClass): ## TODO 12 | class Sub: 13 | def foo(self, x): 14 | print 'foo' 15 | return x 16 | 17 | def main(): 18 | s = Sub() 19 | assert s.foo(10)==10 20 | 21 | main() 22 | -------------------------------------------------------------------------------- /regtests/lang/in.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | in (dict contains) 4 | ''' 5 | 6 | def main(): 7 | d = {'x':1} 8 | a = 'x' in d 9 | assert( a==True ) 10 | b = 'y' in d 11 | assert( b==False ) 12 | 13 | 14 | 15 | main() 16 | -------------------------------------------------------------------------------- /regtests/lang/inline.py: -------------------------------------------------------------------------------- 1 | """inline""" 2 | 3 | def main(): 4 | JS("now = new Date()") 5 | inline("now = new Date()") 6 | -------------------------------------------------------------------------------- /regtests/lang/list_passed_as_arg.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | list passed to function 4 | ''' 5 | 6 | def f( l:[]int ): 7 | l.append(1) 8 | 9 | def main(): 10 | a = []int(1,2,3) 11 | assert( a[0]==1 ) 12 | f( a ) 13 | assert( len(a)==4 ) 14 | 15 | b = [ x for x in range(9) ] 16 | f( b ) 17 | assert( len(b)==10 ) 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /regtests/lang/map_passed_as_arg.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | list passed to function 4 | ''' 5 | 6 | def f( m:map[string]int ): 7 | m['x'] = 100 8 | 9 | def main(): 10 | a = map[string]int{ 11 | 'x' : 1, 12 | 'y' : 2, 13 | 'z' : 3 14 | } 15 | assert( a['x']==1 ) 16 | f( a ) 17 | assert( a['x']==100 ) 18 | #assert( len(a)==4 ) 19 | main() 20 | -------------------------------------------------------------------------------- /regtests/lang/new.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | js new keyword 4 | ''' 5 | 6 | def main(): 7 | ## new as keyword can be used in simple statements, but can break the parser in some cases, 8 | ## it is only allowed to make it easy to copy and paste js code and convert it to rusthon. 9 | a = new Date() 10 | b = new( Date() ) ## using new as a function call is safer and always works 11 | assert( a.getFullYear()==2016 ) 12 | assert( b.getFullYear()==2016 ) 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /regtests/lang/raise.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | raise and catch error 4 | ''' 5 | 6 | def main(): 7 | a = False 8 | try: 9 | raise TypeError 10 | except TypeError: 11 | a = True 12 | 13 | assert( a==True ) 14 | 15 | b = False 16 | try: 17 | b = True 18 | except: 19 | b = False 20 | 21 | assert( b==True ) 22 | 23 | c = False 24 | try: 25 | raise AttributeError('name') 26 | except AttributeError: 27 | c = True 28 | 29 | assert( c==True ) 30 | 31 | main() 32 | -------------------------------------------------------------------------------- /regtests/lang/switch.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | switch case default 4 | ''' 5 | 6 | def main(): 7 | ## this is ok in rust because it can infer the type of x from below, 8 | ## but this fails with the C++ backend because None becomes std::nullptr 9 | #x = None 10 | x = '' 11 | a = 2 12 | switch a: 13 | case 1: 14 | x = 'fail' 15 | case 2: 16 | x = 'ok' 17 | default: 18 | ## default x to some string so that rust can see that x is a string in all cases, 19 | ## this is only required if x was initalized to None 20 | x = 'default' 21 | break 22 | print(x) 23 | assert( x=='ok' ) 24 | 25 | 26 | main() 27 | -------------------------------------------------------------------------------- /regtests/lang/try_except.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | try except 4 | ''' 5 | 6 | def main(): 7 | a = [1,2,3] 8 | b = False 9 | try: 10 | a.no_such_method() 11 | b = 'this should not happen' 12 | except: 13 | b = True 14 | assert( b == True ) 15 | 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /regtests/lang/typedarrays.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | javascript typed array syntax 4 | ''' 5 | 6 | def main(): 7 | s = [10,20,30] 8 | for v in s: 9 | print v 10 | print s 11 | 12 | print 'testing javascript typed arrays' 13 | a = [128]int( 1,2,3 ) 14 | print __is_some_array(a) 15 | 16 | assert len(a)==128 17 | assert isinstance(a, Int32Array) 18 | assert a[0]==1 19 | assert a[1]==2 20 | assert a[2]==3 21 | assert a[3]==0 22 | 23 | ii = 0 24 | #for value in a: ## will raise a runtime error 25 | for value in iter(a): 26 | print value 27 | ii += 1 28 | if ii > 10: break 29 | #print a 30 | 31 | b = [128]int32(1,2,3) 32 | c = [128]i32(1,2,3) 33 | assert isinstance(b, Int32Array) 34 | assert isinstance(c, Int32Array) 35 | 36 | d = [128]float( 1.1, 2.2, 3.3 ) 37 | assert isinstance(d, Float32Array) 38 | d = [128]float32( 1.1, 2.2, 3.3 ) 39 | assert isinstance(d, Float32Array) 40 | d = [128]f32( 1.1, 2.2, 3.3 ) 41 | assert isinstance(d, Float32Array) 42 | 43 | d = [128]float64( 1.1, 2.2, 3.3 ) 44 | assert isinstance(d, Float64Array) 45 | d = [128]f64( 1.1, 2.2, 3.3 ) 46 | assert isinstance(d, Float64Array) 47 | print d[0] 48 | print d[1] 49 | print d[2] 50 | 51 | 52 | print 'ok' 53 | 54 | main() 55 | -------------------------------------------------------------------------------- /regtests/list/comp.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | list comprehensions 4 | ''' 5 | 6 | def main(): 7 | a = [x for x in range(3)] 8 | assert( len(a)==3 ) 9 | assert( a[0]==0 ) 10 | assert( a[1]==1 ) 11 | assert( a[2]==2 ) 12 | 13 | main() 14 | -------------------------------------------------------------------------------- /regtests/list/concatenate.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """concatenate lists""" 3 | 4 | def main(): 5 | a = [1,2] 6 | b = [3,4] 7 | n = 1 8 | w = 100 9 | with oo: 10 | c = a + b 11 | ## it is slow to just stick everything under `with oo` 12 | ## because these operations on numbers become much slower. 13 | n += n 14 | w = w + w 15 | 16 | assert n == 2 17 | assert w == 200 18 | 19 | assert( len(c)==4 ) 20 | assert( c[0]==1 ) 21 | assert( c[1]==2 ) 22 | assert( c[2]==3 ) 23 | assert( c[3]==4 ) 24 | 25 | ## the pythonic way is ugly 26 | d = a.__add__(b) 27 | assert len(d)==4 28 | 29 | ## the recommend way in rusthon 30 | e = a.add(b) 31 | assert len(e)==4 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /regtests/list/contains.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """if x in list""" 3 | def main(): 4 | a = ['foo', 'bar'] 5 | assert( 'foo' in a ) 6 | 7 | b = [0, 1, 2] 8 | assert( 2 in b ) 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /regtests/list/if_empty.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """if empty list then false""" 3 | 4 | class A: 5 | pass 6 | 7 | def main(): 8 | d = [] 9 | #if d: ## this is not allowed, and will raise an error at runtime 10 | if len(d): 11 | err1 = 1 12 | else: 13 | err1 = 0 14 | 15 | if len([]): 16 | err2 = 1 17 | else: 18 | err2 = 0 19 | 20 | d.append('xxx') 21 | if len(d): 22 | err3 = 0 23 | else: 24 | err3 = 1 25 | 26 | assert( err1 == 0 ) 27 | assert( err2 == 0 ) 28 | assert( err3 == 0 ) 29 | 30 | a = A() 31 | ok = False 32 | #if a: ## this is not allowed, and will raise an error at runtime 33 | if a is not None: 34 | ok = True 35 | assert ok 36 | 37 | a.x = [] 38 | if len(a.x): 39 | err4 = 1 40 | else: 41 | err4 = 0 42 | 43 | assert( err4 == 0 ) 44 | 45 | main() 46 | -------------------------------------------------------------------------------- /regtests/list/index.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """list indices""" 3 | def main(): 4 | a = [1,2,3,4] 5 | idx = 1 6 | assert( a[0]==1 ) 7 | assert( a[idx]==2 ) 8 | assert( a.index(3)==2 ) 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /regtests/list/insert.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """insert""" 3 | def main(): 4 | global a 5 | print 'testing array.insert' 6 | print [] 7 | print '----' 8 | a = [1,2,3,4] 9 | print a.length 10 | print Object.keys(a) 11 | print '____' 12 | print a 13 | assert( len(a)==4 ) 14 | 15 | a.insert(0, 'hi') 16 | #print a 17 | assert( len(a)==5 ) 18 | assert( a[0]=='hi' ) 19 | 20 | a.insert(1, a.pop(0)) 21 | #print a 22 | assert( a[0]==1 ) 23 | assert( a[1]=='hi' ) 24 | 25 | main() 26 | -------------------------------------------------------------------------------- /regtests/list/loop.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | simple for loop 4 | ''' 5 | 6 | def main(): 7 | a = [1,2,3] 8 | y = 0 9 | for x in a: 10 | y += x 11 | assert( y==6 ) 12 | 13 | b = range(3) 14 | z = 0 15 | for x in b: 16 | z += x 17 | assert( z==3 ) 18 | 19 | w = 0 20 | for i in a: 21 | for j in b: 22 | w += 1 23 | assert( w==9 ) 24 | 25 | main() 26 | -------------------------------------------------------------------------------- /regtests/list/mul.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """list multiplication""" 3 | 4 | 5 | def main(): 6 | a = ['hi'] 7 | print a 8 | with operator_overloading: 9 | b = a * 2 10 | print b 11 | assert( len(b)==2 ) 12 | assert( b[0]=='hi' ) 13 | assert( b[1]=='hi' ) 14 | print 'ok' 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /regtests/list/neg_index.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """negative list indices""" 3 | def main(): 4 | a = [1,2,3,4] 5 | ## negative indices are allowed when using a number literal as the index, 6 | ## this is the most common use case, because often you want to index from 7 | ## the end with a literal number and not a variable. 8 | assert( a[-1]==4 ) 9 | assert a[-2]==3 10 | assert a[-3]==2 11 | assert a[-4]==1 12 | 13 | ## this is allowed in regular python, but not in rusthon. 14 | idx = -2 15 | #assert( a[idx]==3 ) 16 | ## if you really need to use a variable to perform a negative index, 17 | ## this is the workaround. 18 | assert a[a.length+idx-1] 19 | 20 | main() 21 | -------------------------------------------------------------------------------- /regtests/list/pop.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """list.pop(n)""" 3 | 4 | 5 | def main(): 6 | a = list(range(10)) 7 | print a 8 | b = a.pop() 9 | print b 10 | print a 11 | assert( b==9 ) 12 | c = a.pop(0) 13 | assert( c==0 ) 14 | 15 | d = ['A', 'B', 'C'] 16 | assert( d.pop(1)=='B' ) 17 | assert( len(d)==2 ) 18 | main() 19 | -------------------------------------------------------------------------------- /regtests/list/range.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """range""" 3 | def main(): 4 | a = range(10) 5 | assert( len(a)==10 ) 6 | assert( a[0] == 0 ) 7 | assert( a[9] == 9 ) 8 | 9 | b = range(1,10) 10 | assert( len(b)==9 ) 11 | assert( b[0] == 1 ) 12 | assert( b[8] == 9 ) 13 | 14 | 15 | main() 16 | -------------------------------------------------------------------------------- /regtests/list/remove.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """remove""" 3 | 4 | def main(): 5 | a = [1,2] 6 | a.remove(1) 7 | assert( len(a) == 1 ) 8 | 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /regtests/list/set_slice.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """list slice set""" 3 | 4 | 5 | def main(): 6 | a = list(range(10)) 7 | for v in a: print v 8 | a[ 2:4 ] = 'Y' 9 | print a 10 | print '------------' 11 | for v in a: 12 | print v 13 | 14 | assert( a[0]==0 ) 15 | assert( a[1]==1 ) 16 | 17 | assert( a[2]=='Y' ) 18 | 19 | assert( a[3]==4 ) 20 | assert( a[4]==5 ) 21 | assert( a[5]==6 ) 22 | assert( a[6]==7 ) 23 | assert( a[7]==8 ) 24 | assert( a[8]==9 ) 25 | 26 | b = list(range(3)) 27 | print b 28 | c = b [ :2 ] 29 | print c 30 | assert len(c)==2 31 | assert( c[0]==0 ) 32 | assert( c[1]==1 ) 33 | print '----------' 34 | print b 35 | b[ :2 ] = 'ABC' 36 | print b 37 | assert( len(b)==4 ) 38 | assert( b[0]=='A' ) 39 | assert( b[1]=='B' ) 40 | assert( b[2]=='C' ) 41 | assert b[3]==2 42 | 43 | e = range(5) 44 | print e 45 | e[ 2:3 ] = 'x' 46 | print e 47 | assert e[2]=='x' 48 | 49 | 50 | d = list(range(10)) 51 | d[ 2:4 ] = [99, 100] 52 | assert( d[0]==0 ) 53 | assert( d[1]==1 ) 54 | assert( d[2]==99 ) 55 | assert( d[3]==100 ) 56 | print d 57 | 58 | main() 59 | -------------------------------------------------------------------------------- /regtests/list/setitem.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """setitem and append""" 3 | def main(): 4 | a = [1,2,3,4] 5 | idx = 1 6 | assert( a[0]==1 ) 7 | assert( a[idx]==2 ) 8 | 9 | a[ 0 ] = 'hello' 10 | a[ 1 ] = 'world' 11 | assert( a[0]=='hello' ) 12 | assert( a[1]=='world' ) 13 | 14 | a.append( 'xxx' ) 15 | assert( a[4]=='xxx' ) 16 | assert( len(a)==5 ) 17 | 18 | a.append( 'yyy' ) 19 | assert( a[5]=='yyy' ) 20 | assert( len(a)==6 ) 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /regtests/list/simple.py: -------------------------------------------------------------------------------- 1 | """basics""" 2 | from runtime import * 3 | 4 | def main(): 5 | a = [1,2,3,4] 6 | assert( len(a)==4 ) 7 | 8 | b = list() 9 | assert( len(b)==0 ) 10 | b.append( 5 ) 11 | assert len(b)==1 12 | 13 | with oo: 14 | a += b 15 | assert len(a)==5 16 | 17 | ## the pythonic way 18 | a.extend( b ) 19 | assert len(a)==6 20 | 21 | main() -------------------------------------------------------------------------------- /regtests/list/slice.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """list slice""" 3 | 4 | class XXX: 5 | def __init__(self): 6 | self.v = range(10) 7 | def method(self, a): 8 | return a 9 | 10 | def main(): 11 | a = range(10)[:-5] 12 | assert( len(a)==5 ) 13 | assert( a[4]==4 ) 14 | 15 | print '--------' 16 | b = range(10)[::2] 17 | print b 18 | assert( len(b)==5 ) 19 | assert( b[0]==0 ) 20 | assert( b[1]==2 ) 21 | assert( b[2]==4 ) 22 | assert( b[3]==6 ) 23 | assert( b[4]==8 ) 24 | 25 | #if BACKEND=='DART': 26 | # print(b[...]) 27 | #else: 28 | # print(b) 29 | 30 | 31 | c = range(20) 32 | d = c[ len(b) : ] 33 | 34 | #if BACKEND=='DART': 35 | # print(d[...]) 36 | #else: 37 | # print(d) 38 | 39 | assert( len(d)==15 ) 40 | 41 | x = XXX() 42 | e = x.v[ len(b) : ] 43 | assert( len(e)==5 ) 44 | 45 | f = x.method( x.v[len(b):] ) 46 | assert( len(f)==5 ) 47 | 48 | main() 49 | -------------------------------------------------------------------------------- /regtests/list/slice_reverse.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """list reverse slice""" 3 | 4 | 5 | def main(): 6 | a = range(10) 7 | b = a[ 4::-1 ] 8 | 9 | #if BACKEND=='DART': 10 | # print(b[...]) 11 | #else: 12 | # print(b) 13 | 14 | 15 | assert( b[0]==4 ) 16 | assert( b[1]==3 ) 17 | assert( b[2]==2 ) 18 | assert( b[3]==1 ) 19 | assert( b[4]==0 ) 20 | 21 | c = range(20) 22 | d = c[ 2::-1 ] 23 | 24 | #if BACKEND=='DART': 25 | # print(d[...]) 26 | #else: 27 | # print(d) 28 | 29 | assert( d[0]==2 ) 30 | assert( d[1]==1 ) 31 | assert( d[2]==0 ) 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /regtests/list/sort.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """list sort""" 3 | 4 | def main(): 5 | x = [100, 10, 3,2,1] 6 | x.sort() 7 | assert( x[0]==1 ) 8 | assert( x[1]==2 ) 9 | assert( x[2]==3 ) 10 | assert( x[3]==10 ) 11 | assert( x[4]==100 ) 12 | 13 | y = ['C', 'B', 'A'] 14 | y.sort() 15 | assert( y[0]=='A' ) 16 | assert( y[1]=='B' ) 17 | assert( y[2]=='C' ) 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /regtests/loop/for_else.py: -------------------------------------------------------------------------------- 1 | ''' 2 | for else loop (DEPRECATED) 3 | ''' 4 | 5 | def main(): 6 | for i in range(10): 7 | if i==0: 8 | break 9 | 10 | else: 11 | pass 12 | 13 | 14 | -------------------------------------------------------------------------------- /regtests/loop/for_loop.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | for loop tests 4 | ''' 5 | 6 | def main(): 7 | 8 | a = [1,2,3] 9 | y = 0 10 | for x in a: 11 | y += x 12 | assert( y==6 ) 13 | 14 | z = '' 15 | arr = ['a', 'b', 'c'] 16 | for v in arr: 17 | z += v 18 | assert( z == 'abc' ) 19 | 20 | b = False 21 | if 'a' in arr: 22 | b = True 23 | assert( b == True ) 24 | 25 | s = 'hello world' 26 | z = '' 27 | for char in iter(s): 28 | z += char 29 | assert( z == 'hello world' ) 30 | 31 | b = False 32 | if 'hello' in s: 33 | b = True 34 | assert( b==True ) 35 | 36 | print 'testing for loop over dict' 37 | ob = {'a' : 'A', 'b' : 'B'} 38 | k = '' 39 | v = '' 40 | for key in iter(ob): 41 | k += key 42 | v += ob[key] 43 | print k 44 | print v 45 | assert(k=='ab' or k=='ba') 46 | assert(v=='AB' or v=='BA') 47 | 48 | keys = [] 49 | values = [] 50 | for x,y in ob.items(): 51 | keys.append( x ) 52 | values.append( y ) 53 | 54 | assert( 'a' in keys ) 55 | assert( 'A' in values ) 56 | 57 | ob2 = {'c':'C', 'd':'D'} 58 | e = 0 59 | arr = [] 60 | for x,y in ob.items(): 61 | arr.append(x) 62 | arr.append(y) 63 | for w,z in ob2.items(): 64 | e += 1 65 | arr.append(w) 66 | arr.append(z) 67 | 68 | assert( e==4 ) 69 | assert( 'a' in arr) 70 | assert( 'b' in arr) 71 | assert( 'A' in arr) 72 | assert( 'B' in arr) 73 | assert( 'c' in arr) 74 | assert( 'C' in arr) 75 | assert( 'd' in arr) 76 | assert( 'D' in arr) 77 | 78 | 79 | 80 | main() 81 | -------------------------------------------------------------------------------- /regtests/loop/interval_loop.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | timeout decorator with loop 4 | ''' 5 | 6 | counter = 0 7 | 8 | def main(): 9 | @timeout(1) 10 | def foo(): 11 | print 'foo' 12 | 13 | @timeout(1, loop=True) 14 | def bar(): 15 | global counter 16 | print 'bar:'+counter 17 | counter += 1 18 | if counter > 5: 19 | process.exit() 20 | 21 | main() 22 | -------------------------------------------------------------------------------- /regtests/loop/range.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | range builtin 4 | ''' 5 | 6 | def main(): 7 | a = range(10) 8 | assert( a[0]==0 ) 9 | assert( a[1]==1 ) 10 | assert( len(a)==10 ) 11 | 12 | b = range(1,10) 13 | assert( b[0]==1 ) 14 | assert( b[1]==2 ) 15 | assert( len(b)==9 ) 16 | 17 | c = 0 18 | for i in range(10): 19 | c += 1 20 | assert( c == 10 ) 21 | 22 | d = 0 23 | for i in range(1, 10): 24 | d += 1 25 | assert( d == 9 ) 26 | 27 | e = 0 28 | for i in range(1, 8+2): 29 | e += 1 30 | assert( e == 9 ) 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /regtests/loop/while.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | while loop 4 | ''' 5 | 6 | arr1 = [] 7 | arr2 = [] 8 | 9 | def main(): 10 | a = 0 11 | i = 0 12 | while i < 10: 13 | j = 0 14 | while j < 10: 15 | a += 1 16 | j += 1 17 | i += 1 18 | 19 | assert( a==100 ) 20 | 21 | while len(arr1)+len(arr2) < 10: 22 | arr1.append( 1 ) 23 | arr2.append( 2 ) 24 | 25 | assert( len(arr1)==5 ) 26 | assert( len(arr2)==5 ) 27 | 28 | main() 29 | -------------------------------------------------------------------------------- /regtests/loop/while_else.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | while else loop (DEPRECATED) 4 | ''' 5 | 6 | def main(): 7 | 8 | a = False 9 | i = 0 10 | while i < 10: 11 | i += 1 12 | else: 13 | a = True 14 | 15 | assert( a==True ) 16 | 17 | b = False 18 | i = 0 19 | while i < 10: 20 | i += 1 21 | break 22 | else: 23 | b = True 24 | 25 | assert( b==False ) 26 | 27 | 28 | main() 29 | -------------------------------------------------------------------------------- /regtests/loop/yield.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | ''' 3 | generator function, requires javascript ES6. 4 | ''' 5 | 6 | def fib(n:int) -> int: 7 | a = 0 8 | b = 1 9 | c = 0 10 | 11 | for x in range(n): 12 | #print('looping') 13 | yield a 14 | c = b 15 | b = a+b 16 | a = c 17 | 18 | yield -1 ## signals end 19 | 20 | def main(): 21 | arr = []int() 22 | for n in fib(20): 23 | #print(n) 24 | arr.append( n ) 25 | 26 | assert( arr[0]==0 ) 27 | assert( arr[1]==1 ) 28 | assert( arr[2]==1 ) 29 | assert( arr[3]==2 ) 30 | assert( arr[4]==3 ) 31 | assert( arr[5]==5 ) 32 | assert( arr[6]==8 ) 33 | assert( arr[7]==13 ) 34 | assert( arr[8]==21 ) 35 | assert( arr[9]==34 ) 36 | assert( arr[10]==55 ) 37 | 38 | main() 39 | -------------------------------------------------------------------------------- /regtests/regtest-report-js-set.md: -------------------------------------------------------------------------------- 1 | JavaScript Backend Regression Tests - set 2 | ----------------------------- 3 | the following tests compiled, and run in nodejs without any errors 4 | * [issubset.py](set/issubset.py) 5 | 6 | input: 7 | ------ 8 | ```python 9 | from runtime import * 10 | """get/set remote attributes""" 11 | 12 | def main(): 13 | x = set([1,2,3]) 14 | y = set([1,2,3,4]) 15 | 16 | assert( x.issubset(y)==True ) 17 | assert( y.issubset(x)==False ) 18 | 19 | 20 | main() 21 | ``` 22 | output: 23 | ------ 24 | ```javascript 25 | 26 | 27 | var main = function main(){ 28 | /***/var ƒ = arguments.callee; 29 | /***/ if (main.__recompile !== undefined) { eval("main.__redef="+main.__recompile); main.__recompile=undefined; }; 30 | /***/ if (main.__redef !== undefined) { return main.__redef.apply(this,arguments); }; 31 | var y,x; 32 | ƒ.locals.x=x = set([1, 2, 3]); 33 | ƒ.locals.y=y = set([1, 2, 3, 4]); 34 | if (!(x.issubset(y) === true)) {throw new Error("assertion failed"); } 35 | if (!(y.issubset(x) === false)) {throw new Error("assertion failed"); } 36 | }/*end-> `main` */ 37 | main.locals={}; 38 | 39 | main(); 40 | ``` -------------------------------------------------------------------------------- /regtests/requirejs/import_p2js.py: -------------------------------------------------------------------------------- 1 | '''load p2.js physics library''' 2 | # sudo npm install -g p2 3 | import p2 4 | 5 | def main(): 6 | v1 = p2.vec2.create() 7 | v2 = p2.vec2.fromValues(10,20) 8 | TestError( len(v1)==2 ) 9 | TestError( v2[0]==10 ) 10 | TestError( v2[1]==20 ) 11 | 12 | -------------------------------------------------------------------------------- /regtests/requirejs/import_threejs.py: -------------------------------------------------------------------------------- 1 | '''load three.js library''' 2 | # sudo npm install -g three 3 | import three 4 | 5 | def main(): 6 | v1 = new( three.Vector3(1,2,3) ) 7 | TestError( len(v1)==3 ) 8 | TestError( v1.x==1 ) 9 | TestError( v1.y==2 ) 10 | TestError( v1.z==3 ) 11 | 12 | 13 | -------------------------------------------------------------------------------- /regtests/requirejs/webworker_p2js.py: -------------------------------------------------------------------------------- 1 | '''import p2.js inside webworker''' 2 | # sudo npm install -g p2 3 | import threading 4 | from time import sleep 5 | 6 | def main(): 7 | shared = [] 8 | w = threading.start_webworker( worker, [shared] ) 9 | sleep(1.0) 10 | 11 | TestError( len(shared)==2 ) 12 | TestError( shared[0]==10 ) 13 | TestError( shared[1]==20 ) 14 | 15 | 16 | with webworker: 17 | import p2 18 | 19 | def worker( arr ): 20 | v = p2.vec2.fromValues(10,20) 21 | arr.append( v[0] ) 22 | arr.append( v[1] ) 23 | -------------------------------------------------------------------------------- /regtests/rpc/async_iter.py: -------------------------------------------------------------------------------- 1 | """iteration""" 2 | ## note mycollection is hard coded in run.py as `range(10)` 3 | 4 | def main(): 5 | a = [] 6 | with rpc('http://localhost:8080') as server: 7 | for ob in server.mycollection: 8 | a.append( ob ) 9 | 10 | print(a) 11 | TestError( len(a)==10 ) 12 | TestError( a[0]==0 ) 13 | TestError( a[1]==1 ) 14 | TestError( a[2]==2 ) 15 | 16 | -------------------------------------------------------------------------------- /regtests/rpc/attr.py: -------------------------------------------------------------------------------- 1 | """get/set remote attributes""" 2 | 3 | def main(): 4 | x = None 5 | y = None 6 | with rpc('http://localhost:8080') as server: 7 | server.A = 'hi' 8 | server.B = 100 9 | x = server.A 10 | y = server.B 11 | 12 | TestError( x == 'hi' ) 13 | TestError( y == 100 ) 14 | 15 | -------------------------------------------------------------------------------- /regtests/rpc/hello_server.py: -------------------------------------------------------------------------------- 1 | """simple rpc call""" 2 | 3 | def main(): 4 | a = 'hello' 5 | b = 'server' 6 | x = 100 7 | y = 200 8 | with rpc('http://localhost:8080'): 9 | c = concat( a, b ) 10 | z = add( x, y ) 11 | 12 | TestError( c == 'helloserver' ) 13 | TestError( z == 300 ) 14 | 15 | -------------------------------------------------------------------------------- /regtests/rpc/hello_server_as.py: -------------------------------------------------------------------------------- 1 | """simple rpc call""" 2 | 3 | def f(v): 4 | return v * 2 5 | 6 | def main(): 7 | a = 'hello' 8 | b = 'server' 9 | x = 100 10 | y = 200 11 | with rpc('http://localhost:8080') as server: 12 | c = server.concat( a, b ) 13 | z = server.add( x, y ) 14 | w = f(z) 15 | 16 | TestError( c == 'helloserver' ) 17 | TestError( z == 300 ) 18 | TestError( w == 600 ) 19 | 20 | -------------------------------------------------------------------------------- /regtests/rust/arrays.py: -------------------------------------------------------------------------------- 1 | """array types""" 2 | 3 | def test_pass_array_as_arg( arr:[]int ): 4 | #m = arr.borrow_mut() 5 | #m.push( 5 ) 6 | arr.append( 5 ) 7 | 8 | def main(): 9 | a = []int(1,2,3) 10 | assert a[0]==1 11 | assert len(a)==3 12 | a.append( 4 ) 13 | 14 | assert len(a)==4 15 | 16 | test_pass_array_as_arg( a.clone() ) ## Rc needs to be cloned because `a` is used after this call below. 17 | assert len(a)==5 18 | 19 | b = [2]int(100,200) 20 | assert b[0]==100 21 | assert b[1]==200 22 | 23 | #c = a[:2] 24 | #TestError( len(c)==2 ) 25 | 26 | #d = range(10) 27 | #TestError(len(d)==10) 28 | #d.append(99) 29 | #TestError(len(d)==11) 30 | 31 | #e = range(2,10) 32 | #TestError(len(e)==8) 33 | 34 | #f = range(2,10, 2) 35 | #TestError(len(f)==4) 36 | -------------------------------------------------------------------------------- /regtests/rust/chan.py: -------------------------------------------------------------------------------- 1 | """rust send int over channel""" 2 | 3 | def sender_wrapper(a:int, send: Sender ): 4 | result = 100 5 | send <- result 6 | 7 | def recv_wrapper(a:int, recver: Receiver ) -> int: 8 | v = <- recver 9 | return v 10 | 11 | def main(): 12 | sender, recver = channel(int) 13 | spawn( sender_wrapper(17, sender) ) 14 | # Do other work in the current goroutine until the channel has a result. 15 | x = recv_wrapper(2, recver) 16 | #x = <-recver 17 | print(x) 18 | assert x==100 19 | -------------------------------------------------------------------------------- /regtests/rust/chan_universal_style.py: -------------------------------------------------------------------------------- 1 | """send int over channel for rust, go, and c++""" 2 | 3 | def sender_wrapper(a:int, send: chan Sender ): 4 | result = 100 5 | send <- result 6 | 7 | def recv_wrapper(a:int, recver: chan Receiver ) -> int: 8 | v = <- recver 9 | return v 10 | 11 | def main(): 12 | ## sender and recver are the same object in Go and C++ 13 | sender, recver = channel(int) 14 | spawn( sender_wrapper(17, sender) ) 15 | # Do other work in the current goroutine until the channel has a result. 16 | x = recv_wrapper(2, recver) 17 | print(x) 18 | assert x==100 19 | -------------------------------------------------------------------------------- /regtests/rust/ffi_hello.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ffi 3 | ''' 4 | # ABI types: stdcall, aapcs, cdecl, fastcall, Rust, rust-intrinsic, system, C, win64 5 | import libc 6 | from libc import c_int 7 | 8 | with extern(link="readline", abi="C"): 9 | let rl_readline_version : c_int 10 | 11 | def main(): 12 | print rl_readline_version 13 | 14 | -------------------------------------------------------------------------------- /regtests/rust/list_comp.py: -------------------------------------------------------------------------------- 1 | ''' 2 | rust list comprehensions 3 | ''' 4 | class A: 5 | def __init__(self, id:int ): 6 | self.id = id 7 | 8 | 9 | def test_pass_array( arr:[]int ): 10 | arr.append( 3 ) 11 | 12 | # `[]A` for c++11 backend becomes `std::shared_ptr>>` 13 | def test_pass_array_of_objects( arr:[]A, id:int ): 14 | a = A( id ) 15 | arr.append( a ) 16 | 17 | def main(): 18 | a = []int(x for x in range(3)) 19 | assert len(a)==3 20 | assert a[0]==0 21 | assert a[1]==1 22 | assert a[2]==2 23 | 24 | test_pass_array( a ) 25 | assert len(a)==4 26 | assert a[3]==3 27 | 28 | #b = []A( A(x) for x in ['list', 'comp']) ## TODO fix me, infer type 29 | 30 | #stuff = []string('list', 'comp') 31 | #b = []A( A(x) for x in stuff) 32 | #b = []A( A(x) for x in ('list', 'comp')) ## TODO fix strings 33 | 34 | b = []A( A(x) for x in (1,2,3,4)) 35 | assert len(b)==4 36 | test_pass_array_of_objects( b, 5 ) 37 | assert len(b)==5 38 | -------------------------------------------------------------------------------- /regtests/rust/multiple_inheritance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | multiple inheritance 3 | ''' 4 | class A: 5 | def foo(self) -> int: 6 | return 1 7 | 8 | class B: 9 | def bar(self) -> int: 10 | return 2 11 | 12 | class C( A, B ): 13 | def call_foo_bar(self) -> int: 14 | let mut a = self.foo() 15 | a += self.bar() 16 | return a 17 | 18 | def foo(self) -> int: 19 | return 100 20 | def bar(self) -> int: 21 | return 200 22 | 23 | def test_parents(self) -> int: 24 | #return A.foo(self) + B.bar(self) ## this also works 25 | return A.foo() + B.bar() 26 | 27 | 28 | def main(): 29 | a = A() 30 | assert a.foo()==1 31 | b = B() 32 | assert b.bar()==2 33 | 34 | c = C() 35 | assert c.foo()==100 36 | assert c.bar()==200 37 | 38 | assert c.call_foo_bar()==300 39 | assert c.test_parents()==3 40 | -------------------------------------------------------------------------------- /regtests/rust/pointer_syntax.py: -------------------------------------------------------------------------------- 1 | ''' 2 | rust pointer and typedefs 3 | ''' 4 | # this is just for testing syntax, the rustc may have errors on this code 5 | 6 | def f(a:&mut int) ->int: 7 | return a 8 | 9 | 10 | def main(): 11 | #f(&mut *x) 12 | #f(@mut *x, y.z()) ## translates to `ref mut *x`, but this might be deprecated in the latest rust. 13 | f(x as uint) 14 | 15 | let x : Vec<(uint, Y)> = range(0,1).map().collect() 16 | let i 17 | #i = &**x 18 | 19 | -------------------------------------------------------------------------------- /regtests/rust/rust_select.py: -------------------------------------------------------------------------------- 1 | """rust select""" 2 | 3 | def send_data( A:chan Sender, B:chan Sender, X:int, Y:int): 4 | while True: 5 | print('sending data..') 6 | A <- X 7 | B <- Y 8 | 9 | def select_loop(A:chan Receiver, B:chan Receiver, W:chan Sender) -> int: 10 | print('starting select loop') 11 | let x : int 12 | y = 0 13 | while True: 14 | print('select loop:',y) 15 | select: 16 | case x = <- A: 17 | y += x 18 | W <- y 19 | case x = <- B: 20 | y += x 21 | W <- y 22 | print('end select loop', y) 23 | return y 24 | 25 | def main(): 26 | asender, arecver = channel(int) 27 | bsender, brecver = channel(int) 28 | wsender, wrecver = channel(int) 29 | 30 | t1 = spawn( 31 | select_loop(arecver,brecver, wsender) 32 | ) 33 | t1.detach() 34 | 35 | t2 = spawn( 36 | send_data(asender,bsender, 5, 10) 37 | ) 38 | t2.detach() 39 | 40 | z = 0 41 | while z < 100: 42 | z = <- wrecver 43 | print('main loop', z) 44 | 45 | print('end test') -------------------------------------------------------------------------------- /regtests/rust/simple_class.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple class 3 | ''' 4 | class A: 5 | def __init__(self, x:int, y:int, z:int): 6 | self.x = x 7 | self.y = y 8 | self.z = z 9 | 10 | def mymethod(self, m:int) -> int: 11 | return self.x * m 12 | 13 | def call_method( cb:lambda(int)(int), mx:int ) ->int: 14 | return cb(mx) 15 | 16 | def main(): 17 | a = A( 100, 200, 9999 ) 18 | print( a.x ) 19 | print( a.y ) 20 | print( a.z ) 21 | assert a.x == 100 22 | 23 | b = a.mymethod(3) 24 | print( b ) 25 | 26 | ## taking the address of a method pointer is not allowed in rust 27 | ## http://stackoverflow.com/questions/24728394/rust-method-pointer 28 | ##c = call_method( a.mymethod, 4 ) 29 | 30 | c = call_method( lambda W=int: a.mymethod(W), 4 ) 31 | print( c ) -------------------------------------------------------------------------------- /regtests/rust/simple_subclass.py: -------------------------------------------------------------------------------- 1 | ''' 2 | simple subclass 3 | ''' 4 | class A: 5 | def __init__(self, x:int, y:int, z:int): 6 | self.x = x 7 | self.y = y 8 | self.z = z 9 | 10 | def mymethod(self, m:int) -> int: 11 | return self.x * m 12 | 13 | class B(A): 14 | def __init__(self, s:string): 15 | A.__init__(self, 4, 5, 6) 16 | let self.w : string = s 17 | let self.x : int = 1 18 | 19 | def method2(self, v:string) ->string: 20 | print(self.x) 21 | self.w = v 22 | ## returning `self.w` or `v` is not allowed in Rust, 23 | ## because `v` is now owned by `self` 24 | #return self.w 25 | return "ok" 26 | 27 | def call_method( cb:lambda(int)(int), mx:int ) ->int: 28 | return cb(mx) 29 | 30 | def main(): 31 | a = A( 100, 200, 9999 ) 32 | print( a.x ) 33 | print( a.y ) 34 | print( a.z ) 35 | 36 | b = a.mymethod(3) 37 | print( b ) 38 | 39 | c = call_method( lambda W=int: a.mymethod(W), 4 ) 40 | print( c ) 41 | 42 | x = B('testing...') 43 | print( x.method2('hello world') ) 44 | print( x.w ) 45 | -------------------------------------------------------------------------------- /regtests/rust/try.py: -------------------------------------------------------------------------------- 1 | ''' 2 | rust try! 3 | ''' 4 | 5 | def myfunc(): 6 | b = False 7 | try: 8 | print('trying something that will fail...') 9 | print('some call that fails at runtime') 10 | #f = open('/tmp/nosuchfile') 11 | raise RuntimeError() 12 | except: 13 | b = True 14 | 15 | TestError( b == True ) 16 | print('ok') 17 | 18 | def main(): 19 | myfunc() 20 | -------------------------------------------------------------------------------- /regtests/set/issubset.py: -------------------------------------------------------------------------------- 1 | from runtime import * 2 | """get/set remote attributes""" 3 | 4 | def main(): 5 | x = set([1,2,3]) 6 | y = set([1,2,3,4]) 7 | 8 | assert( x.issubset(y)==True ) 9 | assert( y.issubset(x)==False ) 10 | 11 | 12 | main() 13 | -------------------------------------------------------------------------------- /regtests/stdlib/array.py: -------------------------------------------------------------------------------- 1 | '''stdlib array''' 2 | from array import array 3 | 4 | def main(): 5 | a = array('i', [1,2,3]) 6 | TestError( len(a)==3 ) 7 | TestError( a[0]==1 ) 8 | TestError( 3 in a ) 9 | x = 0 10 | for y in a: 11 | x += y 12 | TestError( x == 6 ) 13 | 14 | ## this fails in javascript-mode because it is a raw typed array can not be resized 15 | #a.append( 4 ) 16 | #TestError( len(a)==4 ) 17 | 18 | 19 | -------------------------------------------------------------------------------- /regtests/stdlib/json.py: -------------------------------------------------------------------------------- 1 | '''stdlib json''' 2 | import json 3 | 4 | def main(): 5 | x = ['a', 'b'] 6 | s = json.dumps( x ) 7 | y = json.loads( s ) 8 | TestError( len(y)==2 ) 9 | TestError( y[0]=='a' ) 10 | TestError( y[1]=='b' ) 11 | -------------------------------------------------------------------------------- /regtests/stdlib/math_and_random.py: -------------------------------------------------------------------------------- 1 | import math, random 2 | 3 | def main(): 4 | print math.pi 5 | print math.sin(1) 6 | print math.cos(1) 7 | 8 | print random.random() 9 | print random.uniform(-1, 1) 10 | 11 | main() -------------------------------------------------------------------------------- /regtests/stdlib/sleep.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | 3 | def main(): 4 | sleep(0.01) 5 | a = [] 6 | sleep(0.1) 7 | a.append(1) 8 | sleep(0.1) 9 | a.append(2) 10 | 11 | TestError( len(a)==2 ) -------------------------------------------------------------------------------- /regtests/str/basics.py: -------------------------------------------------------------------------------- 1 | """string basics""" 2 | 3 | from runtime import * 4 | 5 | def main(): 6 | assert(len('a') == 1) 7 | a = 'XYZ' 8 | assert( a[0] == 'X' ) 9 | assert( a[-1] == 'Z' ) 10 | assert( a[0:2] == 'XY' ) 11 | assert( a[:2] == 'XY' ) 12 | assert( a[1:3] == 'YZ' ) 13 | assert( a[1:] == 'YZ' ) 14 | assert( a[-3:-1] == 'XY' ) 15 | 16 | assert( a.lower() == 'xyz' ) 17 | b = 'abc' 18 | assert( b.upper() == 'ABC' ) 19 | 20 | assert( ord('A') == 65 ) 21 | assert( chr(65) == 'A' ) 22 | 23 | c = '%s-%s' %('xxx', 'yyy') 24 | assert( c == 'xxx-yyy' ) 25 | 26 | d = 'a b c'.split() 27 | assert( d[0]=='a' ) 28 | assert( d[1]=='b' ) 29 | assert( d[2]=='c' ) 30 | 31 | d = 'a,b,c'.split(',') 32 | assert( d[0]=='a' ) 33 | assert( d[1]=='b' ) 34 | assert( d[2]=='c' ) 35 | 36 | e = 'x%sx' %1 37 | assert( e=='x1x' ) 38 | 39 | f = 'x"y' 40 | assert( ord(f[1]) == 34 ) 41 | 42 | f = 'x\"y' 43 | assert( ord(f[1]) == 34 ) 44 | 45 | f = 'x\'y"' 46 | assert( ord(f[1]) == 39 ) 47 | 48 | f = '\r' 49 | assert( ord(f[0]) == 13 ) 50 | 51 | main() -------------------------------------------------------------------------------- /regtests/str/compare.py: -------------------------------------------------------------------------------- 1 | """compare""" 2 | 3 | from runtime import * 4 | 5 | def main(): 6 | a = 'XYZ' 7 | b = 'XYZ' 8 | assert( a == b ) 9 | 10 | x = False 11 | if 'a' < 'b': 12 | x = True 13 | 14 | assert( x==True ) 15 | 16 | assert( 'a' < 'b' ) 17 | 18 | main() -------------------------------------------------------------------------------- /regtests/str/format.py: -------------------------------------------------------------------------------- 1 | """string.format""" 2 | from runtime import * 3 | 4 | def main(): 5 | a = '{x}{y}'.format( x='A', y='B') 6 | assert(a == 'AB') 7 | 8 | main() -------------------------------------------------------------------------------- /regtests/str/iter.py: -------------------------------------------------------------------------------- 1 | """string iteration requires wrappingn with `iter(my)`""" 2 | from runtime import * 3 | 4 | def main(): 5 | a = list("abc") 6 | print a 7 | assert(a[0] == 'a') 8 | assert(a[1] == 'b') 9 | assert(a[2] == 'c') 10 | print '--------' 11 | b = ['a'] 12 | for chr in iter("xyz"): 13 | print chr 14 | b.append(chr) 15 | print b 16 | print '--------' 17 | print b 18 | assert(b[0] == 'a') 19 | assert(b[1] == 'x') 20 | assert(b[2] == 'y') 21 | assert(b[3] == 'z') 22 | 23 | b = ['a'] 24 | mystr = "xyz" 25 | for char in iter(mystr): 26 | print char 27 | b.append(char) 28 | print b 29 | print '--------' 30 | print b 31 | assert(b[0] == 'a') 32 | assert(b[1] == 'x') 33 | assert(b[2] == 'y') 34 | assert(b[3] == 'z') 35 | 36 | x = [] 37 | y = [1,2,3] 38 | ## should be faster to call iter(myarr) when myarry is short. 39 | ## for long arrays use `for v in myarry` 40 | for v in iter(y): 41 | x.append(v) 42 | print v 43 | print x 44 | print '--' 45 | print x 46 | 47 | main() -------------------------------------------------------------------------------- /regtests/str/mul.py: -------------------------------------------------------------------------------- 1 | """string multiplication""" 2 | from runtime import * 3 | 4 | def main(): 5 | print 'testing string multiplication' 6 | assert 'hi'*2 == 'hihi' 7 | a = 'hi' 8 | 9 | ## this fails because `a` is not a string literal, 10 | ## operator overloading must be used for this to work. 11 | #assert a*2 == 'hihi' 12 | 13 | with oo: 14 | b = a * 2 15 | 16 | assert( b == 'hihi' ) 17 | 18 | ## you can also be verbose, and use `__mul__` directly 19 | assert a.__mul__(2) == 'hihi' 20 | print 'OK' 21 | 22 | main() -------------------------------------------------------------------------------- /regtests/str/replace.py: -------------------------------------------------------------------------------- 1 | """replace""" 2 | from runtime import * 3 | 4 | def main(): 5 | a = 'abc' 6 | b = a.replace('a', 'A') 7 | assert( b == 'Abc') 8 | 9 | a = 'aaa' 10 | b = a.replace('a', 'A') 11 | assert( b == 'AAA') 12 | 13 | main() -------------------------------------------------------------------------------- /regtests/str/specials.py: -------------------------------------------------------------------------------- 1 | """Specials chars in strings""" 2 | from runtime import * 3 | 4 | class C: 5 | def __init__(self): 6 | self.value = None 7 | 8 | def main(): 9 | print 'testing special strings' 10 | assert(len('\\') == 1) 11 | #a = u'éè' ## prefixing `u` is invalid, and will cause UnicodeDecodeError 12 | 13 | a = 'éè' 14 | print a 15 | assert( a == 'é' + 'è') 16 | 17 | c = C() 18 | c.value = "é" 19 | assert( c.value == 'é') 20 | 21 | assert len('éè') == 2 22 | assert('éè'[::-1] == 'èé') 23 | print 'ok' 24 | 25 | main() -------------------------------------------------------------------------------- /regtests/str/sprintf.py: -------------------------------------------------------------------------------- 1 | """sprintf""" 2 | from runtime import * 3 | 4 | def main(): 5 | a = '%s.%s' %('X', 'Y') 6 | print a 7 | assert(a[0] == 'X') 8 | assert(a[1] == '.') 9 | assert(a[2] == 'Y') 10 | 11 | b = 'X%sX' %1.1 12 | print b 13 | assert(b == 'X1.1X') 14 | 15 | c = 'foo%s %s' %(1*1, 2+2) 16 | print c 17 | 18 | main() -------------------------------------------------------------------------------- /regtests/test-all.py: -------------------------------------------------------------------------------- 1 | import os, subprocess 2 | os.chdir( os.path.split(__file__)[0] ) 3 | subprocess.check_call(['python', 'test-c++.py']) 4 | subprocess.check_call(['python', 'test-go.py']) 5 | subprocess.check_call(['python', 'test-javascript.py']) 6 | subprocess.check_call(['python', 'test-markdowns.py']) 7 | -------------------------------------------------------------------------------- /regtests/test-c++.py: -------------------------------------------------------------------------------- 1 | import os, sys, subprocess 2 | 3 | passed = {} 4 | ignore = () 5 | 6 | TODO_FIX = ( 7 | 'chain.py', 8 | 'generics_subclasses.py', 9 | ) 10 | 11 | files = os.listdir('./c++') 12 | files.reverse() 13 | for md in files: 14 | if md in TODO_FIX: 15 | print 'skip test: %s (TODO fix later)' %md 16 | continue 17 | elif not md.endswith('.py'): 18 | continue 19 | 20 | print md 21 | if md.startswith( ignore ): 22 | continue 23 | subprocess.check_call([ 24 | 'pythia', 25 | '--c++', 26 | os.path.join('./c++', md) 27 | ]) 28 | 29 | passed[ md ] = open('/tmp/rusthon-c++-build.cpp').read().split('/*end-builtins*/')[-1] 30 | 31 | 32 | print 'TESTS PASSED:' 33 | report = [ 34 | 'C++11 Backend Regression Tests', 35 | '-----------------------------', 36 | 'the following tests compiled, and the binary executed without any errors', 37 | ] 38 | 39 | for md in passed: 40 | print md 41 | report.append('* [%s](c++/%s)' %(md,md)) 42 | report.append('') 43 | report.append('input:') 44 | report.append('------') 45 | report.append('```python') 46 | report.extend( open('./c++/'+md, 'rb').read().splitlines() ) 47 | report.append('```') 48 | report.append('output:') 49 | report.append('------') 50 | report.append('```c++') 51 | report.extend( passed[md].splitlines() ) 52 | report.append('```') 53 | 54 | open('regtest-report-c++.md', 'wb').write('\n'.join(report)) 55 | -------------------------------------------------------------------------------- /regtests/test-go.py: -------------------------------------------------------------------------------- 1 | import os, sys, subprocess 2 | 3 | passed = {} 4 | ignore = () 5 | 6 | TODO_FIX = ( 7 | 'generics_subcls_return_a_subcls.py', 8 | 'generics_mreturns.py', 9 | 'generics_init.py', 10 | ) 11 | 12 | files = os.listdir('./go') 13 | files.reverse() 14 | for md in files: 15 | if md in TODO_FIX: 16 | print 'skip test: %s (TODO fix later)' %md 17 | continue 18 | elif not md.endswith('.py'): 19 | continue 20 | 21 | print md 22 | if md.startswith( ignore ): 23 | continue 24 | subprocess.check_call([ 25 | 'pythia', 26 | '--go', 27 | os.path.join('./go', md) 28 | ]) 29 | 30 | passed[ md ] = open('/tmp/rusthon-go-build.go').read().split('/*end-builtins*/')[-1] 31 | 32 | 33 | print 'TESTS PASSED:' 34 | report = [ 35 | 'Go Backend Regression Tests', 36 | '-----------------------------', 37 | 'the following tests compiled, and the binary executed without any errors', 38 | ] 39 | 40 | for md in passed: 41 | print md 42 | report.append('* [%s](go/%s)' %(md,md)) 43 | report.append('') 44 | report.append('input:') 45 | report.append('------') 46 | report.append('```python') 47 | report.extend( open('./go/'+md, 'rb').read().splitlines() ) 48 | report.append('```') 49 | report.append('output:') 50 | report.append('------') 51 | report.append('```go') 52 | report.extend( passed[md].splitlines() ) 53 | report.append('```') 54 | 55 | open('regtest-report-go.md', 'wb').write('\n'.join(report)) 56 | -------------------------------------------------------------------------------- /regtests/test-markdowns.py: -------------------------------------------------------------------------------- 1 | import os, sys, subprocess 2 | 3 | passed = [] 4 | ignore = ('fails_', 'giws_', 'unreal_', 'verilog', 'nuitka_', 'nim_', 'java_', 'custom_', 'cpython_', 'nodejs_', 'osv_') 5 | ignoreosx = ['hello_cpython.md'] 6 | 7 | ## rust is broken on fedora? Travis uses Debian. 8 | TODO_FIX = ( 9 | 'async_channels_rust.md', # rustc: error while loading shared libraries: librustc_driver-4e7c5e5c.so: cannot open shared object file: No such file or directory 10 | 'hello_nim.md', 11 | 'hello_verilog.md', 12 | 'cpython_multithreaded.md', 13 | 'cpython_multithreaded_raw_capi.md', 14 | 'hello_threejs.md', 15 | 'hello_java.md', 16 | 'hello_caffe.md', 17 | 'hello_nuitka.md', 18 | 'hello_rapydscript.md', 19 | 'hello_coffee.md', 20 | 'hello_elm.md', 21 | 'hello_fullstack.md', 22 | 'hello_openlayers.md', 23 | 'hello_sdl.md', 24 | 'hello_civetweb.md', 25 | 'hello_nw_gyp.md', 26 | 'hello_osv.md', 27 | ) 28 | 29 | files = os.listdir('../examples') 30 | files.reverse() 31 | for md in files: 32 | if md in TODO_FIX: 33 | print 'skip test: %s (TODO fix later)' %md 34 | continue 35 | elif not md.endswith('.md'): 36 | continue 37 | elif sys.platform=='darwin' and md in ignoreosx: 38 | continue 39 | 40 | print md 41 | if md.startswith( ignore ): 42 | continue 43 | subprocess.check_call([ 44 | 'pythia', 45 | os.path.join('../examples', md) 46 | ]) 47 | passed.append( md ) 48 | 49 | print 'TESTS PASSED:' 50 | for md in passed: 51 | print ' %s' %md 52 | -------------------------------------------------------------------------------- /regtests/test-rust.py: -------------------------------------------------------------------------------- 1 | import os, sys, subprocess 2 | 3 | passed = {} 4 | ignore = () 5 | 6 | TODO_FIX = ( 7 | 'ffi_hello.py', ## libc is unstable as of Rust1.2 8 | 'pointer_syntax.py', 9 | 'rust_select.py', 10 | 'try.py', 11 | ) 12 | 13 | files = os.listdir('./rust') 14 | files.sort() 15 | 16 | for md in files: 17 | if md in TODO_FIX: 18 | print 'skip test: %s (TODO fix later)' %md 19 | continue 20 | elif not md.endswith('.py'): 21 | continue 22 | 23 | print md 24 | if md.startswith( ignore ): 25 | continue 26 | subprocess.check_call([ 27 | 'python', 28 | '../rusthon.py', 29 | '--rust', 30 | os.path.join('./rust', md) 31 | ]) 32 | passed[ md ] = open('/tmp/rusthon-build.rs').read().split('/*end-builtins*/')[-1] 33 | 34 | report = [ 35 | 'Rust Backend Regression Tests', 36 | '-----------------------------', 37 | 'the following tests compiled, and the binary executed without any errors', 38 | ] 39 | print 'TESTS PASSED:' 40 | for md in passed: 41 | print md 42 | report.append('* [%s](rust/%s)' %(md,md)) 43 | report.append('') 44 | report.append('input:') 45 | report.append('------') 46 | report.append('```python') 47 | report.extend( open('./rust/'+md, 'rb').read().splitlines() ) 48 | report.append('```') 49 | report.append('output:') 50 | report.append('------') 51 | report.append('```rust') 52 | report.extend( passed[md].splitlines() ) 53 | report.append('```') 54 | 55 | open('regtest-report-rust.md', 'wb').write('\n'.join(report)) 56 | -------------------------------------------------------------------------------- /regtests/threads/args.py: -------------------------------------------------------------------------------- 1 | """simple thread""" 2 | from time import sleep 3 | import threading 4 | 5 | @webworker( 'xxx.js' ) 6 | def mythread(a,b, c): 7 | c.append( a ) 8 | c.append( b ) 9 | 10 | def main(): 11 | 12 | c = [] 13 | t = threading.start_new_thread( mythread, ('hello', 'worker', c) ) 14 | sleep(0.1) 15 | ticks = 0 16 | while len(c) < 2: 17 | ticks += 1 18 | if ticks > 100000: ## do not hangup if there is a bug in the webworker 19 | break 20 | 21 | TestError( c[0] == 'hello' ) 22 | TestError( c[1] == 'worker' ) 23 | -------------------------------------------------------------------------------- /regtests/threads/call_from_worker.py: -------------------------------------------------------------------------------- 1 | '''call function in main from inside webworker''' 2 | import threading 3 | from time import sleep 4 | 5 | shared = [] 6 | 7 | def myfunc( a, b ): 8 | shared.append( a ) 9 | shared.append( b ) 10 | 11 | def main(): 12 | w = threading.start_webworker( worker, [] ) 13 | sleep(1.0) 14 | 15 | TestError( len(shared)==2 ) 16 | TestError( shared[0]==10 ) 17 | TestError( shared[1]==20 ) 18 | 19 | 20 | with webworker: 21 | 22 | def worker(): 23 | myfunc( 10, 20 ) 24 | -------------------------------------------------------------------------------- /regtests/threads/call_from_worker_blocking.py: -------------------------------------------------------------------------------- 1 | '''call function from main and get result''' 2 | import threading 3 | from time import sleep 4 | 5 | shared = [] 6 | 7 | def blocking_func(x,y): 8 | shared.append( x ) 9 | shared.append( y ) 10 | return x+y 11 | 12 | def async_func( a ): 13 | shared.append( a ) 14 | 15 | def main(): 16 | w = threading.start_webworker( worker, [] ) 17 | sleep(1.0) 18 | 19 | TestError( len(shared)==3 ) 20 | TestError( shared[0]==10 ) 21 | TestError( shared[1]==20 ) 22 | TestError( shared[2]==30 ) 23 | 24 | 25 | with webworker: 26 | 27 | def worker(): 28 | ## the translator knows this is blocking because the result of the function is assigned to `v`, 29 | v = blocking_func( 10, 20 ) 30 | #print('returned to blocking callback', v) 31 | async_func( v ) 32 | self.terminate() 33 | -------------------------------------------------------------------------------- /regtests/threads/shared_dict.py: -------------------------------------------------------------------------------- 1 | """shared dict""" 2 | 3 | import threading 4 | 5 | @webworker( 'myworker.js' ) 6 | def mythread(a,b, lowlevel): 7 | ## checks a and b, if they are Array, then wrap them. 8 | if lowlevel: ## workaround for javascript mode 9 | a.__setitem__('x', 'hello') 10 | b.__setitem__('y', 'world') 11 | else: 12 | a[ 'x' ] = 'hello' 13 | b[ 'y' ] = 'world' 14 | 15 | def main(): 16 | 17 | shared1 = {} 18 | shared2 = {'z':100} 19 | 20 | t = threading.start_new_thread( mythread, (shared1, shared2, BACKEND=='JAVASCRIPT') ) 21 | 22 | ticks = 0 23 | while len(shared1) + len(shared2) < 2: 24 | ticks += 1 25 | if ticks > 10000: ## do not hangup if there is a bug in the webworker 26 | break 27 | 28 | TestError( shared1['x'] == 'hello' ) 29 | TestError( shared2['y'] == 'world' ) 30 | TestError( shared2['z'] == 100 ) 31 | 32 | -------------------------------------------------------------------------------- /regtests/threads/shared_dict_coop.py: -------------------------------------------------------------------------------- 1 | ''' 2 | threads shared dict 3 | ''' 4 | 5 | from time import time 6 | from time import sleep 7 | import threading 8 | 9 | 10 | def main(): 11 | if PYTHON=='PYTHONJS': 12 | pythonjs.configure( direct_operator='+' ) 13 | pass 14 | else: 15 | def l (f,a): threading._start_new_thread(f,a) 16 | threading.start_webworker = l 17 | 18 | seq = {} 19 | w1 = threading.start_webworker( worker, (seq, 'abcdefgh', 'i') ) 20 | w2 = threading.start_webworker( worker, (seq, 'ijklmnop', 'p') ) 21 | sleep(1.0) 22 | 23 | 24 | TestError( 'a' in seq ) 25 | TestError( 'i' in seq ) 26 | print('-----main exit') 27 | print(seq) 28 | 29 | if PYTHON != 'PYTHONJS': 30 | class webworker(object): 31 | def __enter__(self, *args): pass 32 | def __exit__(self, *args): pass 33 | webworker = webworker() 34 | 35 | with webworker: 36 | def worker(seq, s, break_on): 37 | print('------enter worker------') 38 | for char in s: 39 | seq[ char ] = True 40 | if break_on in seq: 41 | break 42 | #while break_on not in seq: 43 | # seq[ '-' ] = False 44 | sleep(0.1) # this sleep is not required in normal CPython 45 | 46 | print('worker exit') 47 | print(seq) 48 | 49 | -------------------------------------------------------------------------------- /regtests/threads/shared_list.py: -------------------------------------------------------------------------------- 1 | """shared list""" 2 | 3 | import threading 4 | 5 | 6 | @webworker( 'xxx.js' ) 7 | def mythread(a,b): 8 | ## checks a and b, if they are Array, then wrap them. 9 | a.append('hello') 10 | b.append('world') 11 | b.append( 'XXX' ) 12 | 13 | ## this fails if the worker is translated in javascript-mode because the method __setitem__ is not called, 14 | ## and instead b[1] is used directly. 15 | b[1] = 'YYY' 16 | 17 | ticks = 0 18 | while True: #'ZZZ' not in a: 19 | ticks += 1 20 | if ticks > 100000: 21 | break 22 | if 'ZZZ' in a: 23 | break 24 | 25 | def main(): 26 | 27 | shared1 = [] 28 | shared2 = [] 29 | 30 | t = threading.start_new_thread( mythread, (shared1, shared2) ) 31 | 32 | ticks = 0 33 | while len(shared1) + len(shared2) < 4: 34 | ticks += 1 35 | if ticks > 100000: ## do not hangup if there is a bug in the webworker 36 | break 37 | 38 | shared1.append( 'ZZZ' ) 39 | 40 | TestError( shared1[0] == 'hello' ) 41 | TestError( shared2[0] == 'world' ) 42 | TestError( shared2[1] == 'YYY' ) 43 | 44 | ticks = 0 45 | while ticks < 100000: 46 | ticks += 1 47 | -------------------------------------------------------------------------------- /regtests/threads/shared_list_coop.py: -------------------------------------------------------------------------------- 1 | ''' 2 | threads shared data 3 | ''' 4 | 5 | from time import time 6 | from time import sleep 7 | import threading 8 | 9 | 10 | def main(): 11 | if PYTHON=='PYTHONJS': 12 | pythonjs.configure( direct_operator='+' ) 13 | pass 14 | 15 | seq = [] 16 | w1 = threading.start_webworker( worker, (seq, 'A', 'B') ) 17 | w2 = threading.start_webworker( worker, (seq, 'B', 'A') ) 18 | 19 | sleep(1.0) 20 | 21 | TestError( 'A' in seq ) 22 | TestError( 'B' in seq ) 23 | 24 | 25 | with webworker: 26 | def worker(seq, a, b): 27 | for i in range(0, 10): 28 | seq.append( a ) 29 | if b in seq: 30 | break 31 | 32 | -------------------------------------------------------------------------------- /regtests/threads/shared_list_sleep.py: -------------------------------------------------------------------------------- 1 | """shared lists""" 2 | from time import sleep 3 | import threading 4 | 5 | @webworker( 'myworker.js' ) 6 | def mythread(a,b): 7 | i = 0 8 | while i < 10: 9 | a.append('o') 10 | i += 1 11 | #sleep(0.1) 12 | 13 | def main(): 14 | 15 | shared1 = [] 16 | shared2 = [] 17 | 18 | t = threading.start_new_thread( mythread, (shared1, shared2) ) 19 | i = 0 20 | while i < 10: 21 | shared1.append('x') 22 | i += 1 23 | sleep(0.2) 24 | 25 | while len(shared1) <= 20: 26 | shared1.append('0') 27 | sleep(0.1) 28 | 29 | TestError( len(shared1) == 20 ) 30 | -------------------------------------------------------------------------------- /regtests/threads/simple.py: -------------------------------------------------------------------------------- 1 | """simple thread""" 2 | 3 | import threading 4 | 5 | 6 | @webworker( 'myworker.js' ) 7 | def mythread(a): 8 | for i in range(100): 9 | a.append( i ) 10 | 11 | def main(): 12 | 13 | arr = [] 14 | t = threading.start_new_thread( mythread, (arr,) ) 15 | ticks = 0 16 | while len(arr) < 100: 17 | ticks += 1 18 | if ticks > 100000: ## do not hangup if there is a bug in the webworker 19 | break 20 | 21 | TestError( sum(arr) == 4950 ) 22 | -------------------------------------------------------------------------------- /regtests/typed/float32vec.py: -------------------------------------------------------------------------------- 1 | """simd float32vec""" 2 | 3 | def get_data(): 4 | return [1.9, 1.8, 1.7, 0.6, 0.99,0.88,0.77,0.66] 5 | def main(): 6 | ## the translator knows this is a float32vec because there are more than 4 elements 7 | x = y = z = w = 22/7 8 | a = numpy.array( [1.1, 1.2, 1.3, 0.4, x,y,z,w], dtype=numpy.float32 ) 9 | 10 | ## in this case the translator is not sure what the length of `u` is, so it defaults 11 | ## to using a float32vec. 12 | u = get_data() 13 | b = numpy.array( u, dtype=numpy.float32 ) 14 | 15 | c = a + b 16 | print(c) 17 | 18 | TestError( c[0]==3.0 ) 19 | TestError( c[1]==3.0 ) 20 | TestError( c[2]==3.0 ) 21 | TestError( c[3]==1.0 ) 22 | -------------------------------------------------------------------------------- /regtests/typed/float32x4.py: -------------------------------------------------------------------------------- 1 | """simd float32x4""" 2 | 3 | def main(): 4 | float32x4 a = numpy.array( [1.1, 1.2, 1.3, 0.4], dtype=numpy.float32 ) 5 | float32x4 b = numpy.array( [1.9, 1.8, 1.7, 0.6], dtype=numpy.float32 ) 6 | 7 | c = a + b 8 | print(c) 9 | 10 | if PYTHON == 'PYTHONJS': 11 | TestError( c.x==3.0 ) 12 | TestError( c.y==3.0 ) 13 | TestError( c.z==3.0 ) 14 | TestError( c.w==1.0 ) 15 | 16 | else: 17 | TestError( c[0]==3.0 ) 18 | TestError( c[1]==3.0 ) 19 | TestError( c[2]==3.0 ) 20 | TestError( c[3]==1.0 ) 21 | -------------------------------------------------------------------------------- /regtests/typed/int.py: -------------------------------------------------------------------------------- 1 | """int static type""" 2 | 3 | 4 | def main(): 5 | int x = 1 6 | y = x + x 7 | TestError( y==2 ) 8 | 9 | int z = 2 10 | w = z * 2 11 | TestError( w==4 ) 12 | 13 | w = z * 3 14 | TestError( w==6 ) 15 | 16 | w = z * 64 17 | TestError( w==128 ) 18 | 19 | w = z // 2 20 | TestError( w==1 ) 21 | 22 | z = 640 23 | w = z // 64 24 | TestError( w==10 ) -------------------------------------------------------------------------------- /regtests/typed/long.py: -------------------------------------------------------------------------------- 1 | """long static type""" 2 | 3 | def main(): 4 | long x = 65536 5 | long y = x * x 6 | long z = 4294967296 7 | TestError( y==z ) 8 | 9 | long a = z + z 10 | long b = 8589934592 11 | TestError( a==b ) 12 | 13 | TestError( y < b ) 14 | TestError( b > y ) 15 | 16 | TestError( y <= b ) 17 | TestError( b >= y ) 18 | 19 | ## TODO check why this fails when used with translator.py directly (bad indent bug) -------------------------------------------------------------------------------- /src/main.md: -------------------------------------------------------------------------------- 1 | Pythia Source Code 2 | ------------------- 3 | 4 | You need to be familiar with the Python AST module to understand how Pythia works. 5 | The best guide to Python AST is here: [Green Tree Snakes](https://greentreesnakes.readthedocs.org/en/latest/) 6 | 7 | Script Header 8 | ------------- 9 | ```python 10 | import os, sys 11 | import ast, itertools, json 12 | 13 | ``` 14 | 15 | First Stage Translator 16 | ---------------------- 17 | * [@import helper function](pythia/genmarkdown.md) converts folders and files into pythia markdown containers. 18 | * [@import pythia syntax pre-processor](pythia/typedpython.md) converts source into python AST compatible code. 19 | * [@import helper functions for AST processing](pythia/astutils.md) used mostly by the first stage of translation. 20 | * [@import helper codewriter class](pythia/codewriter.md) 21 | * [@import first stage of translator](pythia/intermediateform.md) 22 | 23 | Second Stage Translator 24 | ----------------------- 25 | * [@import multi-backend base class](pythia/generatorbase.md) 26 | * [@import javascript translator](pythia/jstranslator.md) 27 | * [@import golang translator](pythia/gotranslator.md) 28 | * [@import rust and c++](pythia/cpprustbase.md) shared base class logic. 29 | * [@import rust translator](pythia/rusttranslator.md) 30 | * [@import c++14 translator](pythia/cpptranslator.md) 31 | 32 | -------------------------------------------------------------------------------- /src/mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: PythiaSource 2 | repo_url: https://github.com/secureosv/pythia 3 | docs_dir: pythia 4 | theme: readthedocs 5 | 6 | pages: 7 | - Home: index.md 8 | - MultiBackendBaseClass: generatorbase.md 9 | - JavascriptTranslator: jstranslator.md 10 | - GolangTranslator: gotranslator.md 11 | - SharedRustC++Class: cpprustbase.md 12 | - C++Translator: cpptranslator.md 13 | - PreProcessor: typedpython.md 14 | - PreTranslator: intermediateform.md 15 | 16 | -------------------------------------------------------------------------------- /src/pythia/clikelang.md: -------------------------------------------------------------------------------- 1 | C Like Language 2 | -------------- 3 | simple syntax that is common to all C-like languages. 4 | [generatorbase.md](generatorbase.md) subclasses from this. 5 | 6 | ```python 7 | class CLikeLanguage: 8 | def visit_Not(self, node): 9 | return '!' 10 | 11 | def visit_USub(self, node): 12 | return '-' 13 | 14 | def visit_And(self, node): 15 | return ' && ' 16 | 17 | def visit_Or(self, node): 18 | return ' || ' 19 | 20 | 21 | def visit_Eq(self, node): 22 | return '==' 23 | 24 | def visit_NotEq(self, node): 25 | return '!=' 26 | 27 | def visit_Num(self, node): 28 | return str(node.n) 29 | 30 | def visit_Mult(self, node): 31 | return '*' 32 | 33 | def visit_Add(self, node): 34 | return '+' 35 | 36 | def visit_Sub(self, node): 37 | return '-' 38 | 39 | def visit_Div(self, node): 40 | return '/' 41 | 42 | def visit_Mod(self, node): 43 | return '%' 44 | 45 | def visit_Lt(self, node): 46 | return '<' 47 | 48 | def visit_Gt(self, node): 49 | return '>' 50 | 51 | def visit_GtE(self, node): 52 | return '>=' 53 | 54 | def visit_LtE(self, node): 55 | return '<=' 56 | 57 | def visit_LShift(self, node): 58 | return '<<' 59 | def visit_RShift(self, node): 60 | return '>>' 61 | def visit_BitXor(self, node): 62 | return '^' 63 | def visit_BitOr(self, node): 64 | return '|' 65 | def visit_BitAnd(self, node): 66 | return '&' 67 | 68 | 69 | ``` -------------------------------------------------------------------------------- /src/pythia/codewriter.md: -------------------------------------------------------------------------------- 1 | CodeWriter Class 2 | ---------------- 3 | makes it simple to build output source with formatting, insert before, and append lines. 4 | 5 | 6 | ```python 7 | import sys 8 | 9 | #if sys.version_info.major == 3: 10 | # import io 11 | # StringIO = io.StringIO 12 | #else: 13 | # from StringIO import StringIO 14 | 15 | #import io ## Python2.6+ 16 | #StringIO = io.StringIO 17 | 18 | class CodeWriter(object): 19 | 20 | def __init__(self): 21 | self.level = 0 22 | self.buffer = list() 23 | self.output = list() #StringIO() 24 | self.functions = [] 25 | 26 | def is_at_global_level(self): 27 | return self.level == 0 28 | 29 | def push(self): 30 | self.level += 1 31 | 32 | def pull(self): 33 | self.level -= 1 34 | 35 | def append(self, code): 36 | self.buffer.append(code) 37 | 38 | def write(self, code): 39 | for content in self.buffer: 40 | self._write(content) 41 | self.buffer = list() 42 | self._write(code) 43 | 44 | def _write(self, code): 45 | indentation = self.level * 4 * ' ' 46 | s = '%s%s\n' % (indentation, code) 47 | #self.output.write(s) 48 | #try: 49 | # s.encode('utf-8') 50 | #except: 51 | # raise RuntimeError(s) 52 | self.output.append( s ) 53 | 54 | def getvalue(self): 55 | #s = self.output.getvalue() 56 | #self.output = StringIO() 57 | s = '\n'.join(self.output) 58 | self.output = [] 59 | return s 60 | 61 | ``` -------------------------------------------------------------------------------- /src/pythia/cppheader.md: -------------------------------------------------------------------------------- 1 | C++ Header 2 | ---------- 3 | 4 | notes: new in c++11: algorithm, functional, thread, and chrono. 5 | includes typedefs for the standard types, like `f32`. 6 | 7 | note: OSX requires cmath, because std::pow and std::round is used in the builtins. 8 | 9 | ```python 10 | 11 | CPP_HEADER = """ 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | typedef long i64; 28 | typedef int i32; 29 | typedef double f64; 30 | typedef double float64; 31 | typedef float f32; 32 | typedef float float32; 33 | typedef const char* cstring; 34 | 35 | """ 36 | 37 | ``` -------------------------------------------------------------------------------- /src/pythia/index.md: -------------------------------------------------------------------------------- 1 | AST Translation 2 | --------------- 3 | 4 | Abstract Syntax Trees (AST) translate source code into objects you can traverse over 5 | and generate new code in the process. The `ast` module is built into Python, and is 6 | the standard way to translate python source code into another language. 7 | 8 | The best documentation on the Python `ast` module is [Green Tree Snakes](https://greentreesnakes.readthedocs.org/en/latest/) 9 | 10 | Pythia Source Code 11 | ------------------ 12 | Most of Pythia's source code is written in markdown files, and compiled by `pythia.py` which loads `main.md` 13 | -------------------------------------------------------------------------------- /src/pythia/jvm.md: -------------------------------------------------------------------------------- 1 | JavaVM JNI 2 | --------- 3 | 4 | Supports user code `import.jvm`, `jvm.namespace`, and `jvm(myclass)`. See example here: 5 | https://github.com/rusthon/Rusthon/blob/master/examples/java_giws.md 6 | 7 | Below `gen_jvm_header` generates the JNI header code required to implement rusthon's `jvm` api. 8 | TODO: fix JVM crash, originally it was working, but then something changed here (making it a global?) that makes it crash on exit. 9 | 10 | ```python 11 | 12 | 13 | JVM_HEADER = ''' 14 | #include 15 | 16 | JavaVM* __create_javavm__() { 17 | JavaVM* jvm = new JavaVM(); 18 | JNIEnv* env; 19 | JavaVMInitArgs args; 20 | JavaVMOption options[2]; 21 | args.version = JNI_VERSION_1_4; 22 | args.nOptions = 2; 23 | options[0].optionString = const_cast("-Djava.class.path=.%s"); 24 | options[1].optionString = const_cast("-Xcheck:jni"); 25 | args.options = options; 26 | args.ignoreUnrecognized = JNI_FALSE; 27 | JNI_CreateJavaVM(&jvm, (void **)&env, &args); 28 | return jvm; 29 | } 30 | 31 | static JavaVM* __javavm__ = __create_javavm__(); 32 | ''' 33 | def gen_jvm_header( jars ): 34 | if jars: 35 | a = ':' + ':'.join(jars) 36 | return JVM_HEADER %a 37 | else: 38 | return JVM_HEADER %'' 39 | 40 | ``` -------------------------------------------------------------------------------- /src/pythia/runtime/osv_builtins.py: -------------------------------------------------------------------------------- 1 | # OSv helper builtins 2 | # by Brett Hartshorn - copyright 2015 3 | # License: "New BSD" 4 | 5 | import osv/power.hh 6 | 7 | def __request_rebuild( reboots, sleep_seconds ): 8 | counter = 0 9 | 10 | try: 11 | print 'trying to readfile...' 12 | d = readfile( open('/reboot.log', 'r' ) ) 13 | print d 14 | #counter = int( d ) 15 | counter = inline('(int)(d[0])') - 48 16 | print counter 17 | print '--------' 18 | except: 19 | print 'first bootup...' 20 | 21 | counter += 1 22 | print counter 23 | #f = open('/reboot.log', 'w') 24 | #s=cstr(str(counter)) 25 | #f.close() 26 | 27 | if counter < reboots: 28 | print 'sleeping...' 29 | #sleep( sleep_seconds ) 30 | print 'rebooting...' 31 | osv::reboot() 32 | else: 33 | print 'vm shutdown...' 34 | osv::poweroff() -------------------------------------------------------------------------------- /src/pythia/runtime/pythonpythonjs.py: -------------------------------------------------------------------------------- 1 | # PythonJS Low Level Runtime 2 | # by Amirouche Boubekki and Brett Hartshorn - copyright 2013 3 | # License: "New BSD" 4 | 5 | __NULL_OBJECT__ = Object.create( null ) 6 | __WEBWORKER__ = False 7 | __NODEJS__ = False 8 | __BROWSER__ = False 9 | 10 | ## note browser and nodejs can both be true in the case of NodeWebkit 11 | if typeof(process) != 'undefined': ## TODO check if this is true inside a nodejs webworker 12 | __NODEJS__ = True 13 | if typeof(window) != 'undefined': 14 | __BROWSER__ = True 15 | if typeof(importScripts) == 'function': 16 | __WEBWORKER__ = True 17 | 18 | if not __NODEJS__ and not __WEBWORKER__: 19 | if typeof(HTMLDocument) == 'undefined': ## fix for older IE 20 | HTMLDocument = Document 21 | -------------------------------------------------------------------------------- /src/pythia/runtime/rust_builtins.py: -------------------------------------------------------------------------------- 1 | # Rusthon builtins 2 | # by Brett Hartshorn - copyright 2014 3 | # License: "New BSD" 4 | 5 | 6 | inline(""" 7 | 8 | /* Rusthon builtins */ 9 | 10 | type int = i64; 11 | type uint = u64; 12 | type string = &'static str; 13 | //type string = String; 14 | type __type__int = Vec; 15 | 16 | //fn range1<'caller>( lifetime : &'caller int, x : int ) -> &'caller Vec { 17 | fn range1( x : int ) -> Vec { 18 | let mut arr: Vec = Vec::with_capacity(x as usize); 19 | for i in 0u32..(x as u32) { arr.push(i as int); } 20 | return arr; 21 | } 22 | 23 | fn range2( start:int, end:int ) -> Vec { 24 | let mut arr: Vec = Vec::with_capacity( (end-start) as usize); 25 | for i in (start as u32)..(end as u32) { arr.push(i as int); } 26 | return arr; 27 | } 28 | 29 | fn ord( s:String ) -> int { 30 | return s.into_bytes()[0] as int; 31 | } 32 | 33 | fn __float__( s:String ) -> f32 { 34 | //return std::str::FromStr::from_str( s.as_slice() ).unwrap(); 35 | return 1.0; 36 | } 37 | 38 | fn __int__( n:String ) -> int { 39 | //return from_str::( n.as_slice() ).unwrap(); // TODO update to new API 40 | return 0; 41 | } 42 | 43 | fn round( n:f32, places:int ) -> f32 { 44 | let p = (10i64).pow( places as u32 ) as f32; 45 | return (n*p) / p; 46 | } 47 | 48 | /*end-builtins*/ 49 | """) 50 | --------------------------------------------------------------------------------