Monday, September 23, 2013

PythonScript - Operator Overloading

In the previous post I introduced Amirouche's awesome PythonScript. In this post I will explain how I modified the first-stage compiler to support simple operator overloading for attribute access "." and subscript "[]" operators. This allows you to write classes using the special methods: __getattr__ and __getitem__.

PythonScript compilation to JavaScript is a two stage process. The first stage parses the original Python code and converts it into a lower subset of Python that matches the semantics of JavaScript, so called: "PythonJS". The second stage takes PythonJS code (still valid Python) and converts it into JavaScript.
To add operator overloading only required changing the first stage of the compiler, see my commits: [1], [2]. The AST NodeVistor has been changed to keep track of: class names, special methods, and instances of the classes. The logic that inspects the AST and tracks class instances is too simple at the moment, and only understands: "a = SomeClass()". Then, as the rest of the AST is traversed, any references to "a" that use attribute access "." or subscript "[]" will be replaced with a PythonJS style function. In the example below, assume that class A has defined a special __getattr__ method.


a = A()
b = a.x + a.y


a = get_attribute(A, "__call__")();
b = __A___getattr__([a, "x"]) + __A___getattr__([a, "y"]);

1 comment:

  1. I will review your change as soon as possible and integrate them, getattr was something that I was missing, thanks.