Saturday, March 14, 2015

CPython inside Rusthon


Normally when mixing C++ with CPython you compile your C++ code and load it as an extension module. Sometimes, but less often CPython is embedded inside a C++ program. To interact with the Python interpreter from C++ requires writing verbose C-API calls all over the place. Rusthon simplifies using the C-API with special syntax ->, dedicated to PyObjects, that will generate the required PyObject_XXX calls for you.

simple tutorial: cpython_embed.md

The simple tutorial above shows you how to call methods on PyObject's and convert the return value to a C++ native type. Below shows how to use Go style channels to send PyObject's around to different threads created with spawn (c++11 std::thread).

multi-threaded GIL example: cpython_multithreaded.md

with gil:
    value = pyob->pymethod( cppob.cppmethod() as pyint ) as int
above example shows different calling styles for the PyObject and C++ object. note: as pyint becomes PyInt_FromLong from the CPython C-API, this is used to convert the return value of `cppmethod` to a PyObject.

Sunday, March 1, 2015

Literate Programming


Literate Programming, invented by Donald Knuth, makes programs human readable, secure and of higher quality.

Rusthon's multi-language markdown allows you use literate programming for mixing: python, c++, c, java, nim, rust, go, javascript and html. The transpiler/markdown-parser also acts as a compiler frontend to: gcc, g++, java, rustc, and go. This allows you to create multiple compiled executeables from a single markdown.

The source code of Rusthon itself is now mostly written in markdown, the main modules are:

Thursday, February 26, 2015

Nim and Java and C++


This single markdown file, nim_java.md mixes: Nim, Java, and C++. The output is a single executeable that includes the Nim code translated to C, the Nim C runtime, Rusthon code translated to C++, and links to the JVM. This allows you to call Nim and Java functions from Rusthon, and manage passing data between them. For how to load a JAR library, see here.

#backend:c++

import nim
import jvm
jvm.namespace('mymod')

@jvm
class PointSubclass( Point ):
 def __init__(self, x:int, y:int):
  self.set(x,y)

 def show(self):
  print self.getx()
  print self.gety()


def main():
 nim.main()
 p1 = jvm( PointSubclass(1,2) )
 p2 = jvm( PointSubclass(10,20) )
 p1.show()
 p2.show()
 p2.scale( nim_sum(100, 1000) )
 p2.show()

Mixing Nim, Java and C++ in a single binary would normally require some complex build, and running a wrapper generator like Nimrod-Java. But Nimrod-Java has not been updated in a year, and calling JNI through Nim is going to complicate threading.