pycow_compressor_source

Исходники компилятора py->js

from django.conf import settings
from pycow.pycow import PyCow

import ast

class PyCowWithQuasyImport(PyCow):
    """
    It is PyCow extension, wich enables of declaring external classes with import
    >>> a = Fx.Morph()
    will be compiled to javascript as
    >var a = Fx.Morph()
    but
    >>> from Fx import Morph 
    >>>#or 
    >>>import Fx.Morph
    >>> a = Fx.Morph()
    will be compiled as
    >var a = new Fx.Morph()
    """
    def __init__(self, *args, **kwargs):
        self.__imported_classes = []
        super(PyCowWithQuasyImport, self).__init__(*args, **kwargs)        

    @property
    def __write(self):
        return getattr(self,"_PyCow__write")


    def visit_Import(self, *args, **kwargs):
        i = args[0]
        self.__imported_classes.extend(map(lambda name:name.name, i.names)) 
        return super(PyCowWithQuasyImport, self).visit_Import(*args, **kwargs)

    def visit_ImportFrom(self, *args, **kwargs):
        i = args[0]
        self.__imported_classes.extend(map(lambda name:"%s.%s"%(i.module,name.name), i.names))         
        return super(PyCowWithQuasyImport, self).visit_ImportFrom(*args, **kwargs)

    def visit_Call(self, *args, **kwargs):
        node = args[0].func
        attrs = []
        id = None
        while hasattr(node,"attr"):
            attrs.insert(0,node.attr)
            node = node.value
            if hasattr(node,"id"):
                id = node.id
        if id and "%s.%s"%(id,".".join(attrs)) in self.__imported_classes:
            self.__write("new ") 
        return super(PyCowWithQuasyImport, self).visit_Call(*args, **kwargs)


def translate_string(input, indent = "\t", namespace = "", warnings = True):
    moo = PyCowWithQuasyImport(indent=indent, namespace=namespace, warnings=warnings)
    moo.visit(ast.parse(input, "(string)"))
    return moo.output()

def pycow(*args, **kwargs):
    try:
        return translate_string(args[0], warnings = False)
    except:
        if settings.DEBUG:
            raise
        else:
            return ""
Add post to: Delicious Reddit Slashdot Digg Technorati Google
(already: 1) Comment post

Comments

No comments for this post

Required. 30 chars of fewer.

Required.