code
stringlengths
1
1.72M
language
stringclasses
1 value
''' reference material: http://webreference.com/javascript/reference/core_ref/ http://webreference.com/programming/javascript/ http://mochikit.com/ http://www.mozilla.org/js/spidermonkey/ svn co http://codespeak.net/svn/kupu/trunk/ecmaunit ''' import py import os from pypy.rpython.rmodel import inputconst from pypy.rpython.typesystem import getfunctionptr from pypy.rpython.lltypesystem import lltype from pypy.rpython.ootypesystem import ootype from pypy.tool.udir import udir from pypy.translator.js.log import log from pypy.translator.js.asmgen import AsmGen from pypy.translator.js.jts import JTS from pypy.translator.js.opcodes import opcodes from pypy.translator.js.function import Function from pypy.translator.js.database import LowLevelDatabase from pypy.translator.oosupport.genoo import GenOO from heapq import heappush, heappop def _path_join(root_path, *paths): path = root_path for p in paths: path = os.path.join(path, p) return path class Tee(object): def __init__(self, *args): self.outfiles = args def write(self, s): for outfile in self.outfiles: outfile.write(s) def close(self): for outfile in self.outfiles: if outfile is not sys.stdout: outfile.close() class JS(GenOO): TypeSystem = JTS opcodes = opcodes Function = Function Database = LowLevelDatabase def __init__(self, translator, functions=[], stackless=False, compress=False, \ logging=False, use_debug=False): if not isinstance(functions, list): functions = [functions] GenOO.__init__(self, udir, translator, None) pending_graphs = [translator.annotator.bookkeeper.getdesc(f).cachedgraph(None) for f in functions ] for graph in pending_graphs: self.db.pending_function(graph) self.db.translator = translator self.use_debug = use_debug self.assembly_name = self.translator.graphs[0].name self.tmpfile = udir.join(self.assembly_name + '.js') def gen_pendings(self): while self.db._pending_nodes: node = self.db._pending_nodes.pop() to_render = [] nparent = node while nparent.order != 0: nparent = nparent.parent to_render.append(nparent) to_render.reverse() for i in to_render: i.render(self.ilasm) node.render(self.ilasm) def generate_communication_proxy(self): """ Render necessary stuff aroundc communication proxies """ for proxy in self.db.proxies: proxy.render(self.ilasm) def create_assembler(self): out = self.tmpfile.open('w') return AsmGen(out, self.assembly_name) def generate_source(self): self.ilasm = self.create_assembler() self.fix_names() self.gen_entrypoint() while self.db._pending_nodes: self.gen_pendings() self.db.gen_constants(self.ilasm, self.db._pending_nodes) self.ilasm.close() assert len(self.ilasm.right_hand) == 0 return self.tmpfile.strpath def write_source(self): # write down additional functions # FIXME: when used with browser option it should probably # not be used as inlined, rather another script to load # this is just workaround self.generate_source() data = self.tmpfile.open().read() src_filename = _path_join(os.path.dirname(__file__), 'jssrc', 'misc.js') f = self.tmpfile.open("w") s = open(src_filename).read() f.write(s) self.ilasm = AsmGen(f, self.assembly_name ) self.generate_communication_proxy() f.write(data) f.close() self.filename = self.tmpfile return self.tmpfile
Python
"""Contains high level javascript compilation function """ import autopath #from pypy.translator.js.test.runtest import compile_function #from pypy.translator.translator import TranslationContext from pypy.translator.driver import TranslationDriver from pypy.translator.js.js import JS from pypy.tool.error import AnnotatorError, FlowingError, debug from pypy.rlib.nonconst import NonConstant from pypy.annotation.policy import AnnotatorPolicy from py.compat import optparse from pypy.config.config import OptionDescription, BoolOption, StrOption from pypy.config.config import Config, to_optparse import py import sys js_optiondescr = OptionDescription("jscompile", "", [ BoolOption("view", "View flow graphs", default=False, cmdline="--view"), BoolOption("use_pdb", "Use debugger", default=False, cmdline="--pdb"), StrOption("output", "File to save results (default output.js)", default="output.js", cmdline="--output")]) class FunctionNotFound(Exception): pass class BadSignature(Exception): pass class JsPolicy(AnnotatorPolicy): allow_someobjects = False def get_args(func_data): l = [] for i in xrange(func_data.func_code.co_argcount): l.append("NonConstant(%s)" % repr(func_data.func_defaults[i])) return ",".join(l) def get_arg_names(func_data): return ",".join(func_data.func_code.co_varnames\ [:func_data.func_code.co_argcount]) def rpython2javascript_main(argv, jsconfig): if len(argv) == 0: print "usage: module <function_names>" sys.exit(0) module_name = argv[0] if not module_name.endswith('.py'): module_name += ".py" mod = py.path.local(module_name).pyimport() if len(argv) == 1: function_names = [] for function_name in dir(mod): function = getattr(mod, function_name) if callable(function) and getattr(function, '_client', False): function_names.append( function_name ) if not function_names: print "Cannot find any function with _client=True in %s"\ % module_name sys.exit(1) else: function_names = argv[1:] source = rpython2javascript(mod, function_names, jsconfig=jsconfig) if not source: print "Exiting, source not generated" sys.exit(1) open(jsconfig.output, "w").write(source) print "Written file %s" % jsconfig.output # some strange function source source_ssf_base = """ import %(module_name)s from pypy.translator.js.helper import __show_traceback from pypy.rlib.nonconst import NonConstant as NonConst %(function_defs)s def some_strange_function_which_will_never_be_called(): %(functions)s """ wrapped_function_def_base = """ def %(fun_name)s(%(arg_names)s): try: traceback_handler.enter(NonConst("entrypoint"), NonConst("()"), NonConst(""), NonConst(0)) %(module_name)s.%(fun_name)s(%(arg_names)s) traceback_handler.leave(NonConst("entrypoint")) except Exception, e: new_tb = traceback_handler.tb[:] __show_traceback(new_tb, str(e)) %(fun_name)s.explicit_traceback = True """ function_base = "%(module_name)s.%(fun_name)s(%(args)s)" wrapped_function_base = "%(fun_name)s(%(args)s)" def get_source_ssf(mod, module_name, function_names): #source_ssf = "\n".join(["import %s" % module_name, "def some_strange_function_which_will_never_be_called():"] + [" "+\ # module_name+"."+fun_name+get_args(mod.__dict__[fun_name]) for fun_name in function_names]) function_list = [] function_def_list = [] for fun_name in function_names: args = get_args(mod.__dict__[fun_name]) arg_names = get_arg_names(mod.__dict__[fun_name]) base = function_base function_list.append(py.code.Source(base % locals())) function_defs = "\n\n".join([str(i) for i in function_def_list]) functions = "\n".join([str(i.indent()) for i in function_list]) retval = source_ssf_base % locals() print retval return retval def rpython2javascript(mod, function_names, jsconfig=None, use_pdb=True): if isinstance(function_names, str): function_names = [function_names] # avoid confusion if mod is None: # this means actual module, which is quite hairy to get in python, # so we cheat import sys mod = sys.modules[sys._getframe(1).f_globals['__name__']] if jsconfig is None: jsconfig = Config(js_optiondescr) if use_pdb: jsconfig.use_pdb = True module_name = mod.__name__ if not function_names and 'main' in mod.__dict__: function_names.append('main') for func_name in function_names: if func_name not in mod.__dict__: raise FunctionNotFound("function %r was not found in module %r" % (func_name, module_name)) func_code = mod.__dict__[func_name] if func_code.func_defaults: lgt = len(func_code.func_defaults) else: lgt = 0 if func_code.func_code.co_argcount > 0 and func_code.func_code. \ co_argcount != lgt: raise BadSignature("Function %s does not have default arguments" % func_name) source_ssf = get_source_ssf(mod, module_name, function_names) exec(source_ssf) in globals() # now we gonna just cut off not needed function # XXX: Really do that #options = optparse.Values(defaults=DEFAULT_OPTIONS) from pypy.config.pypyoption import get_pypy_config config = get_pypy_config(translating=True) driver = TranslationDriver(config=config) try: driver.setup(some_strange_function_which_will_never_be_called, [], policy = JsPolicy()) driver.proceed(["compile_js"]) if jsconfig.view: driver.translator.view() return driver.gen.tmpfile.open().read() # XXX: Add some possibility to write down selected file except Exception, e: # do something nice with it debug(driver, use_pdb)
Python
try: set except NameError: from sets import Set as set from pypy.objspace.flow import model as flowmodel from pypy.rpython.lltypesystem.lltype import Signed, Unsigned, Void, Bool, Float from pypy.rpython.lltypesystem.lltype import SignedLongLong, UnsignedLongLong from pypy.rpython.ootypesystem import ootype from pypy.translator.oosupport.metavm import Generator,InstructionList from pypy.translator.oosupport import function from pypy.translator.js.log import log from types import FunctionType import re class BaseGenerator(object): def load(self, v): if isinstance(v, flowmodel.Variable): if v.name in self.argset: selftype, selfname = self.args[0] if self.is_method and v.name == selfname: self.ilasm.load_self() else: self.ilasm.load_arg(v) else: self.ilasm.load_local(v) elif isinstance(v, flowmodel.Constant): self.db.load_const(v.concretetype, v.value, self.ilasm) elif isinstance(v, str): self.ilasm.load_const("'" + v + "'") else: assert False def store(self, v): assert isinstance(v, flowmodel.Variable) if v.concretetype is not Void: self.ilasm.store_local(v) else: self.ilasm.store_void() def change_name(self, name, to_name): self.ilasm.change_name(name, to_name) def add_comment(self, text): pass def function_signature(self, graph): return self.cts.graph_to_signature(graph, False) def class_name(self, ooinstance): return ooinstance._name def emit(self, instr, *args): self.ilasm.emit(instr, *args) def call_graph(self, graph): self.db.pending_function(graph) func_sig = self.function_signature(graph) self.ilasm.call(func_sig) def call_external(self, name, args): self.ilasm.call((name, args)) #def call_signature(self, signature): # self.ilasm.call(signature) def cast_to(self, lltype): cts_type = self.cts.lltype_to_cts(lltype, False) self.ilasm.castclass(cts_type) def new(self, obj): self.ilasm.new(self.cts.obj_name(obj)) def set_field(self, obj, name): self.ilasm.set_field(obj, name) #self.ilasm.set_field(self.field_name(obj,name)) def get_field(self, useless_stuff, name): self.ilasm.get_field(name) def call_method(self, obj, name): func_name, signature = self.cts.method_signature(obj, name) self.ilasm.call_method(obj, name, signature) def call_external_method(self, name, arg_len): self.ilasm.call_method(None, name, [0]*arg_len) def instantiate(self): self.ilasm.runtimenew() def downcast(self, TYPE): pass def load_special(self, v): # special case for loading value # when setting builtin field we need to load function instead of None # FIXME: we cheat here if isinstance(v, flowmodel.Constant) and v.concretetype is ootype.Void and isinstance(v.value, FunctionType): graph = self.db.translator.annotator.bookkeeper.getdesc(v.value).cachedgraph(None) self.db.pending_function(graph) name = graph.name self.ilasm.load_str(name) else: self.load(v) def cast_function(self, name, num): self.ilasm.cast_function(name, num) def prefix_op(self, st): self.ilasm.prefix_op(st) def load_str(self, s): self.ilasm.load_str(s) def load_void(self): self.ilasm.load_void() def list_setitem(self, base_obj, item, val): self.load(base_obj) self.load(val) self.load(item) self.ilasm.list_setitem() def list_getitem(self, base_obj, item): self.load(base_obj) self.load(item) self.ilasm.list_getitem() def push_primitive_constant(self, TYPE, value): self.db.load_const(TYPE, value, self.ilasm) def branch_unconditionally(self, target_label): self.ilasm.jump_block(self.block_map[target_label]) def branch_conditionally(self, exitcase, target_label): self.ilasm.branch_if(exitcase) self.ilasm.jump_block(self.block_map[target_label]) self.ilasm.close_branch() class Function(function.Function, BaseGenerator): def __init__(self, db, graph, name=None, is_method=False, is_entrypoint=False, _class=None): self._class = _class super(Function, self).__init__(db, graph, name, is_method, is_entrypoint) self._set_args() self._set_locals() self.order = 0 self.name = name or self.db.get_uniquename(self.graph, self.graph.name) def _setup_link(self, link, is_exc_link = False): target = link.target for to_load, to_store in zip(link.args, target.inputargs): if to_load.concretetype is not Void: if is_exc_link and isinstance(to_load, flowmodel.Variable) and re.match("last_exc_value", to_load.name): self.ilasm.load_str("exc") else: self.load(to_load) self.store(to_store) def _create_generator(self, ilasm): return self def begin_render(self): block_map = {} for blocknum, block in enumerate(self.graph.iterblocks()): block_map[self._get_block_name(block)] = blocknum self.block_map = block_map if self.is_method: args = self.args[1:] # self is implicit else: args = self.args if self.is_method: self.ilasm.begin_method(self.name, self._class, [i[1] for i in args]) else: self.ilasm.begin_function(self.name, args) self.ilasm.set_locals(",".join([i[1] for i in self.locals])) self.ilasm.begin_for() def render_return_block(self, block): return_var = block.inputargs[0] if return_var.concretetype is not Void: self.load(return_var) self.ilasm.ret() else: self.ilasm.load_void() self.ilasm.ret() def end_render(self): self.ilasm.end_for() self.ilasm.end_function() def render_raise_block(self, block): self.ilasm.throw(block.inputargs[1]) def end_try(self, target_label): self.ilasm.jump_block(self.block_map[target_label]) self.ilasm.catch() #self.ilasm.close_branch() def record_ll_meta_exc(self, ll_meta_exc): pass def begin_catch(self, llexitcase): real_name = self.cts.lltype_to_cts(llexitcase._inst.class_._INSTANCE) s = "isinstanceof(exc, %s)"%real_name self.ilasm.branch_if_string(s) def end_catch(self, target_label): """ Ends the catch block, and branchs to the given target_label as the last item in the catch block """ self.ilasm.close_branch() def store_exception_and_link(self, link): self._setup_link(link, True) self.ilasm.jump_block(self.block_map[self._get_block_name(link.target)]) def after_except_block(self): #self.ilasm.close_branch() self.ilasm.throw_real("exc") self.ilasm.close_branch() def set_label(self, label): self.ilasm.write_case(self.block_map[label]) #self.ilasm.label(label) def begin_try(self): self.ilasm.begin_try() def clean_stack(self): self.ilasm.clean_stack()
Python
import py Option = py.test.config.Option option = py.test.config.addoptions("pypy-ojs options", Option('--use-browser', action="store", dest="browser", type="string", default="", help="run Javascript tests in your default browser"), Option('--tg', action="store_true", dest="tg", default=False, help="Use TurboGears machinery for testing") )
Python
""" backend generator routines """ from pypy.translator.js.log import log from pypy.objspace.flow.model import Variable from StringIO import StringIO class CodeGenerator(object): def __init__(self, out, indentstep = 4, startblock = '{', endblock = '}'): self._out = out self._indent = 0 self._bol = True # begin of line self._indentstep = indentstep self._startblock = startblock self._endblock = endblock def write(self, s, indent = 0): indent = self._indent + (indent * self._indentstep) if self._bol: self._out.write(' ' * indent) self._out.write(s) self._bol = (s and s[-1] == '\n') def writeline(self, s=''): self.write(s) self.write('\n') def openblock(self): self.writeline(self._startblock) self._indent += self._indentstep def closeblock(self): self._indent -= self._indentstep self.writeline(self._endblock) class Queue(object): def __init__(self, l, subst_table): self.l = l[:] self.subst_table = subst_table def pop(self): el = self.l.pop() return self.subst_table.get(el, el) def __getattr__(self,attr): return getattr(self.l, attr) def __len__(self): return len(self.l) def __nonzero__(self): return len(self.l) > 0 def empty(self): self.l = [] def __repr__(self): return "<Queue %s>" % (repr(self.l),) class AsmGen(object): """ JS 'assembler' generator routines """ def __init__(self, outfile, name): self.outfile = outfile self.name = name self.subst_table = {} self.right_hand = Queue([], self.subst_table) self.codegenerator = CodeGenerator(outfile) def close(self): self.outfile.close() def begin_function(self, name, arglist): args = ",".join([i[1] for i in arglist]) self.codegenerator.write("function %s (%s) "%(name, args)) self.codegenerator.openblock() def begin_method(self, name, _class, arglist): args = ",".join(arglist) self.codegenerator.write("%s.prototype.%s = function (%s)"%(_class, name, args)) self.codegenerator.openblock() def end_function(self): self.codegenerator.closeblock() self.codegenerator.writeline("") def load_arg(self, v): self.right_hand.append(v.name) def store_local(self, v): self.store_name(v.name) def store_name(self, name): name = self.subst_table.get(name, name) element = self.right_hand.pop() if element != name: self.codegenerator.writeline("%s = %s;"%(name, element)) def load_local(self, v): self.right_hand.append(v.name) def load_const(self, v): self.right_hand.append(v) def ret(self): self.codegenerator.writeline("return ( %s );"%self.right_hand.pop()) def emit(self, opcode, *args): v1 = self.right_hand.pop() v2 = self.right_hand.pop() self.right_hand.append("(%s%s%s)"%(v2, opcode, v1)) def call(self, func): func_name, args = func l = [self.right_hand.pop() for i in xrange(len(args))] l.reverse() real_args = ",".join(l) self.right_hand.append("%s ( %s )" % (func_name, real_args)) def branch_if(self, exitcase): def mapping(exitc): if exitc in ['True', 'False']: return exitc.lower() return exitc arg = self.right_hand.pop() if hasattr(arg,'name'): arg_name = self.subst_table.get(arg.name, arg.name) else: arg_name = arg self.branch_if_string("%s == %s"%(arg_name, mapping(str(exitcase)))) def branch_if_string(self, arg): self.codegenerator.writeline("if (%s)"%arg) self.codegenerator.openblock() def branch_elsif_string(self, arg): self.codegenerator.closeblock() self.codegenerator.writeline("else if (%s)"%arg) self.codegenerator.openblock() def branch_elsif(self, arg, exitcase): self.codegenerator.closeblock() self.branch_if(arg, exitcase, "else if") def branch_while(self, arg, exitcase): def mapping(exitc): if exitc in ['True', 'False']: return exitc.lower() return exitc arg_name = self.subst_table.get(arg.name, arg.name) self.codegenerator.write("while ( %s == %s )"%(arg_name, mapping(str(exitcase)))) self.codegenerator.openblock() def branch_while_true(self): self.codegenerator.write("while (true)") self.codegenerator.openblock() def branch_else(self): self.right_hand.pop() self.codegenerator.closeblock() self.codegenerator.write("else") self.codegenerator.openblock() def close_branch(self): self.codegenerator.closeblock() def label(self, *args): self.codegenerator.openblock() def change_name(self, from_name, to_name): if isinstance(from_name,Variable) and isinstance(to_name,Variable): self.subst_table[from_name.name] = to_name.name def cast_function(self, name, num): # FIXME: redundancy with call args = [self.right_hand.pop() for i in xrange(num)] args.reverse() arg_list = ",".join(args) self.right_hand.append("%s ( %s )"%(name, arg_list)) def prefix_op(self, st): self.right_hand.append("%s%s"%(st, self.right_hand.pop())) #def field(self, f_name, cts_type): # pass def set_locals(self, loc_string): if loc_string != '': self.codegenerator.writeline("var %s;"%loc_string) def set_static_field(self, _type, namespace, _class, varname): self.codegenerator.writeline("%s.prototype.%s = %s;"%(_class, varname, self.right_hand.pop())) def set_field(self, useless_parameter, name): v = self.right_hand.pop() self.codegenerator.writeline("%s.%s = %s;"%(self.right_hand.pop(), name, v)) #self.right_hand.append(None) def call_method(self, obj, name, signature): l = [self.right_hand.pop() for i in signature] l.reverse() args = ",".join(l) self.right_hand.append("%s.%s(%s)"%(self.right_hand.pop(), name, args)) def get_field(self, name): self.right_hand.append("%s.%s"%(self.right_hand.pop(), name)) def new(self, obj): #log("New: %r"%obj) self.right_hand.append("new %s()"%obj) def runtimenew(self): self.right_hand.append("new %s()" % self.right_hand.pop()) def load_self(self): self.right_hand.append("this") def store_void(self): if not len(self.right_hand): return v = self.right_hand.pop() if v is not None and v.find('('): self.codegenerator.writeline(v+";") def begin_consts(self, name): # load consts, maybe more try to use stack-based features? self.codegenerator.writeline("%s = {};"%name) def new_obj(self): self.right_hand.append("{}") def new_list(self): self.right_hand.append("[]") # FIXME: will refactor later load_str = load_const def list_setitem(self): item = self.right_hand.pop() value = self.right_hand.pop() lst = self.right_hand.pop() self.right_hand.append("%s[%s]=%s"%(lst, item, value)) def list_getitem(self): item = self.right_hand.pop() lst = self.right_hand.pop() self.right_hand.append("%s[%s]"%(lst, item)) def load_void(self): self.right_hand.append("undefined") def load_void_obj(self): self.right_hand.append("{}") def begin_try(self): self.codegenerator.write("try ") self.codegenerator.openblock() def catch(self): self.codegenerator.closeblock() self.codegenerator.write("catch (exc)") self.codegenerator.openblock() def begin_for(self): self.codegenerator.writeline("var block = 0;") self.codegenerator.write("for(;;)") self.codegenerator.openblock() self.codegenerator.write("switch(block)") self.codegenerator.openblock() def write_case(self, num): self.codegenerator.writeline("case %d:"%num) def jump_block(self, num): self.codegenerator.writeline("block = %d;"%num) self.codegenerator.writeline("break;") def end_for(self): self.codegenerator.closeblock() self.codegenerator.closeblock() def inherits(self, subclass_name, parent_name): self.codegenerator.writeline("inherits(%s,%s);"%(subclass_name, parent_name)) def throw(self, var): self.throw_real(var.name) def throw_real(self, s): self.codegenerator.writeline("throw(%s);"%s) def clean_stack(self): self.right_hand.empty()
Python
#!/usr/bin/env python """ In this example I'll show how to manipulate DOM tree from inside RPython code Note that this is low-level API to manipulate it, which might be suitable if you don't like boilerplate on top. There is ongoing effort to provide API of somewhat higher level, which will be way easier to manipulate. """ from pypy.translator.js.lib import server from pypy.translator.js.main import rpython2javascript from pypy.translator.js.modules.dom import document # dom manipulating module HTML = ''' <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body> <table id="atable"> <tr><td>A row</td></tr> </table> <a href="#" onclick="addrow()">Add row</a> <a href="#" onclick="delrow()">Del row</a> </body> </html> ''' # these are exposed functions def addrow(): # we need to call a helper, similiar to document in JS tr = document.createElement("tr") td = document.createElement("td") td.appendChild(document.createTextNode("A row")) tr.appendChild(td) document.getElementById("atable").appendChild(tr) def delrow(): table = document.getElementById("atable") # note -1 working here like in python, this is last element in list table.removeChild(table.childNodes[-1]) class Handler(server.TestHandler): def index(self): return HTML index.exposed = True def source_js(self): return "text/javascript", rpython2javascript(None, ["addrow", "delrow"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ In this example, we'll show how to add javascript to our simple server from previous example """ from pypy.translator.js.lib import server import sys # here we have virtual script "source.js" which we generate # on-the-fly when requested HTML = """ <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body onload="show()"> </body> </html> """ from pypy.translator.js.main import rpython2javascript # here we import rpython -> javascript conversion utility from pypy.translator.js.modules import dom # and here we import functions from modules that we want to use # this is function which will be translated into javascript, # we can put it in a different module if we like so def show(): dom.alert("Alert") class Handler(server.TestHandler): def index(self): return HTML index.exposed = True # here we generate javascript, this will be accessed when # asked for source.js def source_js(self): # this returns content-type (if not text/html) # and generated javascript code # None as argument means current module, while "show" is the # name of function to be exported (under same name) return "text/javascript", rpython2javascript(None, ["show"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ In this example I'll show how to manipulate DOM tree from inside RPython code Note that this is low-level API to manipulate it, which might be suitable if you don't like boilerplate on top. There is ongoing effort to provide API of somewhat higher level, which will be way easier to manipulate. """ from pypy.translator.js.lib import server from pypy.translator.js.main import rpython2javascript from pypy.translator.js.modules.dom import document # dom manipulating module HTML = ''' <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body> <table id="atable"> <tr><td>A row</td></tr> </table> <a href="#" onclick="addrow()">Add row</a> <a href="#" onclick="delrow()">Del row</a> </body> </html> ''' # these are exposed functions def addrow(): # we need to call a helper, similiar to document in JS tr = document.createElement("tr") td = document.createElement("td") td.appendChild(document.createTextNode("A row")) tr.appendChild(td) document.getElementById("atable").appendChild(tr) def delrow(): table = document.getElementById("atable") # note -1 working here like in python, this is last element in list table.removeChild(table.childNodes[-1]) class Handler(server.TestHandler): def index(self): return HTML index.exposed = True def source_js(self): return "text/javascript", rpython2javascript(None, ["addrow", "delrow"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ In this example, we'll show how to add javascript to our simple server from previous example """ from pypy.translator.js.lib import server import sys # here we have virtual script "source.js" which we generate # on-the-fly when requested HTML = """ <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body onload="show()"> </body> </html> """ from pypy.translator.js.main import rpython2javascript # here we import rpython -> javascript conversion utility from pypy.translator.js.modules import dom # and here we import functions from modules that we want to use # this is function which will be translated into javascript, # we can put it in a different module if we like so def show(): dom.alert("Alert") class Handler(server.TestHandler): def index(self): return HTML index.exposed = True # here we generate javascript, this will be accessed when # asked for source.js def source_js(self): # this returns content-type (if not text/html) # and generated javascript code # None as argument means current module, while "show" is the # name of function to be exported (under same name) return "text/javascript", rpython2javascript(None, ["show"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ This is simple all-in-one self-containing server, which just shows almost-empty HTML page """ # here we import server, which is derivative of # BaseHTTPServer from python standard library from pypy.translator.js.lib import server # We create handler, which will handle all our requests class Handler(server.TestHandler): def index(self): # provide some html contents return "<html><head></head><body><p>Something</p></body></html>" # this line is necessary to make server show something, # otherwise method is considered private-only index.exposed = True if __name__ == '__main__': # let's start our server, # this will create running server instance on port 8000 by default, # which will run until we press Control-C server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ This is simple all-in-one self-containing server, which just shows almost-empty HTML page """ # here we import server, which is derivative of # BaseHTTPServer from python standard library from pypy.translator.js.lib import server # We create handler, which will handle all our requests class Handler(server.TestHandler): def index(self): # provide some html contents return "<html><head></head><body><p>Something</p></body></html>" # this line is necessary to make server show something, # otherwise method is considered private-only index.exposed = True if __name__ == '__main__': # let's start our server, # this will create running server instance on port 8000 by default, # which will run until we press Control-C server.create_server(handler=Handler).serve_forever()
Python
""" Communication proxy rendering """ from pypy.objspace.flow.model import Variable, Constant from pypy.rpython.ootypesystem.bltregistry import ArgDesc GET_METHOD_BODY = """ %(class)s.prototype.%(method)s = function ( %(args)s ) { var data,str; var x = new XMLHttpRequest(); data = %(data)s; str = "" for(i in data) { if (data[i]) { if (str.length == 0) { str += "?"; } else { str += "&"; } str += escape(i) + "=" + escape(data[i].toString()); } } //logDebug('%(call)s'+str); x.open("GET", '%(call)s' + str, true); x.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); x.onreadystatechange = function () { %(real_callback)s(x, callback) }; //x.setRequestHeader("Connection", "close"); //x.send(data); x.send(null); } """ POST_METHOD_BODY = """ %(class)s.prototype.%(method)s = function ( %(args)s ) { var data,str; var x = new XMLHttpRequest(); data = %(data)s; str = "" for(i in data) { if (data[i]) { if (str.length != 0) { str += "&"; } str += escape(i) + "=" + escape(data[i].toString()); } } //logDebug('%(call)s'+str); x.open("POST", '%(call)s', true); //x.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); x.onreadystatechange = function () { %(real_callback)s(x, callback) }; //x.setRequestHeader("Connection", "close"); //logDebug(str); x.send(str); //x.send(null); } """ CALLBACK_BODY = """ function %(real_callback)s (x, cb) { var d; if (x.readyState == 4) { if (x.responseText) { eval ( "d = " + x.responseText ); cb(d); } else { cb({}); } } } """ CALLBACK_XML_BODY = """ function %(real_callback)s (x, cb) { if (x.readyState == 4) { if (x.responseXML) { cb(x.responseXML.documentElement); } else { cb(null); } } } """ MOCHIKIT_BODY = """ %(class)s.prototype.%(method)s = function ( %(args)s ) { var data,str; data = %(data)s; loadJSONDoc('%(call)s', data).addCallback(callback); } """ USE_MOCHIKIT = True # FIXME: some option? class XmlHttp(object): """ Class for rendering xmlhttp request communication over normal js code """ def __init__(self, ext_obj, name, use_xml=False, base_url="", method="GET"): self.ext_obj = ext_obj self.name = name self.use_xml = use_xml self.base_url = base_url obj = self.ext_obj._TYPE._class_ if not base_url and hasattr(obj, '_render_base_path'): self.base_url = obj._render_base_path self.method = method def render(self, ilasm): self.render_body(ilasm) for method_name, method in self.ext_obj._TYPE._class_._methods.iteritems(): self.render_method(method_name, method, ilasm) def render_body(self, ilasm): ilasm.begin_function(self.name, []) ilasm.end_function() def render_method(self, method_name, method, ilasm): args, retval = method.args, method.retval.name if len(args) == 0 or args[-1].name != 'callback': args.append(ArgDesc('callback', lambda : None)) real_args = list(arg.name for arg in args) # FIXME: dirty JS here data = "{%s}" % ",".join(["'%s':%s" % (i,i) for i in real_args if i != 'callback']) real_callback = Variable("callback").name if len(self.base_url) > 0 and not self.base_url.endswith("/"): url = self.base_url + "/" +method_name else: url = self.base_url + method_name METHOD_BODY = globals()[self.method + "_METHOD_BODY"] if USE_MOCHIKIT and self.use_xml: assert 0, "Cannot use mochikit and xml requests at the same time" if USE_MOCHIKIT and self.method == "POST": assert 0, "Cannot use mochikit with POST method" if USE_MOCHIKIT: ilasm.codegenerator.write(MOCHIKIT_BODY % {'class':self.name, 'method':method_name,\ 'args':','.join(real_args), 'data':data, 'call':url}) else: if not self.use_xml: callback_body = CALLBACK_BODY else: callback_body = CALLBACK_XML_BODY ilasm.codegenerator.write(callback_body % {'real_callback':real_callback}) ilasm.codegenerator.write(METHOD_BODY % {'class':self.name, 'method':method_name,\ 'args':",".join(real_args), 'data':data, 'call':url,\ 'real_callback':real_callback})
Python
import py from pypy.tool.ansi_print import ansi_log log = py.log.Producer("js") py.log.setconsumer("js", ansi_log)
Python
""" JavaScript type system """ from pypy.rpython.ootypesystem import ootype from pypy.rpython.lltypesystem import lltype from pypy.translator.cli import oopspec from pypy.rpython.lltypesystem.lltype import Signed, Unsigned, Void, Bool, Float from pypy.rpython.lltypesystem.lltype import SignedLongLong, UnsignedLongLong, Primitive from pypy.rpython.lltypesystem.lltype import Char, UniChar from pypy.rpython.ootypesystem.ootype import String, _string, List, StaticMethod from pypy.rlib.objectmodel import Symbolic from pypy.translator.js.log import log from types import FunctionType from pypy.rpython.extfunc import is_external try: set except NameError: from sets import Set as set class JTS(object): """ Class implementing JavaScript type system calls with mapping similiar to cts """ def __init__(self, db): self.db = db #def __class(self, name): # return name.replace(".", "_") def escape_name(self, name): return name.replace('.', '_') def llvar_to_cts(self, var): return 'var ', var.name def lltype_to_cts(self, t): if isinstance(t, ootype.Instance): self.db.pending_class(t) return self.escape_name(t._name) elif isinstance(t, ootype.List): return "Array" elif isinstance(t, lltype.Primitive): return "var" elif isinstance(t, ootype.Record): return "Object" elif isinstance(t, ootype.String.__class__): return '""' elif isinstance(t, ootype.Dict): return "Object" elif isinstance(t, ootype.DictItemsIterator): return "Object" elif t is ootype.StringBuilder: return "StringBuilder" #return "var" raise NotImplementedError("Type %r" % (t,)) def graph_to_signature(self, graph, is_method = False, func_name = None): func_name = func_name or self.db.get_uniquename(graph,graph.name) args = [arg for arg in graph.getargs() if arg.concretetype is not ootype.Void] if is_method: args = args[1:] return func_name,args def method_signature(self, obj, name): # TODO: use callvirt only when strictly necessary if isinstance(obj, ootype.Instance): owner, meth = obj._lookup(name) METH = meth._TYPE return obj._name, METH.ARGS elif isinstance(obj, ootype.BuiltinType): meth = oopspec.get_method(obj, name) class_name = self.lltype_to_cts(obj) return class_name,meth.ARGS else: assert False def obj_name(self, obj): return self.lltype_to_cts(obj) def primitive_repr(self, _type, v): if _type is Bool: if v == False: val = 'false' else: val = 'true' elif _type is Void: val = 'undefined' elif isinstance(_type,String.__class__): val = '%r'%v._str elif isinstance(_type,List): # FIXME: It's not ok to use always empty list val = "[]" elif isinstance(_type,StaticMethod): if hasattr(v, 'graph') and not is_external(v): self.db.pending_function(v.graph) else: self.db.pending_abstract_function(v) val = v._name val = val.replace('.', '_') if val == '?': val = 'undefined' elif _type is UniChar or _type is Char: #log("Constant %r"%v) s = repr(v) if s.startswith('u'): s = s[1:] if s != "'\''": s.replace("'", '"') val = s elif isinstance(v, Symbolic): val = v.expr elif isinstance(_type, Primitive): #log("Type: %r"%_type) val = str(v) else: assert False, "Unknown constant %r"%_type val = str(v) return val #def lltype_to_cts(self, t, include_class=True): # return 'var' ## if isinstance(t, ootype.Instance): ## self.db.pending_class(t) ## return self.__class(t._name, include_class) ## elif isinstance(t, ootype.Record): ## name = self.db.pending_record(t) ## return self.__class(name, include_class) ## elif isinstance(t, ootype.StaticMethod): ## return 'void' # TODO: is it correct to ignore StaticMethod? ## elif isinstance(t, ootype.List): ## item_type = self.lltype_to_cts(t._ITEMTYPE) ## return self.__class(PYPY_LIST % item_type, include_class) ## elif isinstance(t, ootype.Dict): ## key_type = self.lltype_to_cts(t._KEYTYPE) ## value_type = self.lltype_to_cts(t._VALUETYPE) ## return self.__class(PYPY_DICT % (key_type, value_type), include_class) ## elif isinstance(t, ootype.DictItemsIterator): ## key_type = self.lltype_to_cts(t._KEYTYPE) ## value_type = self.lltype_to_cts(t._VALUETYPE) ## return self.__class(PYPY_DICT_ITEMS_ITERATOR % (key_type, value_type), include_class) ## ## return _get_from_dict(_lltype_to_cts, t, 'Unknown type %s' % t)
Python
""" Opcode meaning objects, descendants of MicroInstruction """ #from pypy.translator.js.jsbuiltin import Builtins from pypy.translator.oosupport.metavm import PushArg, PushAllArgs, StoreResult,\ InstructionList, New, GetField, MicroInstruction from pypy.translator.js.log import log from pypy.rpython.ootypesystem import ootype from types import FunctionType from pypy.objspace.flow.model import Constant class NewBuiltin(MicroInstruction): def __init__(self, arg): self.arg = arg def render(self, generator, op): generator.ilasm.new(self.arg) class _ListSetitem(MicroInstruction): def render(self, generator, op): generator.load(op.args[1]) generator.load(op.args[3]) generator.load(op.args[2]) generator.ilasm.list_setitem() ListSetitem = _ListSetitem() class _ListGetitem(MicroInstruction): def render(self, generator, op): generator.load(op.args[1]) generator.load(op.args[2]) generator.ilasm.list_getitem() ListGetitem = _ListGetitem() class _ListContains(MicroInstruction): def render(self, generator, op): generator.load(op.args[1]) generator.load(op.args[2]) generator.ilasm.list_getitem() generator.ilasm.load_void() generator.emit('!=') ListContains = _ListContains() class _Call(MicroInstruction): def render(self, generator, op): graph = op.args[0].value.graph self._render_function(generator, graph, op.args) def _render_builtin(self, generator, builtin, args): for func_arg in args[1:]: # push parameters generator.load(func_arg) generator.call_external(builtin, args[1:]) def _render_builtin_prepared_args(self, generator, builtin, args): for func_arg in args: generator.load_str(func_arg) generator.call_external(builtin, args) def _render_builtin_method(self, generator, builtin, args): for func_arg in args: generator.load_special(func_arg) generator.call_external_method(builtin, len(args)-1) def _render_function(self, generator, graph, args): for func_arg in args[1:]: # push parameters if func_arg.concretetype is not ootype.Void: generator.load(func_arg) generator.call_graph(graph) def _render_method(self, generator, method_name, args): this = args[0] for arg in args: # push parametes generator.load(arg) generator.call_method(this.concretetype, method_name) Call = _Call() class CallBuiltin(_Call): def __init__(self, builtin): self.builtin = builtin def render(self, generator, op): self._render_builtin(generator, self.builtin, op.args) class CallBuiltinMethod(_Call): def __init__(self, builtin, slice=None, additional_args=[]): self.builtin = builtin self.slice = slice self.additional_args = additional_args def render(self, generator, op): if self.slice is not None: args = op.args[self.slice] else: args = op.args args += self.additional_args self._render_builtin_method(generator, self.builtin, args) class _SameAs(MicroInstruction): def render(self, generator, op): generator.change_name(op.result, op.args[0]) class _CastFun(MicroInstruction): def __init__(self, name, num): self.name = name self.num = num def render(self, generator, op): log("Args: %r"%op.args) generator.cast_function(self.name, self.num) class _Prefix(MicroInstruction): def __init__(self, st): self.st = st def render(self, generator, op): generator.prefix_op(self.st) class _NotImplemented(MicroInstruction): def __init__(self, reason): self.reason = reason def render(self, generator, op): raise NotImplementedError(self.reason) class _CastMethod(MicroInstruction): def __init__(self, method_name, num=0): self.method_name = method_name self.num = num def render(self, generator, op): generator.call_external_method(self.method_name, self.num) class _LoadConst(MicroInstruction): def __init__(self, value): self.value = value def render(self, generator, op): generator.load(Constant(self.value, ootype.typeOf(self.value))) class _GetBuiltinField(MicroInstruction): def render(self, generator, op): this = op.args[0] field = op.args[1].value[1:] generator.load(this) generator.get_field(None, field) class _GetPredefinedField(MicroInstruction): def __init__(self, field): self.field = field def render(self, generator, op): this = op.args[1] generator.load(this) generator.get_field(None, self.field) GetBuiltinField = _GetBuiltinField() class _SetBuiltinField(MicroInstruction): def render(self, generator, op): this = op.args[0] field = op.args[1].value if not field.startswith('o'): generator.load_void() else: value = op.args[2] field_name = field[1:] self.run_it(generator, this, field_name, value) def run_it(self, generator, this, field_name, value): generator.load(this) generator.load_special(value) generator.set_field(None, field_name) class _SetPredefinedField(_SetBuiltinField): def __init__(self, field): self.field = field def render(self, generator, op): value = op.args[2] this = op.args[1] self.run_it(generator, this, self.field, value) class _SetExternalField(_SetBuiltinField): def render(self, generator, op): self.run_it(generator, op.args[0], op.args[1].value, op.args[2]) SetBuiltinField = _SetBuiltinField() SetExternalField = _SetExternalField() class _CallMethod(_Call): def render(self, generator, op): method = op.args[0] self._render_method(generator, method.value, op.args[1:]) class _CallBuiltinObject(_Call): def render(self, generator, op): this = op.args[1].concretetype method = op.args[0] method_name = this._methods[method.value]._name[1:] generator.load(op.args[1]) self._render_builtin_method(generator, method_name, op.args[1:]) class _CallExternalObject(_Call): def render(self, generator, op): this = op.args[1].concretetype method = op.args[0] method_name = method.value #generator.load(op.args[1]) self._render_builtin_method(generator, method_name, op.args[1:]) CallBuiltinObject = _CallBuiltinObject() CallExternalObject = _CallExternalObject() class _IsInstance(MicroInstruction): def render(self, generator, op): # FIXME: just temporary hack generator.load(op.args[0]) generator.ilasm.load_const(op.args[1].value._name.replace('.', '_'))#[-1]) generator.cast_function("isinstanceof", 2) class _IndirectCall(MicroInstruction): def render(self, generator, op): for func_arg in op.args[1:]: # push parameters generator.load(func_arg) generator.call_external(op.args[0].name, op.args[1:]) class _SetTimeout(MicroInstruction): # FIXME: Dirty hack for javascript callback stuff def render(self, generator, op): val = op.args[1].value assert(isinstance(val, ootype._static_meth)) #if isinstance(val, ootype.StaticMethod): real_name = val._name generator.db.pending_function(val.graph) #generator.db.pending_function(val.graph) #else: # concrete = val.concretize() # real_name = concrete.value._name # generator.db.pending_function(concrete.value.graph) generator.load_str("'%s()'" % real_name) generator.load(op.args[2]) generator.call_external('setTimeout',[0]*2) class _DiscardStack(MicroInstruction): def render(self, generator, op): generator.clean_stack() class SetOnEvent(MicroInstruction): def __init__(self, field): self.field = field # FIXME: Dirty hack for javascript callback stuff def render(self, generator, op): val = op.args[1].value val = val.concretize().value assert(isinstance(val, ootype._static_meth)) real_name = val._name generator.db.pending_function(val.graph) generator.load_str("document") generator.load_str(real_name) generator.set_field(None, self.field) class _CheckLength(MicroInstruction): def render(self, generator, op): assert not generator.ilasm.right_hand class _ListRemove(MicroInstruction): def render(self, generator, op): generator.list_getitem(op.args[1], op.args[2]) generator.call_external('delete', [0]) ListRemove = _ListRemove() CheckLength = _CheckLength() SetTimeout = _SetTimeout() IndirectCall = _IndirectCall() IsInstance = _IsInstance() CallMethod = _CallMethod() CopyName = [PushAllArgs, _SameAs ()] CastString = _CastFun("convertToString", 1) SameAs = CopyName DiscardStack = _DiscardStack() def fix_opcodes(opcodes): for key, value in opcodes.iteritems(): if type(value) is str: value = InstructionList([PushAllArgs, value, StoreResult, CheckLength]) elif value == []: value = InstructionList([CheckLength]) elif value is not None: if StoreResult not in value: value.append(StoreResult) if CheckLength not in value: value.append(CheckLength) value = InstructionList(value) opcodes[key] = value
Python
""" JavaScript builtin mappings """ from pypy.translator.oosupport.metavm import InstructionList, PushAllArgs,\ _PushAllArgs from pypy.translator.js.metavm import SetBuiltinField, ListGetitem, ListSetitem, \ GetBuiltinField, CallBuiltin, Call, SetTimeout, ListContains,\ NewBuiltin, SetOnEvent, ListRemove, CallBuiltinMethod, _GetPredefinedField,\ _SetPredefinedField from pypy.rpython.ootypesystem import ootype class _Builtins(object): def __init__(self): list_resize = _SetPredefinedField('length') self.builtin_map = { 'll_js_jseval' : CallBuiltin('eval'), 'set_on_keydown' : SetOnEvent('onkeydown'), 'set_on_keyup' : SetOnEvent('onkeyup'), 'setTimeout' : SetTimeout, 'll_int_str' : CallBuiltinMethod('toString', [2]), 'll_strconcat' : InstructionList([_PushAllArgs(slice(1, None)), '+']), 'll_int' : CallBuiltin('parseInt'), #'alert' : CallBuiltin('alert'), 'seval' : CallBuiltin('seval'), 'date': NewBuiltin('Date'), 'll_math.ll_math_fmod' : InstructionList([_PushAllArgs(slice(1, None)), '%']), 'll_time_time' : CallBuiltin('time'), 'll_time_clock' : CallBuiltin('clock'), 'll_os_write' : CallBuiltin('print'), } self.builtin_obj_map = { ootype.String.__class__: { 'll_strconcat' : InstructionList([_PushAllArgs(slice(1, None)), '+']), 'll_strlen' : _GetPredefinedField('length'), 'll_stritem_nonneg' : CallBuiltinMethod('charAt', slice(1,None)), 'll_streq' : InstructionList([_PushAllArgs(slice(1, None)), '==']), 'll_strcmp' : CallBuiltin('strcmp'), 'll_startswith' : CallBuiltin('startswith'), 'll_endswith' : CallBuiltin('endswith'), 'll_split_chr' : CallBuiltin('splitchr'), 'll_substring' : CallBuiltin('substring'), 'll_lower' : CallBuiltinMethod('toLowerCase', slice(1, None)), 'll_upper' : CallBuiltinMethod('toUpperCase', slice(1, None)), 'll_find' : CallBuiltin('findIndexOf'), 'll_find_char' : CallBuiltin('findIndexOf'), 'll_contains' : CallBuiltin('findIndexOfTrue'), 'll_replace_chr_chr' : CallBuiltinMethod('replace', slice(1, None), ['g']), 'll_count_char' : CallBuiltin('countCharOf'), 'll_count' : CallBuiltin('countOf'), }, ootype.List: { 'll_setitem_fast' : ListSetitem, 'll_getitem_fast' : ListGetitem, '_ll_resize' : list_resize, '_ll_resize_ge' : list_resize, '_ll_resize_le' : list_resize, 'll_length' : _GetPredefinedField('length'), }, ootype.Dict: { 'll_get' : ListGetitem, 'll_set' : ListSetitem, 'll_contains' : ListContains, 'll_get_items_iterator' : CallBuiltin('dict_items_iterator'), 'll_length' : CallBuiltin('get_dict_len'), 'll_remove' : ListRemove, 'll_clear': CallBuiltin('clear_dict'), }, ootype.Record: { 'll_get' : ListGetitem, 'll_set' : ListSetitem, 'll_contains' : ListContains, } } self.fix_opcodes() def fix_opcodes(self): from pypy.translator.js.metavm import fix_opcodes #fix_opcodes(self.builtin_map) #for value in self.builtin_obj_map.values(): # fix_opcodes(value) Builtins = _Builtins()
Python
""" self cloning, automatic path configuration copy this into any subdirectory of pypy from which scripts need to be run, typically all of the test subdirs. The idea is that any such script simply issues import autopath and this will make sure that the parent directory containing "pypy" is in sys.path. If you modify the master "autopath.py" version (in pypy/tool/autopath.py) you can directly run it which will copy itself on all autopath.py files it finds under the pypy root directory. This module always provides these attributes: pypydir pypy root directory path this_dir directory where this autopath.py resides """ def __dirinfo(part): """ return (partdir, this_dir) and insert parent of partdir into sys.path. If the parent directories don't have the part an EnvironmentError is raised.""" import sys, os try: head = this_dir = os.path.realpath(os.path.dirname(__file__)) except NameError: head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) while head: partdir = head head, tail = os.path.split(head) if tail == part: break else: raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) pypy_root = os.path.join(head, '') try: sys.path.remove(head) except ValueError: pass sys.path.insert(0, head) munged = {} for name, mod in sys.modules.items(): if '.' in name: continue fn = getattr(mod, '__file__', None) if not isinstance(fn, str): continue newname = os.path.splitext(os.path.basename(fn))[0] if not newname.startswith(part + '.'): continue path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') if path.startswith(pypy_root) and newname != part: modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) if newname != '__init__': modpaths.append(newname) modpath = '.'.join(modpaths) if modpath not in sys.modules: munged[modpath] = mod for name, mod in munged.iteritems(): if name not in sys.modules: sys.modules[name] = mod if '.' in name: prename = name[:name.rfind('.')] postname = name[len(prename)+1:] if prename not in sys.modules: __import__(prename) if not hasattr(sys.modules[prename], postname): setattr(sys.modules[prename], postname, mod) return partdir, this_dir def __clone(): """ clone master version of autopath.py into all subdirs """ from os.path import join, walk if not this_dir.endswith(join('pypy','tool')): raise EnvironmentError("can only clone master version " "'%s'" % join(pypydir, 'tool',_myname)) def sync_walker(arg, dirname, fnames): if _myname in fnames: fn = join(dirname, _myname) f = open(fn, 'rwb+') try: if f.read() == arg: print "checkok", fn else: print "syncing", fn f = open(fn, 'w') f.write(arg) finally: f.close() s = open(join(pypydir, 'tool', _myname), 'rb').read() walk(pypydir, sync_walker, s) _myname = 'autopath.py' # set guaranteed attributes pypydir, this_dir = __dirinfo('pypy') if __name__ == '__main__': __clone()
Python
#!/usr/bin/env python """ A basic Python console from your browser. This depends on MochiKit for proper quoting. You need to provide the files as ..jsdemo/MochiKit/*.js. (Symlinks are your friends.) Try to type: import time; time.sleep(2); print 'hi' """ import autopath import sys, os, cStringIO from cgi import parse_qs from pypy.translator.js.modules.dom import setTimeout, document, window from pypy.translator.js.modules.mochikit import connect, disconnect from pypy.rpython.ootypesystem.bltregistry import MethodDesc, BasicExternal from pypy.translator.js import commproxy from pypy.rpython.extfunc import genericcallable from pypy.translator.js.lib import support from pypy.translator.js.lib import server commproxy.USE_MOCHIKIT = True from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from SocketServer import ThreadingMixIn import time HTML_PAGE = """ <html> <head> <title>Example</title> <script type="text/javascript" src="jssource"></script> <script src="http://mochikit.com/MochiKit/MochiKit.js" type="text/javascript"></script> </head> <body onload="setup_page()"> <h3>Console</h3> <p>Note that a default timeout for the console is 5 minutes, after that time console just dies and stops responding</p> <div id="data"></div> <input id="inp" size="100" type="text" autocomplete="off"/> </body> </html> """ httpd = None def callback(data): inp_elem = document.getElementById("inp") inp_elem.disabled = False answer = data.get('answer', '') add_text(answer) inp_elem.focus() def add_text(text): data_elem = document.getElementById("data") lines = text.split('\n') lines.pop() for line in lines: pre = document.createElement('pre') pre.style.margin = '0px' pre.appendChild(document.createTextNode(line)) data_elem.appendChild(pre) class Storage(object): def __init__(self): self.level = 0 self.cmd = "" storage = Storage() def keypressed(key): kc = key._event.keyCode if kc == ord("\r"): inp_elem = document.getElementById("inp") cmd = inp_elem.value if storage.level == 0: add_text(">>> %s\n" % (cmd,)) else: add_text("... %s\n" % (cmd,)) inp_elem.value = '' if cmd: storage.cmd += cmd + "\n" if cmd.endswith(':'): storage.level = 1 elif storage.level == 0 or cmd == "": if (not storage.level) or (not cmd): inp_elem.disabled = True httpd.some_callback(storage.cmd, callback) storage.cmd = "" storage.level = 0 def setup_page(): connect(document, 'onkeypress', keypressed) document.getElementById("inp").focus() class Server(HTTPServer, BasicExternal): # Methods and signatures how they are rendered for JS _methods = { 'some_callback' : MethodDesc([('cmd', str), ('callback', genericcallable([{str:str}]))], {str:str}) } _render_xmlhttp = True def __init__(self, *args, **kwargs): HTTPServer.__init__(self, *args, **kwargs) self.source = None self.locals = {} class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): path = self.path if '?' in path: i = path.index('?') else: i = len(path) kwds = parse_qs(path[i+1:]) path = path[:i].split("/") if not path[0]: del path[0] if not path: path = [''] cmd = path[0] args = path[1:] method_to_call = getattr(self, "run_" + cmd, None) if method_to_call is None: self.send_error(404, "File %r not found" % (self.path,)) else: method_to_call(*args, **kwds) do_POST = do_GET def run_(self): self.run_index() def run_index(self): self.serve_data("text/html", HTML_PAGE) def run_MochiKit(self, filename): assert filename in os.listdir('MochiKit') pathname = os.path.join('MochiKit', filename) f = open(pathname, 'r') data = f.read() f.close() self.serve_data("text/javascript", data) def run_some_callback(self, cmd=[""]): cmd = cmd[0] self.server.last_activity = time.time() if cmd: buf = cStringIO.StringIO() out1 = sys.stdout err1 = sys.stderr try: sys.stdout = sys.stderr = buf try: exec compile(cmd, '?', 'single') in self.server.locals except Exception: import traceback traceback.print_exc() finally: sys.stdout = out1 sys.stderr = err1 answer = buf.getvalue() else: answer = "" self.serve_data("text/json", repr({'answer': answer})) def run_jssource(self): if self.server.source: source = self.server.source else: source = support.js_source([setup_page]) self.server.source = source self.serve_data("text/javascript", source) def serve_data(self, content_type, data): self.send_response(200) self.send_header("Content-type", content_type) self.send_header("Content-length", len(data)) self.send_header('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT') self.send_header('Last-Modified', time.strftime("%a, %d %b %Y %H:%M:%S GMT")) self.send_header('Cache-Control', 'no-cache, must-revalidate') self.send_header('Cache-Control', 'post-check=0, pre-check=0') self.send_header('Pragma', 'no-cache') self.end_headers() self.wfile.write(data) def build_http_server(server_address=('', 8001)): global httpd httpd = Server(server_address, RequestHandler) print 'http://127.0.0.1:%d' % (server_address[1],) def _main(address=('', 8001)): build_http_server(server_address=address) httpd.serve_forever() if __name__ == '__main__': _main()
Python
from struct import pack, unpack, calcsize try: from localmsg import PORTS except ImportError: PORTS = {} try: from localmsg import HOSTNAME except ImportError: from socket import gethostname HOSTNAME = gethostname() MSG_WELCOME = "Welcome to gamesrv.py(3) !\n" MSG_BROADCAST_PORT= "*" MSG_DEF_PLAYFIELD = "p" MSG_DEF_KEY = "k" MSG_DEF_ICON = "r" MSG_DEF_BITMAP = "m" MSG_DEF_SAMPLE = "w" MSG_DEF_MUSIC = "z" MSG_PLAY_MUSIC = "Z" MSG_FADEOUT = "f" MSG_PLAYER_JOIN = "+" MSG_PLAYER_KILL = "-" MSG_PLAYER_ICON = "i" MSG_PING = "g" MSG_PONG = "G" MSG_INLINE_FRAME = "\\" MSG_PATCH_FILE = MSG_DEF_MUSIC MSG_ZPATCH_FILE = "P" MSG_MD5_FILE = "M" MSG_RECORDED = "\x00" CMSG_PROTO_VERSION= "v" CMSG_KEY = "k" CMSG_ADD_PLAYER = "+" CMSG_REMOVE_PLAYER= "-" CMSG_UDP_PORT = "<" CMSG_ENABLE_SOUND = "s" CMSG_ENABLE_MUSIC = "m" CMSG_PING = "g" CMSG_PONG = "G" CMSG_DATA_REQUEST = "M" CMSG_PLAYER_NAME = "n" BROADCAST_MESSAGE = "game!" # less than 6 bytes def message(tp, *values): strtype = type('') typecodes = [''] for v in values: if type(v) is strtype: typecodes.append('%ds' % len(v)) elif 0 <= v < 256: typecodes.append('B') else: typecodes.append('l') typecodes = ''.join(typecodes) assert len(typecodes) < 256 return pack(("!B%dsc" % len(typecodes)) + typecodes, len(typecodes), typecodes, tp, *values) def decodemessage(data): if data: limit = ord(data[0]) + 1 if len(data) >= limit: typecodes = "!c" + data[1:limit] try: end = limit + calcsize(typecodes) except TypeError: return None, '' if len(data) >= end: return unpack(typecodes, data[limit:end]), data[end:] elif end > 1000000: raise OverflowError return None, data
Python
from msgstruct import * from zlib import decompressobj, decompress from urllib import quote from os.path import exists from struct import unpack from time import time import md5 debug = True def log(msg): if debug: print msg class BitmapCreationException(Exception): pass #proxy messages #PMSG_PING = "ping" #server wants to hear from client #PMSG_PONG = "pong" #server responds to client's ping PMSG_DEF_PLAYFIELD = "def_playfield" PMSG_DEF_ICON = "def_icon" PMSG_PLAYER_ICON = "player_icon" PMSG_PLAYER_JOIN = "player_join" PMSG_PLAYER_KILL = "player_kill" PMSG_DEF_KEY = "def_key" PMSG_INLINE_FRAME = "inline_frame" # convert server messages to proxy messages in json format class ServerMessage: _md5_file = {} _bitmap2hexdigits={} _def_icon_queue = {} base_gfx_dir = 'data/images/' base_gfx_url = '/images/' gfx_extension = 'png' def __init__(self, base_gfx_dir = None): if base_gfx_dir: self.base_gfx_dir = base_gfx_dir if not self.base_gfx_dir.endswith('/'): self.base_gfx_dir += '/' self.socket = None self.data = '' self.n_header_lines = 2 self.gfx_dir = self.base_gfx_dir #gets overwritten depending on playfield FnDesc self.gfx_url = self.base_gfx_url self.decompressobj = decompressobj().decompress self.last_active = time() self._count = 0 def count(self): self._count += 1 return self._count def dispatch(self, *values): #log('RECEIVED:%s(%d)' % (values[0], len(values[1:]))) self.last_active = time() fn = self.MESSAGES.get(values[0]) if fn: try: return fn(self, *values[1:]) except BitmapCreationException, e: log(str(e)) return dict() else: log("UNKNOWN:%s" % str(values)) return dict(type='unknown', values=values) #server message handlers... def ignore(self, *values): #log('ignore %s' % str(values)) return def def_playfield(self, width, height, backcolor, FnDesc): #log('def_playfield width=%s, height=%s, backcolor=%s, FnDesc=%s' % (\ # width, height, backcolor, FnDesc)) self.gfx_dir = self.base_gfx_dir self.gfx_url = self.base_gfx_url return dict(type=PMSG_DEF_PLAYFIELD, width=width, height=height, backcolor=backcolor, FnDesc=FnDesc) def def_bitmap(self, bitmap_code, data_or_fileid, *rest): if type(data_or_fileid) is type(0): fn = self.def_bitmap2 else: fn = self.def_bitmap1 return fn(bitmap_code, data_or_fileid, *rest) def def_bitmap1(self, bitmap_code, data, *rest): import PIL.Image if len(rest) == 0: colorkey = None else: c = rest[0] colorkey = (c & 255, (c >> 8) & 255, (c >> 16) & 255) #log('def_bitmap1 bitmap_code=%d, data=%d bytes, colorkey=%s' % ( # bitmap_code, len(data), colorkey)) try: decompressed_data = decompress(data) except Exception, e: raise BitmapCreationException('ERROR UNCOMPRESSING DATA FOR %s (%s)' % ( bitmap_filename, str(e))) hexdigits = md5.new(decompressed_data).hexdigest() self._bitmap2hexdigits[bitmap_code] = hexdigits gfx_bitmap_filename = '%s%s.%s' % (self.gfx_dir, hexdigits, self.gfx_extension) if exists(gfx_bitmap_filename): #log('CACHED:%s' % gfx_bitmap_filename) pass else: bitmap_filename = '%s%s.ppm' % (self.gfx_dir, hexdigits) f = open(bitmap_filename, 'wb') f.write(decompressed_data) f.close() #TODO: use in memory (don't save ppm first) try: bitmap = PIL.Image.open(bitmap_filename) except IOError, e: raise BitmapCreationException('ERROR LOADING %s (%s)' % ( bitmap_filename, str(e))) #create alpha layer (PIL export this correctly with png but not with gif) if colorkey is not None: bitmap = bitmap.convert("RGBA") data = bitmap.getdata() c = (colorkey[0], colorkey[1], colorkey[2], 255) width, height = bitmap.size for y in range(height): #this is slowish but gfx are cached, so... for x in range(width): p = data.getpixel((x,y)) if p == c: data.putpixel((x,y), (0,0,0,0)) try: bitmap.save(gfx_bitmap_filename) log('SAVED:%s' % gfx_bitmap_filename) except IOError: raise BitmapCreationException('ERROR SAVING %s (%s)' % ( gfx_bitmap_filename, str(e))) def def_bitmap2(self, bitmap_code, fileid, *rest): #log('def_bitmap2: bitmap_code=%d, fileid=%d, colorkey=%s' % (bitmap_code, fileid, rest)) hexdigits = self._md5_file[fileid]['hexdigits'] self._bitmap2hexdigits[bitmap_code] = hexdigits gfx_bitmap_filename = '%s%s.%s' % (self.gfx_dir, hexdigits, self.gfx_extension) if exists(gfx_bitmap_filename): #log('SKIP DATA_REQUEST:%s' % gfx_bitmap_filename) pass else: self._md5_file[fileid]['bitmap_code'] = bitmap_code self._md5_file[fileid]['colorkey'] = rest position = self._md5_file[fileid]['offset'] size = self._md5_file[fileid]['len_data'] msg = message(CMSG_DATA_REQUEST, fileid, position, size) self.socket.send(msg) log('DATA_REQUEST:fileid=%d(pos=%d,size=%d):%s' % ( fileid, position, size, gfx_bitmap_filename)) def def_icon(self, bitmap_code, icon_code, x,y,w,h, *rest): import PIL.Image #log('def_icon bitmap_code=%s, icon_code=%s, x=%s, y=%s, w=%s, h=%s, alpha=%s' %\ # (bitmap_code, icon_code, x,y,w,h, rest) #ignore alpha (bubbles) hexdigits = self._bitmap2hexdigits[bitmap_code] bitmap_filename = '%s%s.%s' % (self.gfx_dir, hexdigits, self.gfx_extension) icon_filename = '%s%s_%d_%d_%d_%d.%s' % ( self.gfx_dir, hexdigits, x, y, w, h, self.gfx_extension) if exists(icon_filename): #log('CACHED:%s' % icon_filename) pass elif exists(bitmap_filename): #TODO: use in memory (don't save ppm first) icon = PIL.Image.open(bitmap_filename) box = (x, y, x+w, y+h) region = icon.crop(box) region.save(icon_filename) log('SAVED:%s' % icon_filename) else: #bitmap is not available yet (protocol 2) #log('%s NOT AVAILABLE FOR %s' % (bitmap_filename, icon_filename)) if bitmap_code not in self._def_icon_queue: self._def_icon_queue[bitmap_code] = [] self._def_icon_queue[bitmap_code].append((icon_code, x, y, w, h, rest)) return filename = '%s%s_%d_%d_%d_%d.%s' % ( self.gfx_url, hexdigits, x, y, w, h, self.gfx_extension) return dict(type=PMSG_DEF_ICON, icon_code=icon_code, filename=filename, width=w, height=h) def zpatch_file(self, fileid, position, data): #response to CMSG_DATA_REQUEST #log('zpatch_file fileid=%d, position=%d, len(data)=%d' % (fileid, position, len(data))) bitmap_code = self._md5_file[fileid]['bitmap_code'] colorkey = self._md5_file[fileid]['colorkey'] try: t = self.def_bitmap(bitmap_code, data, *colorkey) except BitmapCreationException, e: log(str(e)) return #i.e. not attempting to create icons messages = [] if bitmap_code in self._def_icon_queue: #log('%d icons queued for bitmap %d' % ( # len(self._def_icon_queue[bitmap_code]), bitmap_code)) for t in self._def_icon_queue[bitmap_code]: icon_code, x, y, w, h, rest = t messages.append(self.def_icon(bitmap_code, icon_code, x, y, w, h, *rest)) del self._def_icon_queue[bitmap_code] return messages def player_icon(self, player_id, icon_code): #log('player_icon player_id=%d, icon_code=%d' % (player_id, icon_code)) return dict(type=PMSG_PLAYER_ICON, player_id=player_id, icon_code=icon_code) def player_join(self, player_id, client_is_self): #log('player_join player_id=%d, client_is_self=%d' % (player_id, client_is_self)) return dict(type=PMSG_PLAYER_JOIN, player_id=player_id, client_is_self=client_is_self) def player_kill(self, player_id): #log('player_kill player_id=%d' % player_id) return dict(type=PMSG_PLAYER_KILL, player_id=player_id) def def_key(self, keyname, num, *icon_codes): #log('def_key keyname=%s, num=%d, icon_codes=%s' % (keyname, num, str(icon_codes))) return dict(type=PMSG_DEF_KEY, keyname=keyname, num=num, icon_codes=icon_codes) def md5_file(self, fileid, protofilepath, offset, len_data, checksum): hd = '0123456789abcdef' hexdigits = '' for c in checksum: i = ord(c) hexdigits = hexdigits + hd[i >> 4] + hd[i & 15] #log('md5_file fileid=%d, protofilepath=%s, offset=%d, len_data=%d, hexdigits=%s' % ( # fileid, protofilepath, offset, len_data, hexdigits)) self._md5_file[fileid] = { 'protofilepath' : protofilepath, 'offset' : offset, 'len_data' : len_data, 'checksum' : checksum, 'hexdigits' : hexdigits, } def inline_frame(self, data): decompressed_data = d = self.decompressobj(data) #log('inline_frame len(data)=%d, len(decompressed_data)=%d' % ( # len(data), len(d))) return_raw_data = False if return_raw_data: return dict(type=PMSG_INLINE_FRAME, data=decompressed_data) #note: we are not returning the raw data here but we could let the Javascript # handle it. If this is working we can convert this to RPython and move it # to the client instead. (based on BnB update_sprites in display/pclient.py) sounds, sprites = [], [] base = 0 while d[base+4:base+6] == '\xFF\xFF': key, lvol, rvol = struct.unpack("!hBB", udpdata[base:base+4]) sounds.append((key, lvol, rvol)) base += 6 for j in range(base, len(d)-5, 6): info = d[j:j+6] x, y, icon_code = unpack("!hhh", info[:6]) sprites.append((icon_code, x, y)) return dict(type=PMSG_INLINE_FRAME, sounds=sounds, sprites=sprites) MESSAGES = { MSG_BROADCAST_PORT : ignore, MSG_PING : ignore, MSG_PONG : ignore, MSG_DEF_PLAYFIELD : def_playfield, MSG_DEF_BITMAP : def_bitmap, MSG_ZPATCH_FILE : zpatch_file, MSG_DEF_ICON : def_icon, MSG_PLAYER_ICON : player_icon, MSG_PLAYER_JOIN : player_join, MSG_PLAYER_KILL : player_kill, MSG_DEF_KEY : def_key, MSG_MD5_FILE : md5_file, MSG_INLINE_FRAME : inline_frame, }
Python
#!/usr/bin/env python """ bub-n-bros testing utility """ import autopath import py from pypy.translator.js.main import rpython2javascript from pypy.translator.js.modules.dom import document, window from pypy.translator.js.modules.mochikit import log, logWarning,\ createLoggingPane, logDebug, connect from pypy.translator.js.examples.bnb.bnb import exported_methods from pypy.translator.js import commproxy commproxy.USE_MOCHIKIT = True import time import os import sys def logKey(msg): pass class Stats(object): """ Class containing some statistics """ def __init__(self): self.n_received_inline_frames = 0 self.n_rendered_inline_frames = 0 self.n_rendered_dynamic_sprites = 0 self.fps = 0 self.starttime = 0.0 self.n_sprites = 0 def register_frame(self): self.n_rendered_inline_frames += 1 if self.n_rendered_inline_frames >= 10: next_time = time.time() self.fps = 10000/(next_time - self.starttime) self.n_rendered_inline_frames = 0 self.starttime = next_time stats = Stats() class Player(object): def __init__(self): self.id = -1 self.prev_count = 0 self.sessionid = "" player = Player() class SpriteManager(object): def __init__(self): self.sprites = {} self.filenames = {} self.all_sprites = {} self.frames = [] def add_icon(self, icon_code, filename): self.filenames[icon_code] = filename #self.sprite_queues[icon_code] = [] #self.used[icon_code] = [] # FIXME: Need to write down DictIterator once... #self.icon_codes.append(icon_code) def add_sprite(self, s, icon_code, x, y): #try: # img = self.sprite_queues[icon_code].pop() #except IndexError: stats.n_sprites += 1 img = document.createElement("img") img.src = self.filenames[icon_code] img.style.position = 'absolute' img.style.left = x + 'px' img.style.top = y + 'px' img.style.visibility = 'visible' document.getElementById("playfield").appendChild(img) try: self.sprites[s].style.visibility = "hidden" # FIXME: We should delete it except KeyError: self.sprites[s] = img return img def move_sprite(self, s, x, y): i = self.sprites[s] i.style.top = y + 'px' i.style.left = x + 'px' i.style.visibility = 'visible' def hide_sprite(self, s): i = self.sprites[s] i.style.visibility = "hidden" def start_clean_sprites(self): self.all_sprites = {} def show_sprite(self, s, icon_code, x, y): self.all_sprites[s] = 1 try: self.move_sprite(s, x, y) except KeyError: self.add_sprite(s, icon_code, x, y) def end_clean_sprites(self): for i in self.sprites: try: self.all_sprites[i] except KeyError: self.hide_sprite(i) def set_z_index(self, s_num, z): self.sprites[s_num].style.zIndex = z #def show_sprite(self, s): # i = self.sprites[s] # i.style.visibility = "visible" sm = SpriteManager() class KeyManager(object): def __init__(self): self.keymappings = {ord('D'):'right', ord('S'):'fire', ord('A'):'left', ord('W'):'up'} self.key_to_bnb_down = {'right':0, 'left':1, 'fire':3, 'up':2} self.key_to_bnb_up = {'right':4, 'left':5, 'fire':7, 'up':6} self.queue = [] def add_key_up(self, key): self.queue.append(self.key_to_bnb_up[key]) def add_key_down(self, key): self.queue.append(self.key_to_bnb_down[key]) def get_keys(self): retval = self.queue self.queue = [] return retval km = KeyManager() def appendPlayfield(msg): body = document.getElementsByTagName('body')[0] bgcolor = '#000' body.style.backgroundColor = bgcolor div = document.createElement("div") div.id = 'playfield' div.style.width = msg['width'] div.style.height = msg['height'] div.style.position = 'absolute' div.style.top = '0px' div.style.left = '0px' div.appendChild(document.createTextNode('foobar?')) #document.body.childNodes.insert(0, div) body.appendChild(div) def appendPlayfieldXXX(): bgcolor = '#000000' document.body.setAttribute('bgcolor', bgcolor) div = document.createElement("div") div.id = 'playfield' div.style.width = 500 div.style.height = 250 div.style.position = 'absolute' div.style.top = '0px' div.style.left = '0px' document.body.appendChild(div) def process_message(msg): if msg['type'] == 'def_playfield': appendPlayfield(msg) elif msg['type'] == 'def_icon': sm.add_icon(msg['icon_code'], msg['filename']) elif msg['type'] == 'ns': sm.add_sprite(msg['s'], msg['icon_code'], msg['x'], msg['y']) sm.set_z_index(msg['s'], msg['z']) elif msg['type'] == 'sm': sm.move_sprite(msg['s'], msg['x'], msg['y']) sm.set_z_index(msg['s'], msg['z']) elif msg['type'] == 'ds': sm.hide_sprite(msg['s']) elif msg['type'] == 'begin_clean_sprites': sm.start_clean_sprites() elif msg['type'] == 'clean_sprites': sm.end_clean_sprites() elif msg['type'] == 'show_sprite': sm.show_sprite(msg['s'], msg['icon_code'], msg['x'], msg['y']) elif msg['type'] == 'zindex': sm.set_z_index(msg['s'], msg['z']) #elif msg['type'] == 'ss': # sm.show_sprite(msg['s']) elif msg['type'] == 'player_icon' or msg['type'] == 'def_key' or \ msg['type'] == 'player_join' or msg['type'] == 'player_kill': pass #ignore else: logWarning('unknown message type: ' + msg['type']) def ignore(arg): pass ignore._annspecialcase_ = 'specialize:argtype(0)' def addPlayer(player_id): name = "player no. " + str(player_id) #name = "player no. %d" % player_id #File "/Users/eric/projects/pypy-dist/pypy/translator/js/jts.py", line 52, in lltype_to_cts # raise NotImplementedError("Type %r" % (t,)) # NotImplementedError: Type <StringBuilder> prev_player_id = player.id if player.id >= 0: exported_methods.remove_player(player.id, player.sessionid, ignore) player.id = -1 if player_id != prev_player_id: exported_methods.player_name(player_id, name, player.sessionid, ignore) exported_methods.add_player(player_id, player.sessionid, ignore) player.id = player_id def keydown(key): #c = chr(int(key.keyCode)).lower() #c = int(key.keyCode) key = key._event try: c = key.keyCode if c > ord('0') and c < ord('9'): addPlayer(int(chr(c))) #for i in km.keymappings: # log(str(i)) if c in km.keymappings: km.add_key_down(km.keymappings[c]) #else: except Exception, e: log(str(e)) def keyup(key): key = key._event c = key.keyCode if c > ord('0') and c < ord('9'): pass #don't print warning elif c in km.keymappings: km.add_key_up(km.keymappings[c]) else: logWarning('unknown keyup: ' + str(c)) #def ignore_dispatcher(msgs): # pass def bnb_dispatcher(msgs): s = ":".join([str(i) for i in km.get_keys()]) exported_methods.get_message(player.sessionid, player.id, s, bnb_dispatcher) render_frame(msgs) def render_frame(msgs): for msg in msgs['messages']: process_message(msg) stats.register_frame() document.title = str(stats.n_sprites) + " sprites " + str(stats.fps) def session_dispatcher(sessionid): player.sessionid = sessionid connect(document, 'onkeydown', keydown) connect(document, 'onkeyup', keyup) exported_methods.get_message(player.sessionid, player.id, "", bnb_dispatcher) def bnb(): createLoggingPane(True) log("keys: [0-9] to select player, [wsad] to walk around") exported_methods.initialize_session(session_dispatcher) def run_bnb(): from pypy.translator.js.examples.bnb.bnb import BnbRoot from pypy.translator.js.lib import server addr = ('', 7070) httpd = server.create_server(handler=BnbRoot, server_address=addr) httpd.source = rpython2javascript(sys.modules[__name__], ['bnb']) httpd.serve_forever() if __name__ == '__main__': run_bnb()
Python
""" self cloning, automatic path configuration copy this into any subdirectory of pypy from which scripts need to be run, typically all of the test subdirs. The idea is that any such script simply issues import autopath and this will make sure that the parent directory containing "pypy" is in sys.path. If you modify the master "autopath.py" version (in pypy/tool/autopath.py) you can directly run it which will copy itself on all autopath.py files it finds under the pypy root directory. This module always provides these attributes: pypydir pypy root directory path this_dir directory where this autopath.py resides """ def __dirinfo(part): """ return (partdir, this_dir) and insert parent of partdir into sys.path. If the parent directories don't have the part an EnvironmentError is raised.""" import sys, os try: head = this_dir = os.path.realpath(os.path.dirname(__file__)) except NameError: head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) while head: partdir = head head, tail = os.path.split(head) if tail == part: break else: raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) pypy_root = os.path.join(head, '') try: sys.path.remove(head) except ValueError: pass sys.path.insert(0, head) munged = {} for name, mod in sys.modules.items(): if '.' in name: continue fn = getattr(mod, '__file__', None) if not isinstance(fn, str): continue newname = os.path.splitext(os.path.basename(fn))[0] if not newname.startswith(part + '.'): continue path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') if path.startswith(pypy_root) and newname != part: modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) if newname != '__init__': modpaths.append(newname) modpath = '.'.join(modpaths) if modpath not in sys.modules: munged[modpath] = mod for name, mod in munged.iteritems(): if name not in sys.modules: sys.modules[name] = mod if '.' in name: prename = name[:name.rfind('.')] postname = name[len(prename)+1:] if prename not in sys.modules: __import__(prename) if not hasattr(sys.modules[prename], postname): setattr(sys.modules[prename], postname, mod) return partdir, this_dir def __clone(): """ clone master version of autopath.py into all subdirs """ from os.path import join, walk if not this_dir.endswith(join('pypy','tool')): raise EnvironmentError("can only clone master version " "'%s'" % join(pypydir, 'tool',_myname)) def sync_walker(arg, dirname, fnames): if _myname in fnames: fn = join(dirname, _myname) f = open(fn, 'rwb+') try: if f.read() == arg: print "checkok", fn else: print "syncing", fn f = open(fn, 'w') f.write(arg) finally: f.close() s = open(join(pypydir, 'tool', _myname), 'rb').read() walk(pypydir, sync_walker, s) _myname = 'autopath.py' # set guaranteed attributes pypydir, this_dir = __dirinfo('pypy') if __name__ == '__main__': __clone()
Python
""" xmlhttp controllers, usefull for testing """ import py from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc from pypy.translator.js.examples.bnb.servermessage import log, ServerMessage,\ PMSG_INLINE_FRAME, PMSG_DEF_ICON from pypy.translator.js.examples.bnb.msgstruct import * from pypy.translator.js.lib.support import callback from pypy.translator.js.lib import server import re, time, sys, os, urllib, socket, copy, md5, random class SpriteManager(object): def __init__(self): self.sprite_sets = {} self.positions = {} self.num = 0 self.next_pos = {} self.last_seen = set() self.seen = set() self.num_frame = 0 self.z_index = {} def def_icon(self, icon_code): self.sprite_sets[icon_code] = [] def get_frame_number(self): self.num_frame += 1 def get_sprite(self, icon_code, x, y): try: to_ret = self.positions[(icon_code, x, y)] del self.positions[(icon_code, x, y)] self.next_pos[(icon_code, x, y)] = to_ret self.seen.add((icon_code, to_ret)) return "still", to_ret except KeyError: try: try: to_ret = self.sprite_sets[icon_code].pop() except KeyError: self.def_icon(icon_code) raise IndexError self.next_pos[(icon_code, x, y)] = to_ret self.seen.add((icon_code, to_ret)) return "move", to_ret except IndexError: next = self.num self.num += 1 self.next_pos[(icon_code, x, y)] = next self.seen.add((icon_code, next)) return "new", next def end_frame(self): self.positions = copy.deepcopy(self.next_pos) self.next_pos = {} to_ret = [] for ic, i in self.last_seen - self.seen: self.sprite_sets[ic].append(i) to_ret.append(i) self.last_seen = self.seen self.seen = set() return to_ret class ExportedMethods(server.ExportedMethods): _serverMessage = {} _spriteManagers = {} host = 'localhost' try: port = re.findall('value=".*"', urllib.urlopen('http://%s:8000' % host).read())[0] port = int(port[7:-1]) except IOError: log("ERROR: Can't connect to BnB server on %s:8000" % host) # sys.exit() except IndexError: log("ERROR: Connected to BnB server but unable to detect a running game") # sys.exit() #def _close(self, sessionid): # if sessionid in self._serverMessage: # sm = self.serverMessage() # if sm.socket is not None: # sm.socket.close() # del self._serverMessage[sessionid] def get_sprite_manager(self, sessionid): return self._spriteManagers[sessionid] def sessionSocket(self, sessionid, close=False): sm = self.serverMessage(sessionid) if sm.socket is None: player_id = 0 #XXX hardcoded for now sm.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sm.socket.connect((self.host, self.port)) sm.socket.send(message(CMSG_PROTO_VERSION, 2)) #, version a kuku sm.socket.send(message(CMSG_ENABLE_SOUND, 0)) #, has_sound sm.socket.send(message(CMSG_ENABLE_MUSIC, 0)) #, has_music sm.socket.send(message(CMSG_UDP_PORT, "\\")) #, port sm.socket.send(message(CMSG_PING)) #so server starts sending data return sm.socket def _closeIdleConnections(self): t = time.time() - 20.0 #20 seconds until considered idle for sessionid, sm in self._serverMessage.items(): if sm.last_active < t: log("Close connection with sessionid %s because it was idle for %.1f seconds" % ( sessionid, time.time() - sm.last_active)) if sm.socket is not None: sm.socket.close() del self._serverMessage[sessionid] def serverMessage(self, sessionid): self._closeIdleConnections() if sessionid not in self._serverMessage: self._serverMessage[sessionid] = ServerMessage('data/images') return self._serverMessage[sessionid] @callback(retval=None) def player_name(self, player_id=0, name="", sessionid=""): log("Changing player #%s name to %s" % (player_id, name)) socket = self.sessionSocket(sessionid) socket.send(message(CMSG_PLAYER_NAME, int(player_id), name)) @callback(retval=None) def add_player(self, player_id=0, sessionid=""): log("Adding player " + player_id) socket = self.sessionSocket(sessionid) socket.send(message(CMSG_ADD_PLAYER, int(player_id))) @callback(retval=None) def remove_player(self, player_id=0, sessionid=""): log("Remove player " + player_id) socket = self.sessionSocket(sessionid) socket.send(message(CMSG_REMOVE_PLAYER, int(player_id))) @callback(retval=str) def initialize_session(self): sessionid = md5.md5(str(random.random())).hexdigest() self._create_session(sessionid) return sessionid def _create_session(self, sessionid): sm = ServerMessage('data/images/') self._serverMessage[sessionid] = sm self._spriteManagers[sessionid] = SpriteManager() return sessionid @callback(retval={str:[{str:str}]}) def get_message(self, sessionid="", player_id=0, keys=""): """ This one is long, ugly and obscure """ #XXX hangs if not first sending CMSG_PING! try: sm = self.serverMessage(sessionid) except KeyError: self._create_session(sessionid) sm = self.serverMessage(sessionid) data = sm.data sock = self.sessionSocket(sessionid) while True: try: data += sock.recv(4096, socket.MSG_DONTWAIT) except: break while sm.n_header_lines > 0 and '\n' in data: sm.n_header_lines -= 1 header_line, data = data.split('\n',1) #log('RECEIVED HEADER LINE: %s' % header_line) #log('RECEIVED DATA CONTAINS %d BYTES' % len(data)) messages = [] while data: values, data = decodemessage(data) if not values: break # incomplete message messageOutput = sm.dispatch(*values) if messageOutput: if type(messageOutput) is type([]): messages += messageOutput else: messages.append(messageOutput) sm.data = data len_before = len(messages) inline_frames = [i for i,msg in enumerate(messages) if msg['type'] == PMSG_INLINE_FRAME] for i in reversed(inline_frames[:-1]): del messages[i] to_append = [] sprite_manager = self.get_sprite_manager(sessionid) sm_restart = 0 if player_id != -1: if keys: for i in keys.split(":"): self.sessionSocket(sessionid).\ send(message(CMSG_KEY, int(player_id), int(i))) def get_partial_frame(next, z_num): new_sprite, s_num = sprite_manager.get_sprite(*next) if new_sprite == 'new': to_append.append({'type':'ns', 's':s_num, 'icon_code':str(next[0]), 'x':str(next[1]), 'y':str(next[2]), 'z':z_num}) sprite_manager.z_index[s_num] = z_num elif new_sprite == 'move': to_append.append({'type':'sm', 's':str(s_num), 'x':str(next[1]), 'y':str(next[2]), 'z':z_num}) sprite_manager.z_index[s_num] = z_num else: if sprite_manager.z_index[s_num] != z_num: to_append.append({'type':'zindex', 's':s_num, 'z':z_num}) sprite_manager.z_index[s_num] = z_num return s_num z_num = 0 for i, msg in enumerate(messages): if msg['type'] == PMSG_INLINE_FRAME: for next in msg['sprites']: s_num = get_partial_frame(next, z_num) z_num += 1 del messages[i] empty_frame = False if sprite_manager.seen == set([]): empty_frame = True if not empty_frame: for i in sprite_manager.end_frame(): to_append.append({'type':'ds', 's':str(i)}) messages += to_append return dict(messages=messages, add_data=[{'n':sm.count(), 'sm_restart':sm_restart}]) exported_methods = ExportedMethods() class BnbHandler(server.Collection): """ BnB server handler """ exported_methods = exported_methods static_dir = py.path.local(__file__).dirpath().join("data") index = server.Static(static_dir.join("bnb.html")) images = server.StaticDir("data/images", type="image/png") def source_js(self): return "text/javascript", self.server.source source_js.exposed = True MochiKit = server.StaticDir('MochiKit') #@turbogears.expose(format='json') #@turbogears.expose(format='json') ## @turbogears.expose(format='json') ## def key(self, player_id, keynum): ## self.sessionSocket().send(message(CMSG_KEY, int(player_id), int(keynum))) ## return dict() #@turbogears.expose(format='json') def close(self): self._close() return dict() class BnbRoot(server.NewHandler): application = BnbHandler()
Python
#!/usr/bin/env python """ bub-n-bros testing utility """ import autopath import py from pypy.translator.js.main import rpython2javascript from pypy.translator.js.modules.dom import document, window from pypy.translator.js.modules.mochikit import log, logWarning,\ createLoggingPane, logDebug, connect from pypy.translator.js.examples.bnb.bnb import exported_methods from pypy.translator.js import commproxy commproxy.USE_MOCHIKIT = True import time import os import sys def logKey(msg): pass class Stats(object): """ Class containing some statistics """ def __init__(self): self.n_received_inline_frames = 0 self.n_rendered_inline_frames = 0 self.n_rendered_dynamic_sprites = 0 self.fps = 0 self.starttime = 0.0 self.n_sprites = 0 def register_frame(self): self.n_rendered_inline_frames += 1 if self.n_rendered_inline_frames >= 10: next_time = time.time() self.fps = 10000/(next_time - self.starttime) self.n_rendered_inline_frames = 0 self.starttime = next_time stats = Stats() class Player(object): def __init__(self): self.id = -1 self.prev_count = 0 self.sessionid = "" player = Player() class SpriteManager(object): def __init__(self): self.sprites = {} self.filenames = {} self.all_sprites = {} self.frames = [] def add_icon(self, icon_code, filename): self.filenames[icon_code] = filename #self.sprite_queues[icon_code] = [] #self.used[icon_code] = [] # FIXME: Need to write down DictIterator once... #self.icon_codes.append(icon_code) def add_sprite(self, s, icon_code, x, y): #try: # img = self.sprite_queues[icon_code].pop() #except IndexError: stats.n_sprites += 1 img = document.createElement("img") img.src = self.filenames[icon_code] img.style.position = 'absolute' img.style.left = x + 'px' img.style.top = y + 'px' img.style.visibility = 'visible' document.getElementById("playfield").appendChild(img) try: self.sprites[s].style.visibility = "hidden" # FIXME: We should delete it except KeyError: self.sprites[s] = img return img def move_sprite(self, s, x, y): i = self.sprites[s] i.style.top = y + 'px' i.style.left = x + 'px' i.style.visibility = 'visible' def hide_sprite(self, s): i = self.sprites[s] i.style.visibility = "hidden" def start_clean_sprites(self): self.all_sprites = {} def show_sprite(self, s, icon_code, x, y): self.all_sprites[s] = 1 try: self.move_sprite(s, x, y) except KeyError: self.add_sprite(s, icon_code, x, y) def end_clean_sprites(self): for i in self.sprites: try: self.all_sprites[i] except KeyError: self.hide_sprite(i) def set_z_index(self, s_num, z): self.sprites[s_num].style.zIndex = z #def show_sprite(self, s): # i = self.sprites[s] # i.style.visibility = "visible" sm = SpriteManager() class KeyManager(object): def __init__(self): self.keymappings = {ord('D'):'right', ord('S'):'fire', ord('A'):'left', ord('W'):'up'} self.key_to_bnb_down = {'right':0, 'left':1, 'fire':3, 'up':2} self.key_to_bnb_up = {'right':4, 'left':5, 'fire':7, 'up':6} self.queue = [] def add_key_up(self, key): self.queue.append(self.key_to_bnb_up[key]) def add_key_down(self, key): self.queue.append(self.key_to_bnb_down[key]) def get_keys(self): retval = self.queue self.queue = [] return retval km = KeyManager() def appendPlayfield(msg): body = document.getElementsByTagName('body')[0] bgcolor = '#000' body.style.backgroundColor = bgcolor div = document.createElement("div") div.id = 'playfield' div.style.width = msg['width'] div.style.height = msg['height'] div.style.position = 'absolute' div.style.top = '0px' div.style.left = '0px' div.appendChild(document.createTextNode('foobar?')) #document.body.childNodes.insert(0, div) body.appendChild(div) def appendPlayfieldXXX(): bgcolor = '#000000' document.body.setAttribute('bgcolor', bgcolor) div = document.createElement("div") div.id = 'playfield' div.style.width = 500 div.style.height = 250 div.style.position = 'absolute' div.style.top = '0px' div.style.left = '0px' document.body.appendChild(div) def process_message(msg): if msg['type'] == 'def_playfield': appendPlayfield(msg) elif msg['type'] == 'def_icon': sm.add_icon(msg['icon_code'], msg['filename']) elif msg['type'] == 'ns': sm.add_sprite(msg['s'], msg['icon_code'], msg['x'], msg['y']) sm.set_z_index(msg['s'], msg['z']) elif msg['type'] == 'sm': sm.move_sprite(msg['s'], msg['x'], msg['y']) sm.set_z_index(msg['s'], msg['z']) elif msg['type'] == 'ds': sm.hide_sprite(msg['s']) elif msg['type'] == 'begin_clean_sprites': sm.start_clean_sprites() elif msg['type'] == 'clean_sprites': sm.end_clean_sprites() elif msg['type'] == 'show_sprite': sm.show_sprite(msg['s'], msg['icon_code'], msg['x'], msg['y']) elif msg['type'] == 'zindex': sm.set_z_index(msg['s'], msg['z']) #elif msg['type'] == 'ss': # sm.show_sprite(msg['s']) elif msg['type'] == 'player_icon' or msg['type'] == 'def_key' or \ msg['type'] == 'player_join' or msg['type'] == 'player_kill': pass #ignore else: logWarning('unknown message type: ' + msg['type']) def ignore(arg): pass ignore._annspecialcase_ = 'specialize:argtype(0)' def addPlayer(player_id): name = "player no. " + str(player_id) #name = "player no. %d" % player_id #File "/Users/eric/projects/pypy-dist/pypy/translator/js/jts.py", line 52, in lltype_to_cts # raise NotImplementedError("Type %r" % (t,)) # NotImplementedError: Type <StringBuilder> prev_player_id = player.id if player.id >= 0: exported_methods.remove_player(player.id, player.sessionid, ignore) player.id = -1 if player_id != prev_player_id: exported_methods.player_name(player_id, name, player.sessionid, ignore) exported_methods.add_player(player_id, player.sessionid, ignore) player.id = player_id def keydown(key): #c = chr(int(key.keyCode)).lower() #c = int(key.keyCode) key = key._event try: c = key.keyCode if c > ord('0') and c < ord('9'): addPlayer(int(chr(c))) #for i in km.keymappings: # log(str(i)) if c in km.keymappings: km.add_key_down(km.keymappings[c]) #else: except Exception, e: log(str(e)) def keyup(key): key = key._event c = key.keyCode if c > ord('0') and c < ord('9'): pass #don't print warning elif c in km.keymappings: km.add_key_up(km.keymappings[c]) else: logWarning('unknown keyup: ' + str(c)) #def ignore_dispatcher(msgs): # pass def bnb_dispatcher(msgs): s = ":".join([str(i) for i in km.get_keys()]) exported_methods.get_message(player.sessionid, player.id, s, bnb_dispatcher) render_frame(msgs) def render_frame(msgs): for msg in msgs['messages']: process_message(msg) stats.register_frame() document.title = str(stats.n_sprites) + " sprites " + str(stats.fps) def session_dispatcher(sessionid): player.sessionid = sessionid connect(document, 'onkeydown', keydown) connect(document, 'onkeyup', keyup) exported_methods.get_message(player.sessionid, player.id, "", bnb_dispatcher) def bnb(): createLoggingPane(True) log("keys: [0-9] to select player, [wsad] to walk around") exported_methods.initialize_session(session_dispatcher) def run_bnb(): from pypy.translator.js.examples.bnb.bnb import BnbRoot from pypy.translator.js.lib import server addr = ('', 7070) httpd = server.create_server(handler=BnbRoot, server_address=addr) httpd.source = rpython2javascript(sys.modules[__name__], ['bnb']) httpd.serve_forever() if __name__ == '__main__': run_bnb()
Python
""" example of (very simple) serialiser """ def serialise(obj): if isinstance(obj, str): return "S" + obj elif isinstance(obj, int): return "I" + str(obj) return "?" serialise._annspecialcase_ = "specialize:argtype(0)" def serialisetest(): return serialise("aaa") + serialise(3) + serialise(None)
Python
""" In this file we define all necessary stuff build around subprocess to run python console in it """ KILL_TIMEOUT = 300 TIMEOUT = 10 """ The idea behind is that we create xmlhttprequest immediataly and reply with new data (if available) or reply anyway after TIMEOUT """ import py import subprocess from Queue import Queue from py.__.green.greensock2 import autogreenlet, Timer, Interrupted,\ meetingpoint from py.__.green.pipe.fd import FDInput from py.magic import greenlet import time class Killed(Exception): pass class Interpreter(object): def __init__(self, python, timeout=TIMEOUT, kill_timeout=KILL_TIMEOUT): pipe = subprocess.Popen([python, "-u", "-i"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True, bufsize=0) self.pipe = pipe self.read_fd = FDInput(self.pipe.stdout.fileno(), close=False) self.pid = pipe.pid self.timeout = timeout #self.kill_timeout = kill_timeout self.giver, accepter = meetingpoint() autogreenlet(self.timeout_kill, accepter, kill_timeout) #self.last_activity = time.time() def timeout_kill(self, accepter, timeout): while 1: try: self.kill_timer = Timer(timeout) accepter.accept() self.kill_timer.stop() except Interrupted: self.close() return def timeout_read(self, fd, timeout): timer = Timer(timeout) try: data = fd.recv(10024) except Interrupted: data = None else: timer.stop() return data def write_only(self, to_write): if to_write is not None: self.giver.give(42) self.pipe.stdin.write(to_write) def interact(self, to_write=None): self.write_only(to_write) return self.timeout_read(self.read_fd, self.timeout) def close(self): self.pipe.stdin.close() # XXX: some sane way of doing wait here? (note that wait # is blocking, which means it eats all our clean interface) self.pipe.wait() __del__ = close class InterpreterManager(object): pass #class Sessions(object): # def __init__(self): # self.sessions = {} # def new_session(self, python="python"): # pipe = run_console(python) # self.sessions[pipe.pid] = pipe # return pipe.pid # def update_session(self, pid, to_write=None): # pipe = self.sessions[pid] # return interact(pipe, to_write) #def interact(pipe, to_write=None): # if to_write is not None: # pipe.stdin.write(to_write + "\n") # try: # return pipe.stdout.read() # except IOError: # time.sleep(.1) # return ""
Python
from pypy.translator.js.modules import dom from pypy.translator.js.modules.mochikit import log, createLoggingPane from pypy.translator.js.examples.console.console import exported_methods class Glob(object): def __init__(self): self.console_running = False self.next_console = "" self.text_to_show = [] self.pss = [] glob = Glob() def add_text_to_dom(txt): data_elem = dom.document.getElementById("data") if data_elem.childNodes: data = data_elem.childNodes[0].nodeValue + txt else: data = txt while data_elem.childNodes: data_elem.removeChild(data_elem.childNodes[0]) data_elem.appendChild(dom.document.createTextNode(data)) def add_text(txt, server_flag, fn=add_text_to_dom): if not server_flag: if txt.find("\n") != len(txt) - 1: if txt[-1] == '\n': txt = txt[:-1] lst = txt.split("\n") add_text_to_dom(lst[0] + "\n") glob.text_to_show += lst[1:] else: add_text_to_dom(txt) else: for ps in glob.pss: if glob.text_to_show: num = txt.find(ps) if txt.startswith(ps): txt = txt[len(ps):] add_text_to_dom(ps + glob.text_to_show.pop(0) + "\n") add_text(txt, True) return if txt.startswith("\n" + ps): txt = txt[len(ps) + 1:] add_text_to_dom(ps + glob.text_to_show.pop(0) + "\n") add_text(txt, True) return add_text_to_dom(txt) def create_text(txt): return dom.document.createTextNode(txt) def set_text(txt): data_elem = dom.document.getElementById("data") while data_elem.childNodes: data_elem.removeChild(data_elem.childNodes[0]) data_elem.appendChild(dom.document.createTextNode(txt)) def refresh_console(msg): inp_elem = dom.document.getElementById("inp") #inp_elem.disabled = False if msg[0] == "refresh": data = msg[1] if data: inp_elem.scrollIntoView() inp_elem.focus() exported_methods.refresh_empty(glob.sess_id, refresh_console) add_text(data, True) elif msg[0] == 'disconnected': inp_elem.disabled = True name_bar = dom.document.getElementById("namebar") name_bar.style.color = "red" text = name_bar.lastChild.nodeValue name_bar.removeChild(name_bar.lastChild) name_bar.appendChild(create_text(text + " [DEFUNCT]")) glob.console_running = False if glob.next_console: next = glob.next_console glob.next_console = "" load_console(next) def set_sessid(data): sessid = int(data[0]) help_msg = data[1] glob.pss = data[2:] glob.sess_id = sessid inp_elem = dom.document.getElementById("inp") inp_elem.disabled = False name_bar = dom.document.getElementById("namebar") name_bar.style.color = "black" name_bar.removeChild(name_bar.lastChild) name_bar.appendChild(create_text("Python console")) dom.document.getElementById("helpcontents").innerHTML = help_msg exported_methods.refresh_empty(sessid, refresh_console) def empty_callback(msg): inp_elem = dom.document.getElementById("inp") #inp_elem.disabled = False inp_elem.scrollIntoView() def keypressed(key): kc = key.keyCode if kc == ord("\r"): inp_elem = dom.document.getElementById("inp") cmd = inp_elem.value inp_elem.value = '' add_text(cmd + "\n", False) #if not cmd: # exported_methods.refresh(glob.sess_id, cmd, empty_callback) #else: exported_methods.refresh(glob.sess_id, cmd + "\n", refresh_console) def nothing(msg): pass def nothing2(msg): pass def cleanup_console(): inp_elem = dom.document.getElementById("inp") inp_elem.disabled = True set_text("") glob.text_to_show = [] # better safe than sorry exported_methods.kill_console(glob.sess_id, nothing2) def load_console(python="python"): if glob.console_running: cleanup_console() glob.next_console = python return inp_elem = dom.document.getElementById("inp") main = dom.document.getElementById("main") main.style.visibility = "visible" inp_elem.disabled = False inp_elem.focus() glob.console_running = True exported_methods.get_console(python, set_sessid) def add_snippet(snippet): add_text(snippet, False) exported_methods.refresh(glob.sess_id, snippet, refresh_console) def execute_snippet(name='python', number=3): exported_methods.execute_snippet(name, number, add_snippet) def console_onload(): #createLoggingPane(True) #inp_elem = dom.document.getElementById("inp") #inp_elem.focus() dom.document.onkeypress = keypressed #exported_methods.get_console("python", set_sessid)
Python
import py from pypy.translator.js.lib import server from pypy.translator.js.main import rpython2javascript from pypy.translator.js.lib.support import callback from pypy.translator.js import commproxy from pypy.translator.js.examples.console.session import Interpreter, Killed from pypy.translator.js.examples.console.docloader import DocLoader from py.__.green.server.httpserver import GreenHTTPServer from py.__.green.greensock2 import ConnexionClosed commproxy.USE_MOCHIKIT = True FUNCTION_LIST = ["load_console", "console_onload", "execute_snippet"] class Ignore(Exception): pass def js_source(): import client return rpython2javascript(client, FUNCTION_LIST) def line_split(ret, max_len): to_ret = [] for line in ret.split("\n"): if len(line) > max_len: to_ret += [line[i*max_len:(i+1)*max_len] for i in range(len(line)/max_len)] i = len(line)/max_len else: i = 0 to_ret.append(line[i*max_len:]) return "\n".join(to_ret) STATIC_DIR = py.path.local(__file__) for x in range(6): STATIC_DIR = STATIC_DIR.dirpath() STATIC_DIR = STATIC_DIR.join("compiled") DOCDIR = STATIC_DIR.dirpath().join("pypy", "doc", "play1") CONSOLES = ['python', 'pypy-c', 'pypy-c-thunk', 'pypy-c-taint', 'pypy-cli', 'pyrolog-c', 'pypy-c-jit'] class Sessions(object): def __init__(self): self.sessions = {} self.updating = {} testfile = py.path.local(__file__).dirpath().join("play1_snippets.py") self.docloader = DocLoader(docdir=DOCDIR, consoles=CONSOLES, testfile=testfile) def new_session(self, python="python"): if not py.path.local().sysfind(python): python = str(STATIC_DIR.join(python)) ip = Interpreter(python) self.sessions[ip.pid] = ip self.updating[ip.pid] = False return ip.pid def update_session(self, pid, to_write=None): ip = self.sessions[pid] if self.updating[pid]: ip.write_only(to_write) raise Ignore() self.updating[pid] = True ret = ip.interact(to_write) self.updating[pid] = False if not ret: return "" MAX_LEN = 80 return line_split(ret, MAX_LEN) def kill_session(self, pid): ip = self.sessions[pid] ip.pipe.stdin.close() del self.sessions[pid] del self.updating[pid] def get_ps(self, python): if python == 'python': return ['>>> ', '... '] if python.startswith('pypy'): return ['>>>> ', '.... '] if python == 'pyrolog-c': return ['>?-'] return [] # We hack here, cause in exposed methods we don't have global 'server' # state sessions = Sessions() class ExportedMethods(server.ExportedMethods): @callback(retval=[str]) def get_console(self, python="python"): retval = sessions.new_session(python) return [str(retval), sessions.docloader.get_html(python)] +\ sessions.get_ps(python) def _refresh(self, pid, to_write): try: return ["refresh", sessions.update_session(int(pid), to_write)] except (KeyError, IOError, Killed, ConnexionClosed): return ["disconnected"] except Ignore: return ["ignore"] @callback(retval=[str]) def refresh(self, pid=0, to_write=""): return self._refresh(pid, to_write) @callback(retval=[str]) def refresh_empty(self, pid=0): #print "Empty refresh %d" % int(pid) return self._refresh(pid, None) @callback(retval=str) def execute_snippet(self, name='aaa', number=3): return sessions.docloader.get_snippet(name, int(number)) + "\n" @callback() def kill_console(self, pid=0): try: sessions.kill_session(int(pid)) except KeyError: pass exported_methods = ExportedMethods() static_dir = py.path.local(__file__).dirpath().join("data") class Root(server.Collection): exported_methods = exported_methods index = server.FsFile(static_dir.join("console.html")) style_css = server.FsFile(static_dir.dirpath().dirpath().join("data"). join("style.css")) MochiKit = server.StaticDir('MochiKit') def source_js(self): if hasattr(self.server, 'source_console'): source = self.server.source_console else: source = js_source() self.server.source_console = source return "text/javascript", source source_js.exposed = True class Handler(server.NewHandler): application = Root() application.some = Root() application.other = Root() if __name__ == '__main__': addr = ('', 8007) httpd = server.create_server(server_address=addr, handler=Handler, server=GreenHTTPServer) httpd.serve_forever()
Python
""" Simple module for loading documentation of various pypy-cs from doc directory """ import py class DocLoader(object): def __init__(self, consoles, docdir, testfile): self.consoles = consoles self.docdir = py.path.local(docdir) assert self.docdir.check(dir=1) self.testfile = testfile assert self.testfile.check() self.htmls = {} self.snippets = {} self.load() def get_html(self, console): return self.htmls[console] def get_snippet(self, console, num): return str(self.snippets[console][num]) def load(self): def mangle_name(name): return name.replace("-", "_").replace(".", "_") def mangle(source): source = source.strip() del source.lines[0] return source.deindent() testmod = self.testfile.pyimport() for console in self.consoles: html = self.docdir.join(console + '.html').read() snip_class = getattr(testmod, 'AppTest_' + mangle_name(console)) snippets = [mangle(py.code.Source(getattr(snip_class, name))) for name in dir(snip_class) if name.startswith("test_snippet")] self.snippets[console] = snippets self.htmls[console] = html % tuple([str(i) for i in snippets])
Python
from pypy.conftest import gettestobjspace class AppTest_pypy_c(object): def setup_class(cls): cls.space = gettestobjspace(**{"objspace.std.withtproxy": True, "usemodules":("_stackless",)}) def test_snippet_1(self): from tputil import make_proxy history = [] def recorder(operation): history.append(operation) return operation.delegate() l = make_proxy(recorder, obj=[]) class AppTest_pypy_c_thunk(object): def setup_class(cls): cls.space = gettestobjspace(**{"objspace.name": 'thunk'}) def test_snippet_1(self): from __pypy__ import thunk def f(): print 'computing...' return 6*7 x = thunk(f) class AppTest_pypy_c_taint(object): def setup_class(cls): cls.space = gettestobjspace(**{'objspace.name': 'taint'}) def test_snippet_1(self): from __pypy__ import taint x = taint(6) class AppTest_pypy_cli(object): def setup_class(cls): cls.space = gettestobjspace(**{'usemodules': 'clr'}) def test_snippet_1(self): import clr ArrayList = clr.load_cli_class('System.Collections', 'ArrayList') obj = ArrayList() obj.Add(1) class AppTest_pyrolog_c(object): pass class AppTest_python(object): pass class AppTest_pypy_c_jit(object): def setup_class(cls): cls.space = gettestobjspace(**{'usemodules':('pypyjit',)}) def test_snippet_1(self): import time def f1(n): "Arbitrary test function." i = 0 x = 1 while i<n: j = 0 while j<=i: j = j + 1 x = x + (i&j) i = i + 1 return x def test_f1(): res = f1(211) print "running..." N = 5 start = time.time() for i in range(N): assert f1(211) == res end = time.time() print '%d iterations, time per iteration: %s' % (N, (end-start)/N) import pypyjit
Python
"""rpython javascript code""" from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc from pypy.translator.js.lib.support import callback from pypy.translator.js.modules import mochikit from pypy.translator.js.modules import dom class PingHandler(BasicExternal): """Server side code which handles javascript calls""" _render_xmlhttp = True @callback(retval={str:str}) def ping(self, ping_str="aa"): """Simply returns the string prefixed with a PONG""" return dict(response="PONG: %s" % ping_str) ping_handler = PingHandler() def jsping(): mochikit.logDebug("pinging") ping_handler.ping("PING", callback) def callback(data): mochikit.logDebug("Got response: " + data["response"]) log = dom.document.getElementById("log") mochikit.logDebug("got log element") try: s = "<p>" + data["response"] + "</p>" except KeyError: mochikit.logDebug("Can't find data") s = "<p>" + "Error" + "</p>" mochikit.logDebug("Adding: " + s) log.innerHTML += s mochikit.logDebug("added message") def doping_onclick(event): mochikit.logDebug("calling pinger") jsping() def ping_init(): mochikit.createLoggingPane(True) button = dom.document.getElementById("doping") button.onclick = doping_onclick mochikit.logDebug("Ping button setup") if __name__ == "__main__": # circular import from pypy.translator.js.examples.djangoping import client from pypy.translator.js.main import rpython2javascript print rpython2javascript(client, ["ping_init"])
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * urlpatterns = patterns('pypy.translator.js.examples.djangoping.views', (r"^ping.js$", "ping_js"), (r"^ping/$", "ping"), (r"^$", "index"), )
Python
# Django settings for djangoping project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = '' # 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. All choices can be found here: # http://www.postgresql.org/docs/current/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes # http://blogs.law.harvard.edu/tech/stories/storyReader$15 LANGUAGE_CODE = 'en-us' SITE_ID = 1 # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'z-n46o5v2gd^n2!tqlher5)w5!l@0em+d_o+-3qhdulg7qc_lk' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', ) ROOT_URLCONF = 'pypy.translator.js.examples.djangoping.urls' import os # grab a sister package to get its __file__ from pypy.translator.js.examples.djangoping import client TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates". # Always use forward slashes, even on Windows. os.path.join(os.path.dirname(client.__file__), "templates"), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', )
Python
"""Django python views""" from django.http import HttpResponse from django.shortcuts import render_to_response from pypy.translator.js.main import rpython2javascript import simplejson from pypy.translator.js.examples.djangoping import client def render_json_response(data): response = HttpResponse(mimetype="application/json") # response["Pragma"] = "no-cache" # response["Cache-Control"] = "no-cache, must-revalidate" # response["Expires"] = "Mon, 26 Jul 1997 05:00:00 GMT" simplejson.dump(data, response) return response def json(fn): def decorator(*args, **kwargs): data = fn(*args, **kwargs) return render_json_response(data) return decorator def index(request): return render_to_response("index.html", {}) @json def ping(request): ping_str = request.GET["ping_str"] return client.ping_handler.ping(ping_str) def ping_js(request): js_src = rpython2javascript(client, ["ping_init"]) response = HttpResponse(mimetype="text/javascript") response.write(js_src) return response
Python
#!/usr/bin/env python """ A basic Python console from your browser. This depends on MochiKit for proper quoting. You need to provide the files as ..jsdemo/MochiKit/*.js. (Symlinks are your friends.) Try to type: import time; time.sleep(2); print 'hi' """ import autopath import sys, os, cStringIO from cgi import parse_qs from pypy.translator.js.modules.dom import setTimeout, document, window from pypy.translator.js.modules.mochikit import connect, disconnect from pypy.rpython.ootypesystem.bltregistry import MethodDesc, BasicExternal from pypy.translator.js import commproxy from pypy.rpython.extfunc import genericcallable from pypy.translator.js.lib import support from pypy.translator.js.lib import server commproxy.USE_MOCHIKIT = True from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from SocketServer import ThreadingMixIn import time HTML_PAGE = """ <html> <head> <title>Example</title> <script type="text/javascript" src="jssource"></script> <script src="http://mochikit.com/MochiKit/MochiKit.js" type="text/javascript"></script> </head> <body onload="setup_page()"> <h3>Console</h3> <p>Note that a default timeout for the console is 5 minutes, after that time console just dies and stops responding</p> <div id="data"></div> <input id="inp" size="100" type="text" autocomplete="off"/> </body> </html> """ httpd = None def callback(data): inp_elem = document.getElementById("inp") inp_elem.disabled = False answer = data.get('answer', '') add_text(answer) inp_elem.focus() def add_text(text): data_elem = document.getElementById("data") lines = text.split('\n') lines.pop() for line in lines: pre = document.createElement('pre') pre.style.margin = '0px' pre.appendChild(document.createTextNode(line)) data_elem.appendChild(pre) class Storage(object): def __init__(self): self.level = 0 self.cmd = "" storage = Storage() def keypressed(key): kc = key._event.keyCode if kc == ord("\r"): inp_elem = document.getElementById("inp") cmd = inp_elem.value if storage.level == 0: add_text(">>> %s\n" % (cmd,)) else: add_text("... %s\n" % (cmd,)) inp_elem.value = '' if cmd: storage.cmd += cmd + "\n" if cmd.endswith(':'): storage.level = 1 elif storage.level == 0 or cmd == "": if (not storage.level) or (not cmd): inp_elem.disabled = True httpd.some_callback(storage.cmd, callback) storage.cmd = "" storage.level = 0 def setup_page(): connect(document, 'onkeypress', keypressed) document.getElementById("inp").focus() class Server(HTTPServer, BasicExternal): # Methods and signatures how they are rendered for JS _methods = { 'some_callback' : MethodDesc([('cmd', str), ('callback', genericcallable([{str:str}]))], {str:str}) } _render_xmlhttp = True def __init__(self, *args, **kwargs): HTTPServer.__init__(self, *args, **kwargs) self.source = None self.locals = {} class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): path = self.path if '?' in path: i = path.index('?') else: i = len(path) kwds = parse_qs(path[i+1:]) path = path[:i].split("/") if not path[0]: del path[0] if not path: path = [''] cmd = path[0] args = path[1:] method_to_call = getattr(self, "run_" + cmd, None) if method_to_call is None: self.send_error(404, "File %r not found" % (self.path,)) else: method_to_call(*args, **kwds) do_POST = do_GET def run_(self): self.run_index() def run_index(self): self.serve_data("text/html", HTML_PAGE) def run_MochiKit(self, filename): assert filename in os.listdir('MochiKit') pathname = os.path.join('MochiKit', filename) f = open(pathname, 'r') data = f.read() f.close() self.serve_data("text/javascript", data) def run_some_callback(self, cmd=[""]): cmd = cmd[0] self.server.last_activity = time.time() if cmd: buf = cStringIO.StringIO() out1 = sys.stdout err1 = sys.stderr try: sys.stdout = sys.stderr = buf try: exec compile(cmd, '?', 'single') in self.server.locals except Exception: import traceback traceback.print_exc() finally: sys.stdout = out1 sys.stderr = err1 answer = buf.getvalue() else: answer = "" self.serve_data("text/json", repr({'answer': answer})) def run_jssource(self): if self.server.source: source = self.server.source else: source = support.js_source([setup_page]) self.server.source = source self.serve_data("text/javascript", source) def serve_data(self, content_type, data): self.send_response(200) self.send_header("Content-type", content_type) self.send_header("Content-length", len(data)) self.send_header('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT') self.send_header('Last-Modified', time.strftime("%a, %d %b %Y %H:%M:%S GMT")) self.send_header('Cache-Control', 'no-cache, must-revalidate') self.send_header('Cache-Control', 'post-check=0, pre-check=0') self.send_header('Pragma', 'no-cache') self.end_headers() self.wfile.write(data) def build_http_server(server_address=('', 8001)): global httpd httpd = Server(server_address, RequestHandler) print 'http://127.0.0.1:%d' % (server_address[1],) def _main(address=('', 8001)): build_http_server(server_address=address) httpd.serve_forever() if __name__ == '__main__': _main()
Python
#!/usr/bin/env python """ the mandatory guestbook example accompanies the pypyp/doc/js/webapps_with_pypy.txt document, serves as a simple example to show how to go about writing a pypy web application """ import autopath from pypy.translator.js.lib import server from pypy.translator.js.lib.support import callback from pypy.translator.js.main import rpython2javascript import py import shelve class ExportedMethods(server.ExportedMethods): """ this provides the methods that are exposed to the client ('AJAX' stuff) """ def __init__(self): super(ExportedMethods, self).__init__() self._db = shelve.open('messages') self._db.setdefault('messages', []) # callback makes that a method gets exposed, it can get 2 arguments, # 'ret' for specifying the return value, and 'args' for specifying the # argument types @callback(retval=[str]) def get_messages(self): return self._db['messages'] @callback(retval=str) def add_message(self, name='', message=''): text = '%s says: %s' % (name, message) m = self._db['messages'] m.append(text) self._db['messages'] = m return text exported_methods = ExportedMethods() FUNCTION_LIST = ['init_guestbook', 'add_message'] def guestbook_client(): """ compile the rpython guestbook_client code to js """ import guestbook_client return rpython2javascript(guestbook_client, FUNCTION_LIST) class Handler(server.Handler): """ a BaseHTTPRequestHandler subclass providing the HTTP methods """ # provide the exported methods exported_methods = exported_methods # a simple html page def index(self): html = """ <html> <head> <title>Guestbook</title> <script type="text/javascript" src="/guestbook.js"></script> </head> <body onload="init_guestbook()"> <h2>Guestbook</h2> <div id="messages"> <!-- this will be filled from javascript --> </div> <form action="." method="post" onsubmit="add_message(this); return false"> name: <input type="text" name="name" id="name" /><br /> message:<br /> <textarea name="message" id="message"></textarea><br /> <input type="submit" /> </form> </body> </html> """ return 'text/html', html index.exposed = True # the (generated) javascript def guestbook_js(self): if hasattr(self.server, 'source'): source = self.server.source else: source = guestbook_client() self.server.source = source return "text/javascript", source guestbook_js.exposed = True if __name__ == '__main__': addr = ('', 8008) httpd = server.create_server(server_address=addr, handler=Handler) httpd.serve_forever()
Python
#!/usr/bin/env python """ This is script which collects all the demos and run them when needed """ import autopath from pypy.translator.js.lib import server from pypy.translator.js.lib.support import callback from pypy.rpython.ootypesystem.bltregistry import described from pypy.translator.js.main import rpython2javascript from pypy.translator.js.examples.console import console from py.__.green.server.httpserver import GreenHTTPServer import os import py FUNCTION_LIST = ['bnb_redirect'] TIMEOUT = 300 pids = [] def js_source(function_list): import over_client return rpython2javascript(over_client, FUNCTION_LIST) static_dir = py.path.local(__file__).dirpath().join("data") class Root(server.Collection): index = server.FsFile(static_dir.join("index.html")) style_css = server.FsFile(static_dir.join("style.css"), content_type="text/css") terminal = server.Static(static_dir.join("terminal.html")) console = console.Root() py_web1_png = server.FsFile(static_dir.join("py-web1.png"), content_type="image/png") def source_js(self): if hasattr(self.server, 'source'): source = self.server.source else: source = js_source(FUNCTION_LIST) self.server.source = source return "text/javascript", source source_js.exposed = True def bnb(self): return ''' <html> <head> <script src="source.js"></script> </head> <body onload="bnb_redirect()"> </body> </html>''' bnb.exposed = True def handle_error(self, exc, e_value, tb): import traceback tb_formatted = '\n'.join(traceback.format_tb(tb)) + \ "%s: %s" % (exc, e_value) log_file = open("/tmp/play1_error_log", "a") log_file.write(tb_formatted) log_file.close() print tb_formatted class Handler(server.NewHandler): application = Root() error_message_format = static_dir.join('error.html').read() #console = server.Static(os.path.join(static_dir, "launcher.html")) if __name__ == '__main__': try: addr = ('', 8008) httpd = server.create_server(server_address=addr, handler=Handler, server=GreenHTTPServer) httpd.serve_forever() except KeyboardInterrupt: for pid in pids: # eventually os.kill stuff os.kill(pid, 15) os.waitpid(pid, 0)
Python
""" Client side of overmind.py """ from pypy.translator.js.modules import dom def callback(port): hname = dom.window.location.hostname dom.window.location.assign("http://%s:%d" % (hname, port)) def bnb_redirect(): loc = dom.window.location new_loc = loc.protocol + "//" + loc.hostname + ":7070" loc.assign(new_loc)
Python
""" self cloning, automatic path configuration copy this into any subdirectory of pypy from which scripts need to be run, typically all of the test subdirs. The idea is that any such script simply issues import autopath and this will make sure that the parent directory containing "pypy" is in sys.path. If you modify the master "autopath.py" version (in pypy/tool/autopath.py) you can directly run it which will copy itself on all autopath.py files it finds under the pypy root directory. This module always provides these attributes: pypydir pypy root directory path this_dir directory where this autopath.py resides """ def __dirinfo(part): """ return (partdir, this_dir) and insert parent of partdir into sys.path. If the parent directories don't have the part an EnvironmentError is raised.""" import sys, os try: head = this_dir = os.path.realpath(os.path.dirname(__file__)) except NameError: head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) while head: partdir = head head, tail = os.path.split(head) if tail == part: break else: raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) pypy_root = os.path.join(head, '') try: sys.path.remove(head) except ValueError: pass sys.path.insert(0, head) munged = {} for name, mod in sys.modules.items(): if '.' in name: continue fn = getattr(mod, '__file__', None) if not isinstance(fn, str): continue newname = os.path.splitext(os.path.basename(fn))[0] if not newname.startswith(part + '.'): continue path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') if path.startswith(pypy_root) and newname != part: modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) if newname != '__init__': modpaths.append(newname) modpath = '.'.join(modpaths) if modpath not in sys.modules: munged[modpath] = mod for name, mod in munged.iteritems(): if name not in sys.modules: sys.modules[name] = mod if '.' in name: prename = name[:name.rfind('.')] postname = name[len(prename)+1:] if prename not in sys.modules: __import__(prename) if not hasattr(sys.modules[prename], postname): setattr(sys.modules[prename], postname, mod) return partdir, this_dir def __clone(): """ clone master version of autopath.py into all subdirs """ from os.path import join, walk if not this_dir.endswith(join('pypy','tool')): raise EnvironmentError("can only clone master version " "'%s'" % join(pypydir, 'tool',_myname)) def sync_walker(arg, dirname, fnames): if _myname in fnames: fn = join(dirname, _myname) f = open(fn, 'rwb+') try: if f.read() == arg: print "checkok", fn else: print "syncing", fn f = open(fn, 'w') f.write(arg) finally: f.close() s = open(join(pypydir, 'tool', _myname), 'rb').read() walk(pypydir, sync_walker, s) _myname = 'autopath.py' # set guaranteed attributes pypydir, this_dir = __dirinfo('pypy') if __name__ == '__main__': __clone()
Python
""" rpython guestbook client-side code this code can be tested in CPython, but will also be converted to JavaScript to provide the client-side functionality for the guestbook example """ from pypy.translator.js.modules import dom from pypy.translator.js.examples.guestbook import exported_methods def _get_messages_callback(messages): for message in messages: add_html_message(message) def init_guestbook(): exported_methods.get_messages(_get_messages_callback) def _add_message_callback(message): add_html_message(message) def add_message(): doc = dom.window.document name = doc.getElementById('name').value message = doc.getElementById('message').value exported_methods.add_message(name, message, _add_message_callback) def add_html_message(text=''): doc = dom.window.document div = doc.getElementById('messages') msgdiv = doc.createElement('div') msgdiv.style.border = '1px solid black' msgdiv.style.margin = '1em' msgdiv.appendChild(doc.createTextNode(text)) div.appendChild(msgdiv)
Python
#!/usr/bin/env python """ the mandatory guestbook example accompanies the pypyp/doc/js/webapps_with_pypy.txt document, serves as a simple example to show how to go about writing a pypy web application """ import autopath from pypy.translator.js.lib import server from pypy.translator.js.lib.support import callback from pypy.translator.js.main import rpython2javascript import py import shelve class ExportedMethods(server.ExportedMethods): """ this provides the methods that are exposed to the client ('AJAX' stuff) """ def __init__(self): super(ExportedMethods, self).__init__() self._db = shelve.open('messages') self._db.setdefault('messages', []) # callback makes that a method gets exposed, it can get 2 arguments, # 'ret' for specifying the return value, and 'args' for specifying the # argument types @callback(retval=[str]) def get_messages(self): return self._db['messages'] @callback(retval=str) def add_message(self, name='', message=''): text = '%s says: %s' % (name, message) m = self._db['messages'] m.append(text) self._db['messages'] = m return text exported_methods = ExportedMethods() FUNCTION_LIST = ['init_guestbook', 'add_message'] def guestbook_client(): """ compile the rpython guestbook_client code to js """ import guestbook_client return rpython2javascript(guestbook_client, FUNCTION_LIST) class Handler(server.Handler): """ a BaseHTTPRequestHandler subclass providing the HTTP methods """ # provide the exported methods exported_methods = exported_methods # a simple html page def index(self): html = """ <html> <head> <title>Guestbook</title> <script type="text/javascript" src="/guestbook.js"></script> </head> <body onload="init_guestbook()"> <h2>Guestbook</h2> <div id="messages"> <!-- this will be filled from javascript --> </div> <form action="." method="post" onsubmit="add_message(this); return false"> name: <input type="text" name="name" id="name" /><br /> message:<br /> <textarea name="message" id="message"></textarea><br /> <input type="submit" /> </form> </body> </html> """ return 'text/html', html index.exposed = True # the (generated) javascript def guestbook_js(self): if hasattr(self.server, 'source'): source = self.server.source else: source = guestbook_client() self.server.source = source return "text/javascript", source guestbook_js.exposed = True if __name__ == '__main__': addr = ('', 8008) httpd = server.create_server(server_address=addr, handler=Handler) httpd.serve_forever()
Python
#
Python
#!/usr/bin/env python """ This is script which collects all the demos and run them when needed """ import autopath from pypy.translator.js.lib import server from pypy.translator.js.lib.support import callback from pypy.rpython.ootypesystem.bltregistry import described from pypy.translator.js.main import rpython2javascript from pypy.translator.js.examples.console import console from py.__.green.server.httpserver import GreenHTTPServer import os import py FUNCTION_LIST = ['bnb_redirect'] TIMEOUT = 300 pids = [] def js_source(function_list): import over_client return rpython2javascript(over_client, FUNCTION_LIST) static_dir = py.path.local(__file__).dirpath().join("data") class Root(server.Collection): index = server.FsFile(static_dir.join("index.html")) style_css = server.FsFile(static_dir.join("style.css"), content_type="text/css") terminal = server.Static(static_dir.join("terminal.html")) console = console.Root() py_web1_png = server.FsFile(static_dir.join("py-web1.png"), content_type="image/png") def source_js(self): if hasattr(self.server, 'source'): source = self.server.source else: source = js_source(FUNCTION_LIST) self.server.source = source return "text/javascript", source source_js.exposed = True def bnb(self): return ''' <html> <head> <script src="source.js"></script> </head> <body onload="bnb_redirect()"> </body> </html>''' bnb.exposed = True def handle_error(self, exc, e_value, tb): import traceback tb_formatted = '\n'.join(traceback.format_tb(tb)) + \ "%s: %s" % (exc, e_value) log_file = open("/tmp/play1_error_log", "a") log_file.write(tb_formatted) log_file.close() print tb_formatted class Handler(server.NewHandler): application = Root() error_message_format = static_dir.join('error.html').read() #console = server.Static(os.path.join(static_dir, "launcher.html")) if __name__ == '__main__': try: addr = ('', 8008) httpd = server.create_server(server_address=addr, handler=Handler, server=GreenHTTPServer) httpd.serve_forever() except KeyboardInterrupt: for pid in pids: # eventually os.kill stuff os.kill(pid, 15) os.waitpid(pid, 0)
Python
from setuptools import setup, find_packages from turbogears.finddata import find_package_data import os svninfo = os.popen('svn info rpython2javascript').read().split() version = int(svninfo[svninfo.index('Revision:') + 1]) setup( name="rpython2javascript", version="0.%d" % version, description="RPython to JavaScript translator", #description_long="""This is a derivative of the PyPy project. Some words about RPython can be found at http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html#restricted-python""", author="PyPy developers, Maciek Fijalkowski, Eric van Riet Paap", author_email="pypy-dev@codespeak.net", url="http://codespeak.net/pypy", download_url="http://codespeak.net/~ericvrp/rpython2javascript/", license="MIT", install_requires = [ "TurboGears >= 0.9a6", ], #scripts = [ # "start-topl.py" #], zip_safe=False, packages=find_packages(), package_data=find_package_data( where='rpython2javascript', package='rpython2javascript', only_in_packages=False, exclude='*.pyc *~ .* *.bak *.png *.gif *.jpg *.dot *.pdf *.txt *.html *.log *.graffle *.dump *.rdf *.ttf'.split()), entry_points=""" [turbogears.command] js = rpython2javascript.pypy.translator.js.turbogears.commandjs:JsCommand [python.templating.engines] asjavascript = rpython2javascript.pypy.translator.js.turbogears.templateplugin:TemplatePlugin [turbogears.widgets] RPyJSSource = rpython2javascript.pypy.translator.js.turbogears.widgets """, #keywords = [ # # Use keywords if you'll be adding your package to the # # Python Cheeseshop # # # if this has widgets, uncomment the next line # # 'turbogears.widgets', # # # if this has a tg-admin command, uncomment the next line # # 'turbogears.command', # # # if this has identity providers, uncomment the next line # # 'turbogears.identity.provider', # # # If this is a template plugin, uncomment the next line # # 'python.templating.engines', # # # If this is a full application, uncomment the next line # # 'turbogears.app', #], classifiers = [ 'Development Status :: 3 - Alpha', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', #'Framework :: TurboGears', # if this is an application that you'll distribute through # the Cheeseshop, uncomment the next line # 'Framework :: TurboGears :: Applications', # if this is a package that includes widgets that you'll distribute # through the Cheeseshop, uncomment the next line # 'Framework :: TurboGears :: Widgets', ], #test_suite = 'nose.collector', )
Python
import cherrypy from rpython2javascript.pypy.translator.js.main import rpython2javascript class TemplatePlugin: def __init__(self, extra_vars_func=None, options=None): """The standard constructor takes an 'extra_vars_func', which is a callable that is called for additional variables with each rendering. Options is a dictionary that provides options specific to template engines (encoding, for example). The options should be prefixed with the engine's scheme name to allow the same dictionary to be passed in to multiple engines without ill effects.""" pass # the template name will be in python "dot" notation # eg "package1.package2.templatename". It will *not* # have the extension on it. You may want to cache the # template. This method is only called directly if a # template is specified in turbogears.view.baseTemplates. # You might call this yourself from render. # This doesn't *have* to return anything, but # existing implementations return a template class. # (this does not necessarily make sense for all template # engines, though, which is why no return value is # required.) def load_template(self, templatename): "Find a template specified in python 'dot' notation." pass # info is the dictionary returned by the user's controller. # format may only make sense for template engines that can # produce different styles of output based on the same # template. # fragment is used if there are special rules about rendering # a part of a page (don't include headers and declarations). # template is the name of the template to render. # You should incorporate extra_vars_func() output # into the namespace in your template if at all possible. def render(self, info, format="html", fragment=False, template=None): "Renders the template to a string using the provided info." cherrypy.response.headers["Content-Type"] = "text/javascript" return 'alert("JavascriptCodeGoesHere")' # This method is not required for most uses of templates. # It is specifically used for efficiently inserting widget # output into Kid pages. It does the same thing render does, # except the output is a generator of ElementTree Elements # rather than a string. def transform(self, info, template): "Render the output to Elements" pass
Python
#!/usr/bin/env python """Command-line user interface for rpython2javascript.""" import optparse from rpython2javascript.pypy.translator.js.main import rpython2javascript_main class JsCommand: "Translate RPython code to Javascript via command-line interface." desc = "Translate RPython to Javascript" name = None package = None __version__ = "0.2" __author__ = "Eric van Riet Paap" __email__ = "eric@vanrietpaap.nl" __copyright__ = "Copyright 2006 Eric van Riet Paap" __license__ = "MIT" def __init__(self, *args, **kwargs): parser = optparse.OptionParser(usage=""" %prog [options] <command> Available commands: module <function names> Translate RPython functions in a module to Javascript """, version="%prog " + self.__version__) self.parser = parser def run(self): (options, args) = self.parser.parse_args() if not args: self.parser.error("No command specified") #self.options = options #command, args = args[0], args[1:] #print 'JsCommand:', command, args rpython2javascript_main(args) def main(): tool = JsCommand() tool.run() if __name__ == '__main__': main()
Python
#!/usr/bin/env python """Command-line user interface for rpython2javascript.""" import optparse from rpython2javascript.pypy.translator.js.main import rpython2javascript_main class JsCommand: "Translate RPython code to Javascript via command-line interface." desc = "Translate RPython to Javascript" name = None package = None __version__ = "0.2" __author__ = "Eric van Riet Paap" __email__ = "eric@vanrietpaap.nl" __copyright__ = "Copyright 2006 Eric van Riet Paap" __license__ = "MIT" def __init__(self, *args, **kwargs): parser = optparse.OptionParser(usage=""" %prog [options] <command> Available commands: module <function names> Translate RPython functions in a module to Javascript """, version="%prog " + self.__version__) self.parser = parser def run(self): (options, args) = self.parser.parse_args() if not args: self.parser.error("No command specified") #self.options = options #command, args = args[0], args[1:] #print 'JsCommand:', command, args rpython2javascript_main(args) def main(): tool = JsCommand() tool.run() if __name__ == '__main__': main()
Python
from turbogears.widgets.base import JSSource, CoreWD, RenderOnlyWD class RPyJSSource(JSSource): def __init__(self, src, location=None): #print 'RPyJSSource: python:', src mod = 'RPyJSSourceTmp.py' f = open(mod, 'w') f.write(src) f.close() function_names = [] from rpython2javascript.pypy.translator.js.main import rpython2javascript_main jssrc = rpython2javascript_main([mod] + function_names) #print 'RPyJSSource: javascript:', jssrc super(RPyJSSource, self).__init__(jssrc) class RPyJSSourceDesc(CoreWD, RenderOnlyWD): name = "RPyJSSource" for_widget = RPyJSSource("def main(): return 42")
Python
from pypy.translator.gensupp import NameManager #from pypy.translator.js.optimize import is_optimized_function class JavascriptNameManager(NameManager): def __init__(self, db): NameManager.__init__(self) self.db = db self.reserved = {} #http://javascript.about.com/library/blreserved.htm reserved_words = ''' abstract as boolean break byte case catch char class continue const debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface is long namespace native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof use var void volatile while with alert ''' for name in reserved_words.split(): self.reserved[name] = True #http://javascript.about.com/library/blclassobj.htm # XXX WAAAHHH!!! IE alert :( there are a lot of objects here that are # _not_ in standard JS, see # http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.5/reference/ predefined_classes_and_objects = ''' Anchor anchors Applet applets Area Array Body Button Checkbox Date document Error EvalError FileUpload Form forms frame frames Function Hidden History history Image images Link links location Math MimeType mimetypes navigator Number Object Option options Password Plugin plugins Radio RangeError ReferenceError RegExp Reset screen Script Select String Style StyleSheet Submit SyntaxError Text Textarea TypeError URIError window ''' for name in predefined_classes_and_objects.split(): self.reserved[name] = True #http://javascript.about.com/library/blglobal.htm global_properties_and_methods = ''' _content closed Components controllers crypto defaultstatus directories document frames history innerHeight innerWidth length location locationbar menubar name navigator opener outerHeight outerWidth pageXOffset pageYOffset parent personalbar pkcs11 prompter screen screenX screenY scrollbars scrollX scrollY self statusbar toolbar top window ''' for name in global_properties_and_methods.split(): self.reserved[name] = True self.make_reserved_names(' '.join(self.reserved)) self.predefined = set(predefined_classes_and_objects) #def uniquename(self, name, lenmax=0): # return NameManager.uniquename(self, , lenmax) def ensure_non_reserved(self, name): while name in self.reserved: name += '_' return name
Python
""" Some helpers """ from pypy.translator.js.modules.dom import document def escape(s): #return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"). \ # replace("'", "\\'").replace(" ", "&nbsp;").replace("\n", "<br/>") return s def create_debug_div(): debug_div = document.createElement("div") debug_div.setAttribute("id", "debug_div") # XXX attach it somewhere... #body = document.getElementsByTagName('body')[0] document.childNodes[0].childNodes[1].appendChild(debug_div) return debug_div def __show_traceback(tb, exc): debug_div = document.getElementById("debug_div") if not debug_div: # create div here debug_div = create_debug_div() pre_div = document.createElement("pre") pre_div.style.color = "#FF0000" debug_div.appendChild(pre_div) txt = document.createTextNode("") pre_div.appendChild(txt) for tb_entry in tb[1:]: # list of tuples... fun_name, args, filename, lineno = tb_entry # some source maybe? or so? line1 = escape("%s %s" % (fun_name, args)) line2 = escape(" %s: %s\n" % (filename, lineno)) txt.nodeValue += line1 + '\n' + line2 txt.nodeValue += str(exc) __show_traceback.explicit_traceback = True
Python
""" opcode definitions """ from pypy.translator.oosupport.metavm import PushArg, PushAllArgs, StoreResult,\ InstructionList, New, GetField, MicroInstruction, RuntimeNew, PushPrimitive from pypy.translator.oosupport.metavm import _GetFieldDispatcher, _SetFieldDispatcher, \ _CallDispatcher, _MethodDispatcher, SetField from pypy.translator.js.metavm import IsInstance, Call, CallMethod,\ CopyName, CastString, _Prefix, _CastFun, _NotImplemented, CallBuiltin,\ CallBuiltinObject, GetBuiltinField, SetBuiltinField, IndirectCall,\ CallExternalObject, SetExternalField, _CastMethod, _LoadConst,\ DiscardStack, CheckLength, fix_opcodes from pypy.translator.js.jsbuiltin import Builtins from pypy.rpython.ootypesystem import ootype DoNothing = [] from pypy.translator.js.log import log class_map = { 'Call' : Call, 'CallMethod' : CallMethod, 'CallBuiltinObject' : CallBuiltinObject, 'CallBuiltin' : CallBuiltin, 'GetBuiltinField' : GetBuiltinField, 'GetField' : GetField, 'SetField' : SetField, 'SetBuiltinField' : SetBuiltinField, 'CallExternalObject' : CallExternalObject, 'SetExternalField' : SetExternalField, } opcodes = {'int_mul': '*', 'int_add': '+', 'int_sub': '-', 'int_sub_ovf': '-', # XXX overflow 'int_floordiv': '/', 'int_mod': '%', 'int_mod_ovf': '%', # XXX: what's that? 'int_mod_zer': '%', # XXX: fix zero stuff 'int_and': '&', 'int_or': '|', 'int_xor': '^', 'int_lshift': '<<', 'int_lshift_ovf': '<<', # XXX overflow 'int_rshift': '>>', 'int_rshift_ovf': '>>', # XXX overflow 'int_lt': '<', 'int_le': '<=', 'int_eq': '==', 'int_ne': '!=', 'int_ge': '>=', 'int_gt': '>', 'uint_mul': '*', 'uint_add': '+', 'uint_sub': '-', 'uint_floordiv': '/', 'uint_mod': '%', 'uint_and': '&', 'uint_or': '|', 'uint_xor': '^', 'uint_lshift': '<<', 'uint_rshift': '>>', 'uint_lt': '<', 'uint_le': '<=', 'uint_eq': '==', 'uint_ne': '!=', 'uint_ge': '>=', 'uint_gt': '>', 'unichar_lt': '<', 'unichar_le': '<=', 'unichar_eq': '==', 'unichar_ne': '!=', 'unichar_ge': '>=', 'unichar_gt': '>', 'char_lt': '<', 'char_le': '<=', 'char_eq': '==', 'char_ne': '!=', 'char_ge': '>=', 'char_gt': '>', 'float_mul': '*', 'float_add': '+', 'float_sub': '-', 'float_truediv': '/', 'float_lt': '<', 'float_le': '<=', 'float_eq': '==', 'float_ne': '!=', 'float_ge': '>=', 'float_gt': '>', 'ptr_eq': '==', 'ptr_ne': '!=', 'bool_not': [PushAllArgs,_Prefix('!')], 'int_neg': [PushAllArgs,_Prefix('-')], 'int_invert': [PushAllArgs,_Prefix('~')], 'float_neg': [PushAllArgs,_Prefix('-')], 'float_pow': [PushAllArgs,_CastFun('Math.pow',2)], 'int_abs': [PushAllArgs,_CastFun('Math.abs',1)], 'float_abs': [PushAllArgs,_CastFun('Math.abs',1)], 'int_is_true': [PushAllArgs,_Prefix('!!')], 'uint_is_true': [PushAllArgs,_Prefix('!!')], 'float_is_true': [PushAllArgs,_Prefix('!!')], 'is_true': [PushAllArgs,_Prefix('!!')], 'direct_call' : [_CallDispatcher(Builtins, class_map)], 'indirect_call' : [IndirectCall], 'same_as' : CopyName, 'new' : [New], 'runtimenew' : [RuntimeNew], 'instanceof' : [IsInstance], #'subclassof' : [IsSubclassOf], # objects 'oosetfield' : [_SetFieldDispatcher(Builtins, class_map)], 'oogetfield' : [_GetFieldDispatcher(Builtins, class_map)], 'oosend' : [_MethodDispatcher(Builtins, class_map)], 'ooupcast' : CopyName, 'oodowncast' : CopyName, 'oononnull' : [PushAllArgs,_Prefix('!!')], 'oostring' : [PushArg(0),CastString], 'ooparse_int' : [PushAllArgs,_CastFun("parseInt",2)], 'ooparse_float' : [PushAllArgs,_CastFun("parseFloat",1)], 'oois' : '===', 'cast_bool_to_int': CopyName, 'cast_bool_to_uint': CopyName, 'cast_bool_to_float': CopyName, 'cast_char_to_int': [PushAllArgs,_LoadConst(0),_CastMethod("charCodeAt",1)], 'cast_unichar_to_int': [PushAllArgs,_LoadConst(0),_CastMethod("charCodeAt",1)], 'cast_int_to_char': [PushAllArgs,_CastFun("String.fromCharCode",1)], 'cast_int_to_unichar': [PushAllArgs,_CastFun("String.fromCharCode",1)], 'cast_int_to_uint': CopyName, 'cast_int_to_float': CopyName, 'cast_int_to_longlong': CopyName, 'cast_uint_to_int': CopyName, 'cast_uint_to_float': CopyName, 'cast_float_to_int': [PushAllArgs,_CastFun("Math.floor",1)], 'cast_float_to_uint': [PushAllArgs,_CastFun("Math.floor",1)], 'cast_float_to_longlong': [PushAllArgs,_CastFun("Math.floor",1)], 'truncate_longlong_to_int': CopyName, 'debug_assert' : DoNothing, 'resume_point' : DoNothing, 'is_early_constant': [PushPrimitive(ootype.Bool, False)], } fix_opcodes(opcodes)
Python
""" genjs class definition """ from pypy.translator.cli.node import Node from pypy.translator.cli.cts import CTS class Class(Node): def __init__(self, db, classdef): self.db = db self.cts = db.genoo.TypeSystem(db) self.classdef = classdef self.name = classdef._name.replace('.', '_')#[-1] self.real_name = classdef._name if not self.is_root(classdef): self.parent = self.db.pending_class(classdef._superclass) self.order = self.parent.order + 1 else: self.order = 0 def __hash__(self): return hash(self.classdef) def __eq__(self, other): return self.classdef == other.classdef def __cmp__(self, other): return cmp(self.order, other.order) def is_root(classdef): return classdef._superclass is None is_root = staticmethod(is_root) def get_name(self): return self.name def render(self, ilasm): if self.is_root(self.classdef) or self.name == 'Object': return if self.db.class_name(self.classdef) is not None: return # already rendered self.ilasm = ilasm ilasm.begin_function(self.name, []) # we need to copy here all the arguments self.copy_class_attributes(ilasm) ilasm.end_function() # begin to_String method ilasm.begin_method("toString", self.name, []) ilasm.load_str("'<%s object>'" % self.real_name) ilasm.ret() ilasm.end_function() #for f_name, (f_type, f_default) in self.classdef._fields.iteritems(): # cts_type = self.cts.lltype_to_cts(f_type) #if cts_type != 'void': # ilasm.field(f_name, cts_type) if not self.is_root(self.classdef): basename = self.basename(self.classdef._superclass._name) if basename != 'Root': ilasm.inherits(self.name, basename) for m_name, m_meth in self.classdef._methods.iteritems(): graph = getattr(m_meth, 'graph', None) if graph: f = self.db.genoo.Function(self.db, graph, m_name, is_method = True, _class = self.name) f.render(ilasm) else: pass # XXX: We want to implement an abstract method here self.db.pending_abstract_function(m_name) self.db.record_class(self.classdef, self.name) def copy_class_attributes(self, ilasm): default_values = self.classdef._fields.copy() default_values.update(self.classdef._overridden_defaults) for field_name, (field_type, field_value) in default_values.iteritems(): ilasm.load_str("this") self.db.load_const(field_type, field_value, ilasm) ilasm.set_field(None, field_name) def basename(self, name): return name.replace('.', '_')#[-1]
Python
""" This is example of totally basic server for XMLHttp request built on top of BaseHTTPServer. Construction is like that: you take your own implementation of Handler and subclass it to provide whatever you like. Each request is checked first for apropriate method in handler (with dots replaced as _) and this method needs to have set attribute exposed If method is not there, we instead try to search exported_methods (attribute of handler) for apropriate JSON call. We write down a JSON which we get as a return value (note that right now arguments could be only strings) and pass them to caller """ import traceback HTTP_STATUS_MESSAGES = { 200: 'OK', 204: 'No Content', 301: 'Moved permanently', 302: 'Found', 304: 'Not modified', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not found', 500: 'Server error', 501: 'Not implemented', } class HTTPError(Exception): """ raised on HTTP errors """ def __init__(self, status, data=None): self.status = status self.message = HTTP_STATUS_MESSAGES[status] self.data = data def __str__(self): data = '' if self.data: data = ' (%s)' % (self.data,) return '<HTTPException %s "%s"%s>' % (self.status, self.message, data) from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import re import time import random import os import sys import py from pypy.translator.js.lib.url import parse_url from pypy.translator.js import json from pypy.rpython.ootypesystem.bltregistry import MethodDesc, BasicExternal,\ described from pypy.translator.js.main import rpython2javascript from pypy.translator.js import commproxy commproxy.USE_MOCHIKIT = False class Collection(object): """ an HTTP collection essentially this is a container object that has a path that ends on a slash, and support for PATH_INFO (so can have (virtual or not) children) children are callable attributes of ourselves that have an 'exposed' attribute themselves, that accept 3 arguments: 'handler', a reference to the BaseHTTPHandler that handles the request (XXX should be abstracted?), 'path', the requested path to the object, and 'query', the (unparsed!) GET query string (without a preceding ?) """ def traverse(self, path, orgpath): """ traverse path relative to self 'path' is the path requested by the client, split on '/', but relative from the current object: parent Collection items may have removed items (they will have, actually, unless 'self' is the root of the website) from the beginning on traversal to 'self' path is split on '/', the first item is removed and used to do a lookup on self, if that fails a 404 is raised, if successful the item is used to continue traversal (if the object found is a Collection type) or to handle the request (if the object found is a callable with .exposed set to True) if path equals '', a lookup for 'index' is done can be overridden in subclasses to implement different path handling (PATH_INFO-like stuff) """ name = path.pop(0) if name == '': name = 'index' name = name.replace(".", "_") resource = getattr(self, name, None) if (resource is None or (not isinstance(resource, Collection) and (not callable(resource) or not getattr(resource, 'exposed', True)))): raise HTTPError(404) if path: if not isinstance(resource, Collection): raise HTTPError(500) # no PATH_INFO allowed for non-Collection return resource.traverse(path, orgpath) else: if isinstance(resource, Collection): # targeting a collection directly: redirect to its 'index' raise HTTPError(301, orgpath + '/') if not getattr(resource, 'exposed', False): # don't reveal what is not accessible... raise HTTPError(404) return resource class ExportedMethods(BasicExternal, Collection): _render_base_path = "exported_methods" def traverse(self, path, orgpath): """ traverse path relative to self 'path' is the path requested by the client, split on '/', but relative from the current object: parent Collection items may have removed items (they will have, actually, unless 'self' is the root of the website) from the beginning on traversal to 'self' path is split on '/', the first item is removed and used to do a lookup on self, if that fails a 404 is raised, if successful the item is used to continue traversal (if the object found is a Collection type) or to handle the request (if the object found is a callable with .exposed set to True) if path equals '', a lookup for 'index' is done can be overridden in subclasses to implement different path handling (PATH_INFO-like stuff) """ name = path.pop(0) name = name.replace(".", "_") resource = getattr(self, name, None) if not resource: raise HTTPError(404) return lambda **args : ('text/json', json.write(resource(**args))) _render_xmlhttp = True exported_methods = ExportedMethods() def patch_handler(handler_class): """ This function takes care of adding necessary attributed to Static objects """ for name, value in handler_class.__dict__.iteritems(): if isinstance(value, Static) and value.path is None: assert hasattr(handler_class, "static_dir") value.path = os.path.join(str(handler_class.static_dir), name + ".html") class TestHandler(BaseHTTPRequestHandler): exported_methods = exported_methods def do_GET(self): path, args = parse_url(self.path) if not path: path = ["index"] name_path = path[0].replace(".", "_") if len(path) > 1: rest = os.path.sep.join(path[1:]) else: rest = None method_to_call = getattr(self, name_path, None) if method_to_call is None or not getattr(method_to_call, 'exposed', None): exec_meth = getattr(self.exported_methods, name_path, None) if exec_meth is None: self.send_error(404, "File %s not found" % path) else: self.serve_data('text/json', json.write(exec_meth(**args)), True) else: if rest: outp = method_to_call(rest, **args) else: outp = method_to_call(**args) if isinstance(outp, (str, unicode)): self.serve_data('text/html', outp) elif isinstance(outp, tuple): self.serve_data(*outp) else: raise ValueError("Don't know how to serve %s" % (outp,)) def log_message(self, format, *args): # XXX just discard it pass do_POST = do_GET def serve_data(self, content_type, data, nocache=False): self.send_response(200) self.send_header("Content-type", content_type) self.send_header("Content-length", len(data)) if nocache: self.send_nocache_headers() self.end_headers() self.wfile.write(data) def send_nocache_headers(self): self.send_header('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT') self.send_header('Last-Modified', time.strftime("%a, %d %b %Y %H:%M:%S GMT")) self.send_header('Cache-Control', 'no-cache, must-revalidate') self.send_header('Cache-Control', 'post-check=0, pre-check=0') self.send_header('Pragma', 'no-cache') class Static(object): exposed = True def __init__(self, path=None): self.path = path def __call__(self): return open(str(self.path)).read() class FsFile(object): exposed = True debug = False def __init__(self, path, content_type="text/html"): self._path = path self._content_type = content_type _data = None def __call__(self): if self._data is None or self.debug: self._data = self._path.read() return ({'Content-Type': self._content_type}, self._data) class StaticDir(Collection): exposed = True def __init__(self, path, type=None): self.path = path self.type = type def traverse(self, path, orgpath): data = open(os.path.join(str(self.path), *path)).read() if self.type: return lambda : (self.type, data) return lambda : data def create_server(server_address = ('', 8000), handler=TestHandler, server=HTTPServer): """ Parameters: spawn - create new thread and return (by default it doesn't return) fork - do a real fork timeout - kill process after X seconds (actually doesn't work for threads) port_file - function to be called with port number """ patch_handler(handler) httpd = server(server_address, handler) httpd.last_activity = time.time() print "Server started, listening on %s:%s" %\ (httpd.server_address[0],httpd.server_port) return httpd def start_server_in_new_thread(server): import thread thread.start_new_thread(server.serve_forever, ()) def start_server_in_new_process(server, timeout=None): pid = os.fork() if not pid: if timeout: def f(httpd): while 1: time.sleep(.3) if time.time() - httpd.last_activity > timeout: httpd.server_close() import os os.kill(os.getpid(), 15) import thread thread.start_new_thread(f, (server,)) server.serve_forever() os._exit(0) return pid Handler = TestHandler # deprecate TestHandler name class NewHandler(BaseHTTPRequestHandler): """ BaseHTTPRequestHandler that does object publishing """ application = None # attach web root (Collection object) here!! bufsize = 1024 def do_GET(self, send_body=True): """ perform a request """ path, query = self.process_path(self.path) _, args = parse_url("?" + query) try: resource = self.find_resource(path) # XXX strange hack if hasattr(resource, 'im_self'): resource.im_self.server = self.server retval = resource(**args) if isinstance(retval, str): headers = {'Content-Type': 'text/html'} data = retval else: headers, data = retval if isinstance(headers, str): headers = {'Content-Type': headers} except HTTPError, e: status = e.status headers, data = self.process_http_error(e) except: exc, e, tb = sys.exc_info() tb_formatted = '\n'.join(traceback.format_tb(tb)) status = 200 data = 'An error has occurred: %s - %s\n\n%s' % (exc, e, tb_formatted) headers = {'Content-Type': 'text/plain'} if hasattr(self.application, 'handle_error'): self.application.handle_error(exc, e, tb) else: status = 200 if not 'content-type' in [k.lower() for k in headers]: headers['Content-Type'] = 'text/html; charset=UTF-8' self.response(status, headers, data, send_body) do_POST = do_GET def do_HEAD(self): return self.do_GET(False) def process_path(self, path): """ split the path in a path and a query part# returns a tuple (path, query), where path is a string and query a dictionary containing the GET vars (URL decoded and such) """ path = path.split('?') if len(path) > 2: raise ValueError('illegal path %s' % (path,)) p = path[0] q = len(path) > 1 and path[1] or '' return p, q def find_resource(self, path): """ find the resource for a given path """ if not path: raise HTTPError(301, '/') assert path.startswith('/') chunks = path.split('/') chunks.pop(0) # empty item return self.application.traverse(chunks, path) def process_http_error(self, e): """ create the response body and headers for errors """ headers = {'Content-Type': 'text/html'} # XXX need more headers here? if e.status in [301, 302]: headers['Location'] = e.data body = 'Redirecting to %s' % (e.data,) else: message, explain = self.responses[e.status] body = self.error_message_format % {'code': e.status, 'message': message, 'explain': explain} return headers, body def response(self, status, headers, body, send_body=True): """ generate the HTTP response and send it to the client """ self.send_response(status) if (isinstance(body, str) and not 'content-length' in [k.lower() for k in headers]): headers['Content-Length'] = len(body) for keyword, value in headers.iteritems(): self.send_header(keyword, value) self.end_headers() if not send_body: return if isinstance(body, str): self.wfile.write(body) elif hasattr(body, 'read'): while 1: data = body.read(self.bufsize) if data == '': break self.wfile.write(data) else: raise ValueError('body is not a plain string or file-like object')
Python
""" Some support files for mapping urls, mostly bindings for existing cgi stuff """ import cgi import urllib class URL(object): def __init__(self, path, vars): self.path = path self.vars = vars def __eq__(self, other): if isinstance(other, URL): return self.path == other.path and self.vars == other.vars if isinstance(other, tuple): if len(other) != 2: return False return self.path, self.vars == other return False def __ne__(self, other): return not self == other def __iter__(self): return iter((self.path, self.vars)) def parse_url(path): """ Parse a/b/c?q=a into ('a', 'b', 'c') {'q':'a'} """ if '?' in path: path, var_str = path.split("?") vars_orig = cgi.parse_qs(var_str) # if vars has a list inside... vars = {} for i, v in vars_orig.items(): if isinstance(v, list): vars[i] = v[0] else: vars[i] = v else: vars = {} parts = [urllib.unquote(i) for i in path.split("/") if i] return URL(parts, vars)
Python
""" Various simple support functions """ from pypy.rpython.ootypesystem.bltregistry import described, load_dict_args,\ MethodDesc from pypy.rpython.extfunc import genericcallable def callback(retval=None, args={}): """ Variant of described decorator, which flows an additional argument with return value of decorated function, used specifically for callbacks """ def decorator(func): defs = func.func_defaults if defs is None: defs = () vars = func.func_code.co_varnames[:func.func_code.co_argcount] if isinstance(args, dict): arg_list = load_dict_args(vars, defs, args) else: arg_list = args arg_list.append(("callback", genericcallable(args=[retval]))) func._method = (func.__name__, MethodDesc(arg_list, retval)) return func return decorator import sys, new from pypy.translator.js.main import rpython2javascript def js_source(functions, use_pdb=True): mod = new.module('_js_src') function_names = [] for func in functions: name = func.__name__ if hasattr(mod, name): raise ValueError("exported function name %r is duplicated" % (name,)) mod.__dict__[name] = func function_names.append(name) sys.modules['_js_src'] = mod try: return rpython2javascript(mod, function_names, use_pdb=use_pdb) finally: del sys.modules['_js_src']
Python
""" genjs constant database module """ from pypy.rpython.ootypesystem import ootype from pypy.translator.js.opcodes import opcodes from pypy.translator.js.function import Function from pypy.translator.js.log import log from pypy.translator.js._class import Class from pypy.translator.js.support import JavascriptNameManager from pypy.rpython.lltypesystem.lltype import Signed, Unsigned, Void, Bool, Float from pypy.rpython.lltypesystem.lltype import SignedLongLong, UnsignedLongLong, typeOf from pypy.rpython.lltypesystem.lltype import Char, UniChar from pypy.rpython.ootypesystem import ootype from pypy.rpython.ootypesystem import bltregistry from pypy.objspace.flow.model import Variable, Constant from pypy.translator.js.modules import dom from pypy.translator.js.commproxy import XmlHttp try: set except NameError: from sets import Set as set class LowLevelDatabase(object): def __init__(self, genoo): self._pending_nodes = set() self.genoo = genoo self._rendered_nodes = set() self.classes = {} # classdef --> class_name self.functions = {} # graph --> function_name self.function_names = {} # graph --> real_name self.methods = {} # graph --> method_name self.consts = {} # value --> const_name self.reverse_consts = {} self.const_names = set() self.rendered = set() self.const_var = Variable("__consts") self.name_manager = JavascriptNameManager(self) self.pending_consts = [] self.cts = self.genoo.TypeSystem(self) self.proxies = [] def is_primitive(self, type_): if type_ in [Void, Bool, Float, Signed, Unsigned, SignedLongLong, UnsignedLongLong, Char, UniChar, ootype.StringBuilder] or \ isinstance(type_,ootype.StaticMethod): return True return False def pending_function(self, graph): self.pending_node(self.genoo.Function(self, graph)) def pending_abstract_function(self, name): pass # XXX we want to implement it at some point (maybe...) def pending_class(self, classdef): c = Class(self, classdef) self.pending_node(c) return c def pending_record(self, record): r = Record(self, record) self.pending_node(r) return r.get_name() def pending_node(self, node): if node in self._pending_nodes or node in self._rendered_nodes: return self._pending_nodes.add(node) def record_function(self, graph, name): self.functions[graph] = name def get_uniquename(self, graph, name): try: return self.function_names[graph] except KeyError: real_name = self.name_manager.uniquename(name, lenmax=1111111) self.function_names[graph] = real_name return real_name def record_class(self, classdef, name): self.classes[classdef] = name def register_comm_proxy(self, proxy_const, *args): """ Register external object which should be rendered as method call """ self.proxies.append(XmlHttp(proxy_const, *args)) def graph_name(self, graph): return self.functions.get(graph, None) def class_name(self, classdef): return self.classes.get(classdef, None) def record_const(self, value, type_ = None, retval='name'): if type_ is None: type_ = typeOf(value) if self.is_primitive(type_): return None const = AbstractConst.make(self, value) if not const: return None try: if retval == 'name': return self.consts[const] else: self.consts[const] return self.reverse_consts[self.consts[const]] except KeyError: if self.genoo.config.translation.verbose: log("New const:%r"%value) if isinstance(value, ootype._string): log(value._str) else: log.dot() name = const.get_name() if name in self.const_names: name += '__%d' % len(self.consts) self.consts[const] = name self.reverse_consts[name] = const self.const_names.add(name) self.pending_consts.append((const,name)) if retval == 'name': return name else: return const def gen_constants(self, ilasm, pending): try: while True: const,name = self.pending_consts.pop() const.record_fields() except IndexError: pass if pending: return if not self.rendered: ilasm.begin_consts(self.const_var.name) def generate_constants(consts): all_c = [const for const,name in consts.iteritems()] dep_ok = set() while len(all_c) > 0: const = all_c.pop() if const not in self.rendered: to_render = True if hasattr(const, 'depends_on') and const.depends_on: for i in const.depends_on: if i not in self.rendered and i not in dep_ok: assert i.depends is None or const in i.depends to_render = False continue if to_render and (not hasattr(const, 'depends')) or (not const.depends) or const in dep_ok: yield const,consts[const] self.rendered.add(const) else: all_c.append(const) for i in const.depends: all_c.append(i) dep_ok.add(const) # We need to keep track of fields to make sure # our items appear earlier than us to_init = [] for const, name in generate_constants(self.consts): if self.genoo.config.translation.verbose: log("Recording %r %r"%(const,name)) else: log.dot() ilasm.load_local(self.const_var) const.init(ilasm) ilasm.set_field(None, name) ilasm.store_void() to_init.append((const, name)) #ilasm.field(name, const.get_type(), static=True) for const, name in to_init: const.init_fields(ilasm, self.const_var, name) def load_const(self, type_, value, ilasm): if self.is_primitive(type_): ilasm.load_const(self.cts.primitive_repr(type_, value)) else: try: return self.consts[BuiltinConst(value)] except KeyError: name = self.record_const(value) ilasm.load_local(self.const_var) ilasm.get_field(name) #assert False, 'Unknown constant %s' % const class AbstractConst(object): def __init__(self, db, const): self.db = db self.const = const self.cts = db.genoo.TypeSystem(db) self.depends = set() self.depends_on = set() def __hash__(self): return hash(self.get_key()) def __eq__(self, other): return (other.__class__ is self.__class__ and other.get_key() == self.get_key()) def __ne__(self, other): return not (self == other) def make(db, const): if isinstance(const, ootype._view): static_type = const._TYPE const = const._inst else: static_type = None if isinstance(const, ootype._instance): return InstanceConst(db, const, static_type) elif isinstance(const, ootype._list): return ListConst(db, const) elif isinstance(const, ootype._record): return RecordConst(db, const) elif isinstance(const, ootype._string): return StringConst(db, const) elif isinstance(const, ootype._dict): return DictConst(db, const) elif isinstance(const, bltregistry._external_inst): return ExtObject(db, const) elif isinstance(const, ootype._class): if const._INSTANCE: return ClassConst(db, const) else: return None else: assert False, 'Unknown constant: %s %r' % (const, typeOf(const)) make = staticmethod(make) def get_name(self): pass def get_type(self): pass def init(self, ilasm): pass def init_fields(self, ilasm, const_var, name): pass def record_fields(self): pass class InstanceConst(AbstractConst): def __init__(self, db, obj, static_type): self.depends = set() self.depends_on = set() self.db = db self.cts = db.genoo.TypeSystem(db) self.obj = obj if static_type is None: self.static_type = obj._TYPE else: self.static_type = static_type self.cts.lltype_to_cts(obj._TYPE) # force scheduling of obj's class def get_key(self): return self.obj def get_name(self): return self.obj._TYPE._name.replace('.', '_') def get_type(self): return self.cts.lltype_to_cts(self.static_type) def init(self, ilasm): if not self.obj: ilasm.load_void() return classdef = self.obj._TYPE try: classdef._hints['_suggested_external'] ilasm.new(classdef._name.split(".")[-1]) except KeyError: ilasm.new(classdef._name.replace(".", "_")) def record_fields(self): if not self.obj: return INSTANCE = self.obj._TYPE #while INSTANCE: for i, (_type, val) in INSTANCE._allfields().items(): if _type is not ootype.Void: name = self.db.record_const(getattr(self.obj, i), _type, 'const') if name is not None: self.depends.add(name) name.depends_on.add(self) def init_fields(self, ilasm, const_var, name): if not self.obj: return INSTANCE = self.obj._TYPE #while INSTANCE: for i, (_type, el) in INSTANCE._allfields().items(): if _type is not ootype.Void: ilasm.load_local(const_var) self.db.load_const(_type, getattr(self.obj, i), ilasm) ilasm.set_field(None, "%s.%s"%(name, i)) ilasm.store_void() class RecordConst(AbstractConst): def get_name(self): return "const_tuple" def init(self, ilasm): if not self.const: ilasm.load_void() else: ilasm.new_obj() def record_fields(self): if not self.const: return for i in self.const._items: name = self.db.record_const(self.const._items[i], None, 'const') if name is not None: self.depends.add(name) name.depends_on.add(self) def get_key(self): return self.const def init_fields(self, ilasm, const_var, name): if not self.const: return #for i in self.const.__dict__["_items"]: for i in self.const._items: ilasm.load_local(const_var) el = self.const._items[i] self.db.load_const(typeOf(el), el, ilasm) ilasm.set_field(None, "%s.%s"%(name, i)) ilasm.store_void() class ListConst(AbstractConst): def get_name(self): return "const_list" def init(self, ilasm): if not self.const: ilasm.load_void() else: ilasm.new_list() def record_fields(self): if not self.const: return for i in self.const._list: name = self.db.record_const(i, None, 'const') if name is not None: self.depends.add(name) name.depends_on.add(self) def get_key(self): return self.const def init_fields(self, ilasm, const_var, name): if not self.const: return for i in xrange(len(self.const._list)): ilasm.load_str("%s.%s"%(const_var.name, name)) el = self.const._list[i] self.db.load_const(typeOf(el), el, ilasm) self.db.load_const(typeOf(i), i, ilasm) ilasm.list_setitem() ilasm.store_void() class StringConst(AbstractConst): def get_name(self): return "const_str" def get_key(self): return self.const._str def init(self, ilasm): if self.const: s = self.const._str # do some escaping #s = s.replace("\n", "\\n").replace('"', '\"') #s = repr(s).replace("\"", "\\\"") ilasm.load_str("%s" % repr(s)) else: ilasm.load_str("undefined") def init_fields(self, ilasm, const_var, name): pass class ClassConst(AbstractConst): def __init__(self, db, const): super(ClassConst, self).__init__(db, const) self.cts.lltype_to_cts(const._INSTANCE) # force scheduling of class def get_name(self): return "const_class" def get_key(self): return self.get_name() def get_name(self): return self.const._INSTANCE._name.replace(".", "_") def init(self, ilasm): ilasm.load_const("%s" % self.get_name()) #def init_fields(self, ilasm, const_var, name): # pass class BuiltinConst(AbstractConst): def __init__(self, name): self.name = name def get_key(self): return self.name def get_name(self): return self.name def init_fields(self, *args): pass def init(self, ilasm): ilasm.load_str(self.name) class DictConst(RecordConst): def record_const(self, co): name = self.db.record_const(co, None, 'const') if name is not None: self.depends.add(name) name.depends_on.add(self) def record_fields(self): if not self.const: return for i in self.const._dict: self.record_const(i) self.record_const(self.const._dict[i]) def init_fields(self, ilasm, const_var, name): if not self.const: return for i in self.const._dict: ilasm.load_str("%s.%s"%(const_var.name, name)) el = self.const._dict[i] self.db.load_const(typeOf(el), el, ilasm) self.db.load_const(typeOf(i), i, ilasm) ilasm.list_setitem() ilasm.store_void() class ExtObject(AbstractConst): def __init__(self, db, const): self.db = db self.const = const self.name = self.get_name() self.depends = set() self.depends_on = set() def get_key(self): return self.name def get_name(self): return self.const._TYPE._name.split('.')[-1][:-2] def init(self, ilasm): _class = self.const._TYPE._class_ if getattr(_class, '_render_xmlhttp', False): use_xml = getattr(_class, '_use_xml', False) base_url = getattr(_class, '_base_url', "") # XXX: should be method = getattr(_class, '_use_method', 'GET') # on per-method basis self.db.register_comm_proxy(self.const, self.name, use_xml, base_url, method) ilasm.new(self.get_name()) else: # Otherwise they just exist, or it's not implemented if not hasattr(self.const.value, '_render_name'): raise ValueError("Prebuilt constant %s has no attribute _render_name," "don't know how to render" % self.const.value) ilasm.load_str(self.const.value._render_name)
Python
""" tester - support module for testing js code inside python Needs to be imported in case one wants tests involving calling BasicExternal methods """ from pypy.rpython.ootypesystem.bltregistry import BasicExternal def __getattr__(self, attr): val = super(BasicExternal, self).__getattribute__(attr) if not callable(val) or attr not in self._methods: return val # we don't do anything special # otherwise.... def wrapper(*args, **kwargs): args = list(args) # do this only if last arg is callable if not (len(args) > 0 and callable(args[-1])): return val(*args, **kwargs) callback = args.pop() res = val(*args, **kwargs) if not hasattr(self, '__callbacks'): self.__callbacks = [] self.__callbacks.append((callback, res)) wrapper.func_name = attr return wrapper BasicExternal.__getattribute__ = __getattr__ def schedule_callbacks(*args): for arg in args: if hasattr(arg, '__callbacks'): for callback, res in arg.__callbacks: callback(res)
Python
import py, os, re, subprocess from pypy.translator.translator import TranslationContext from pypy.translator.backendopt.all import backend_optimizations from pypy.translator.js.js import JS from pypy.translator.js.test.browsertest import jstest from pypy.translator.js import conftest from pypy.translator.js.log import log from pypy.conftest import option from pypy.rpython.test.tool import BaseRtypingTest, OORtypeMixin from pypy.rlib.nonconst import NonConstant from pypy.rpython.ootypesystem import ootype from pypy.rpython.llinterp import LLException log = log.runtest use_browsertest = conftest.option.browser use_tg = conftest.option.tg port = 8080 class JSException(LLException): pass def _CLI_is_on_path(): if py.path.local.sysfind('js') is None: #we recommend Spidermonkey return False return True class compile_function(object): def __init__(self, function, annotations, stackless=False, view=False, html=None, is_interactive=False, root = None, run_browser = True, policy = None): if not use_browsertest and not _CLI_is_on_path(): py.test.skip('Javascript CLI (js) not found') self.html = html self.is_interactive = is_interactive t = TranslationContext() if policy is None: from pypy.annotation.policy import AnnotatorPolicy policy = AnnotatorPolicy() policy.allow_someobjects = False ann = t.buildannotator(policy=policy) ann.build_types(function, annotations) if view or option.view: t.view() t.buildrtyper(type_system="ootype").specialize() if view or option.view: t.view() #self.js = JS(t, [function, callback_function], stackless) self.js = JS(t, function, stackless) self.js.write_source() if root is None and use_tg: from pypy.translator.js.demo.jsdemo.controllers import Root self.root = Root else: self.root = root self.run_browser = run_browser self.function_calls = [] def source(self): return self.js.tmpfile.open().read() def _conv(self, v): if isinstance(v, str): return repr(v) return str(v).lower() def __call__(self, *kwds): return self.call(None, kwds) def call(self, entry_function, kwds): args = ', '.join([self._conv(kw) for kw in kwds]) #lowerstr for (py)False->(js)false, etc. if entry_function is None: entry_function = self.js.translator.graphs[0].name else: entry_function = self.js.translator.annotator.bookkeeper.getdesc(entry_function).cached_graph(None) function_call = "%s(%s)" % (entry_function, args) self.function_calls.append(function_call) #if self.js.stackless: # function_call = "slp_entry_point('%s')" % function_call if use_browsertest: if not use_tg: log("Used html: %r" % self.html) output = jstest(self.js.filename, function_call, use_browsertest, self.html, self.is_interactive) else: global port from pypy.translator.js.test.tgtest import run_tgtest out = run_tgtest(self, tg_root = self.root, port=port, run_browser=self.run_browser).results assert out[1] == 'undefined' or out[1] == "" output = out[0] port += 1 else: # cmd = 'echo "load(\'%s\'); print(%s)" | js 2>&1' % (self.js.filename, function_call) # log(cmd) # output = os.popen(cmd).read().strip() js = subprocess.Popen(["js"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) input = "load(%r);\n" % self.js.filename.strpath for call in self.function_calls[:-1]: input += "%s;\n" % call input += "print(\"'\" + %s + \"'\");\n" % self.function_calls[-1] js.stdin.write(input) stdout, stderr = js.communicate() output = (stderr + stdout).strip() for s in output.split('\n'): log(s) m = re.match("'(.*)'", output, re.DOTALL) if not m: log("Error: %s" % output) raise JSException(output) return self.reinterpret(m.group(1)) def reinterpret(cls, s): #while s.startswith(" "): # s = s[1:] # :-) quite inneficient, but who cares if s == 'false': res = False elif s == 'true': res = True elif s == 'undefined': res = None elif s == 'inf': res = 1e300 * 1e300 elif s == 'NaN': res = (1e300 * 1e300) / (1e300 * 1e300) elif s.startswith('[') or s.startswith('('): l = s[1:-1].split(',') res = [cls.reinterpret(i) for i in l] else: try: res = float(s) if float(int(res)) == res: return int(res) except ValueError: res = str(s) return res reinterpret = classmethod(reinterpret) class JsTest(BaseRtypingTest, OORtypeMixin): def _compile(self, _fn, args, policy=None): argnames = _fn.func_code.co_varnames[:_fn.func_code.co_argcount] func_name = _fn.func_name if func_name == '<lambda>': func_name = 'func' source = py.code.Source(""" def %s(): from pypy.rlib.nonconst import NonConstant res = _fn(%s) if isinstance(res, type(None)): return None else: return str(res)""" % (func_name, ",".join(["%s=NonConstant(%r)" % (name, i) for name, i in zip(argnames, args)]))) exec source.compile() in locals() return compile_function(locals()[func_name], [], policy=policy) def string_to_ll(self, s): return s def interpret(self, fn, args, policy=None): f = self._compile(fn, args, policy) res = f(*args) return res def interpret_raises(self, exception, fn, args): #import exceptions # needed by eval #try: #import pdb; pdb.set_trace() try: res = self.interpret(fn, args) except JSException, e: s = e.args[0] assert s.startswith('uncaught exception:') assert re.search(exception.__name__, s) else: raise AssertionError("Did not raise, returned %s" % res) #except ExceptionWrapper, ex: # assert issubclass(eval(ex.class_name), exception) #else: # assert False, 'function did raise no exception at all' def ll_to_string(self, s): return str(s) def ll_to_list(self, l): return l def ll_unpack_tuple(self, t, length): assert len(t) == length return tuple(t) def class_name(self, value): return value[:-8].split('.')[-1] def is_of_instance_type(self, val): m = re.match("^<.* object>$", val) return bool(m) def read_attr(self, obj, name): py.test.skip('read_attr not supported on genjs tests') def check_source_contains(compiled_function, pattern): import re source = compiled_function.js.tmpfile.open().read() return re.search(pattern, source)
Python
from BaseHTTPServer import HTTPServer as BaseHTTPServer, BaseHTTPRequestHandler import py from os import system from cgi import parse_qs from sys import platform from time import sleep import webbrowser from pypy.translator.js.log import log log = log.browsertest class HTTPServer(BaseHTTPServer): allow_reuse_address = True class config: http_port = 10001 html_page = """<html> <head> <script type="text/javascript"> %(jscode)s // code for running the unittest... function runTest() { var result = undefined; try { result = %(jstestcase)s; } catch (e) { try { result = "throw '" + e.toSource() + "'"; } catch (dummy) { result = "throw 'unknown javascript exception'"; } } if (result != undefined || !in_browser) { // if valid result (no timeout) handle_result(result); } }; function handle_result(result) { var resultform = document.forms['resultform']; if (typeof(result) == typeof({})) { result = result.chars; //assume it's a rpystring } resultform.result.value = result; resultform.submit(); }; </script> </head> <body onload="runTest()"> %(jsfilename)s <form method="post" name="resultform" id="resultform"> <input name="result" type="hidden" value="UNKNOWN" /> </form> <div id="logdiv"></div> </body> </html>""" refresh_page = """<html> <head> <meta http-equiv="refresh" content="0"> </head> <body> <pre> // testcase: %(jstestcase)s %(jscode)s </pre> </body> </html>""" class TestCase(object): def __init__(self, jsfilename, jstestcase): self.jsfilename = jsfilename self.jscode = open(jsfilename).read() self.jstestcase = jstestcase self.result = None class TestHandler(BaseHTTPRequestHandler): """The HTTP handler class that provides the tests and handles results""" def do_GET(self): global do_status if self.path != "/test.html": self.send_error(404, "File /test.html not found") return jsfilename = jstest.jsfilename jstestcase = jstest.jstestcase jscode = jstest.jscode if self.server.html_page: if self.server.is_interactive: isinteractive = '' else: isinteractive = 'resultform.submit();' try: html_page = open(self.server.html_page).read() % locals() except IOError: log("HTML FILE WAS NOT FOUND!!!!") self.send_error(404, "File %s not found" % self.server.html_page) return else: html_page = config.html_page % locals() open("html_page.html", "w").write(html_page) self.serve_data('text/html', html_page) do_status = 'do_GET' def do_POST(self): global do_status if self.path != "/test.html": self.send_error(404, "File /test.html not found") return form = parse_qs(self.rfile.read(int(self.headers['content-length']))) if self.server.is_interactive: if not form.has_key('ok'): jstest.result = 'Not clicked OK' else: jstest.result = 'OK' #assert False, "Clicked not ok" else: jstest.result = form['result'][0] #we force a page refresh here because of two reason: # 1. we don't have the next testcase ready yet # 2. browser should ask again when we do have a test jsfilename = jstest.jsfilename jstestcase = jstest.jstestcase jscode = jstest.jscode refresh_page = config.refresh_page % locals() self.serve_data('text/html', refresh_page) do_status = 'do_POST' def serve_data(self, content_type, data): self.send_response(200) self.send_header("Content-type", content_type) self.send_header("Content-length", len(data)) self.end_headers() self.wfile.write(data) class BrowserTest(object): """The browser driver""" def start_server(self, port, html_page, is_interactive): server_address = ('', port) self.httpd = HTTPServer(server_address, TestHandler) self.httpd.is_interactive = is_interactive self.httpd.html_page = html_page def get_result(self): global do_status do_status = None while do_status != 'do_GET': self.httpd.handle_request() while do_status != 'do_POST': self.httpd.handle_request() return jstest.result def jstest(jsfilename, jstestcase, browser_to_use, html_page = None, is_interactive = False): global driver, jstest jstest = TestCase(str(jsfilename), str(jstestcase)) try: driver.httpd.html_page = html_page driver.httpd.is_interactive = is_interactive except: driver = BrowserTest() driver.start_server(config.http_port, html_page, is_interactive) if browser_to_use == 'default': browser_to_use = None if browser_to_use != 'none': webbrowser.get(browser_to_use).open('http://localhost:%d/test.html' % config.http_port) result = driver.get_result() return result
Python
""" TurboGears browser testing utility """ import thread import pkg_resources pkg_resources.require("TurboGears") import cherrypy import os import sys import webbrowser from pypy.translator.js.demo.jsdemo import controllers conf_file = os.path.join(os.path.dirname(controllers.__file__), "..", "dev.cfg") class run_tgtest(object): def __init__(self, compiled_fun, tg_root = None, port = 8080, run_browser=True): def cont(): cherrypy.server.wait() if run_browser: webbrowser.open("http://localhost:%d/" % port) cherrypy.root.wait_for_results() self.results = cherrypy.root.results cherrypy.server.stop() cherrypy.server.interrupt = SystemExit() cherrypy.config.update(file=conf_file) cherrypy.config.update({'global':{'server.socketPort':port}}) if tg_root is None: cherrypy.root = controllers.Root() else: cherrypy.root = tg_root() cherrypy.root.jssource = compiled_fun.js.tmpfile.open().read() cherrypy.root.jsname = compiled_fun.js.translator.graphs[0].name thread.start_new_thread(cont, ()) sys.path.insert(1, os.path.join(os.path.dirname(controllers.__file__), "..")) cherrypy.server.start()
Python
"""PyPy Translator Frontend The Translator is a glue class putting together the various pieces of the translation-related code. It can be used for interactive testing of the translator; see pypy/bin/translatorshell.py. """ import autopath, os, sys, types, copy from pypy.objspace.flow.model import * from pypy.translator import simplify from pypy.objspace.flow import FlowObjSpace from pypy.tool.ansi_print import ansi_log from pypy.tool.sourcetools import nice_repr_for_func from pypy.config.pypyoption import pypy_optiondescription from pypy.config.translationoption import get_combined_translation_config import py log = py.log.Producer("flowgraph") py.log.setconsumer("flowgraph", ansi_log) class TranslationContext(object): FLOWING_FLAGS = { 'verbose': False, 'simplifying': True, 'builtins_can_raise_exceptions': False, 'list_comprehension_operations': False, # True, - not super-tested } def __init__(self, config=None, **flowing_flags): if config is None: from pypy.config.pypyoption import get_pypy_config config = get_pypy_config(translating=True) # ZZZ should go away in the end for attr in ['verbose', 'simplifying', 'builtins_can_raise_exceptions', 'list_comprehension_operations']: if attr in flowing_flags: setattr(config.translation, attr, flowing_flags[attr]) self.config = config self.create_flowspace_config() self.annotator = None self.rtyper = None self.exceptiontransformer = None self.graphs = [] # [graph] self.callgraph = {} # {opaque_tag: (caller-graph, callee-graph)} self._prebuilt_graphs = {} # only used by the pygame viewer self._implicitly_called_by_externals = [] def create_flowspace_config(self): # XXX this is a hack: we create a new config, which is only used # for the flow object space. The problem is that the flow obj space # needs an objspace config, but the thing we are translating might not # have one (or worse we are translating pypy and the flow space picks # up strange options of the pypy we are translating). Therefore we need # to construct this new config self.flowconfig = get_combined_translation_config( pypy_optiondescription, self.config, translating=True) self.flowconfig.objspace.name = "flow" def buildflowgraph(self, func, mute_dot=False): """Get the flow graph for a function.""" if not isinstance(func, types.FunctionType): raise TypeError("buildflowgraph() expects a function, " "got %r" % (func,)) if func in self._prebuilt_graphs: graph = self._prebuilt_graphs.pop(func) else: if self.config.translation.verbose: log.start(nice_repr_for_func(func)) space = FlowObjSpace(self.flowconfig) if self.annotator: # ZZZ self.annotator.policy._adjust_space_config(space) elif hasattr(self, 'no_annotator_but_do_imports_immediately'): space.do_imports_immediately = ( self.no_annotator_but_do_imports_immediately) graph = space.build_flow(func) if self.config.translation.simplifying: simplify.simplify_graph(graph) if self.config.translation.list_comprehension_operations: simplify.detect_list_comprehension(graph) if self.config.translation.verbose: log.done(func.__name__) elif not mute_dot: log.dot() self.graphs.append(graph) # store the graph in our list return graph def update_call_graph(self, caller_graph, callee_graph, position_tag): # update the call graph key = caller_graph, callee_graph, position_tag self.callgraph[key] = caller_graph, callee_graph def buildannotator(self, policy=None): if self.annotator is not None: raise ValueError("we already have an annotator") from pypy.annotation.annrpython import RPythonAnnotator self.annotator = RPythonAnnotator(self, policy=policy) return self.annotator def buildrtyper(self, type_system="lltype"): if self.annotator is None: raise ValueError("no annotator") if self.rtyper is not None: raise ValueError("we already have an rtyper") from pypy.rpython.rtyper import RPythonTyper self.rtyper = RPythonTyper(self.annotator, type_system = type_system) return self.rtyper def getexceptiontransformer(self): if self.rtyper is None: raise ValueError("no rtyper") if self.exceptiontransformer is not None: return self.exceptiontransformer from pypy.translator.c.exceptiontransform import ExceptionTransformer self.exceptiontransformer = ExceptionTransformer(self) return self.exceptiontransformer def checkgraphs(self): for graph in self.graphs: checkgraph(graph) # debug aids def about(self, x, f=None): """Interactive debugging helper """ if f is None: f = sys.stdout if isinstance(x, Block): for graph in self.graphs: if x in graph.iterblocks(): print >>f, '%s is a %s' % (x, x.__class__) print >>f, 'in %s' % (graph,) break else: print >>f, '%s is a %s at some unknown location' % ( x, x.__class__.__name__) print >>f, 'containing the following operations:' for op in x.operations: print >>f, " ",op print >>f, '--end--' return raise TypeError, "don't know about %r" % x def view(self): """Shows the control flow graph with annotations if computed. Requires 'dot' and pygame.""" from pypy.translator.tool.graphpage import FlowGraphPage FlowGraphPage(self).display() def viewcg(self): """Shows the whole call graph and the class hierarchy, based on the computed annotations.""" from pypy.translator.tool.graphpage import TranslatorPage TranslatorPage(self).display() # _______________________________________________________________ # testing helper def graphof(translator, func): if isinstance(func, FunctionGraph): return func result = [] for graph in translator.graphs: if getattr(graph, 'func', None) is func: result.append(graph) assert len(result) == 1 return result[0] TranslationContext._graphof = graphof
Python
"""Flow Graph Transformation The difference between simplification and transformation is that transformation is based on annotations; it runs after the annotator completed. """ from __future__ import generators import types from pypy.objspace.flow.model import SpaceOperation from pypy.objspace.flow.model import Variable, Constant, Link from pypy.objspace.flow.model import c_last_exception, checkgraph from pypy.annotation import model as annmodel from pypy.rlib.rstack import stack_check from pypy.rpython.lltypesystem import lltype def checkgraphs(self, blocks): seen = {} for block in blocks: graph = self.annotated[block] if graph not in seen: checkgraph(graph) seen[graph] = True def fully_annotated_blocks(self): """Ignore blocked blocks.""" for block, is_annotated in self.annotated.iteritems(): if is_annotated: yield block # XXX: Lots of duplicated codes. Fix this! # [a] * b # --> # c = newlist(a) # d = mul(c, int b) # --> # d = alloc_and_set(b, a) def transform_allocate(self, block_subset): """Transforms [a] * b to alloc_and_set(b, a) where b is int.""" for block in block_subset: length1_lists = {} # maps 'c' to 'a', in the above notation for i in range(len(block.operations)): op = block.operations[i] if (op.opname == 'newlist' and len(op.args) == 1): length1_lists[op.result] = op.args[0] elif (op.opname == 'mul' and op.args[0] in length1_lists and self.gettype(op.args[1]) is int): new_op = SpaceOperation('alloc_and_set', (op.args[1], length1_lists[op.args[0]]), op.result) block.operations[i] = new_op # lst += string[x:y] # --> # b = getitem(string, slice) # c = inplace_add(lst, b) # --> # c = extend_with_str_slice(lst, string, slice) def transform_extend_with_str_slice(self, block_subset): """Transforms lst += string[x:y] to extend_with_str_slice""" for block in block_subset: slice_sources = {} # maps b to [string, slice] in the above notation for i in range(len(block.operations)): op = block.operations[i] if (op.opname == 'getitem' and self.gettype(op.args[0]) is str and self.gettype(op.args[1]) is slice): slice_sources[op.result] = op.args elif (op.opname == 'inplace_add' and op.args[1] in slice_sources and self.gettype(op.args[0]) is list): v_string, v_slice = slice_sources[op.args[1]] new_op = SpaceOperation('extend_with_str_slice', [op.args[0], v_string, v_slice], op.result) block.operations[i] = new_op # lst += char*count [or count*char] # --> # b = mul(char, count) [or count, char] # c = inplace_add(lst, b) # --> # c = extend_with_char_count(lst, char, count) def transform_extend_with_char_count(self, block_subset): """Transforms lst += char*count to extend_with_char_count""" for block in block_subset: mul_sources = {} # maps b to (char, count) in the above notation for i in range(len(block.operations)): op = block.operations[i] if op.opname == 'mul': s0 = self.binding(op.args[0], None) s1 = self.binding(op.args[1], None) if (isinstance(s0, annmodel.SomeChar) and isinstance(s1, annmodel.SomeInteger)): mul_sources[op.result] = op.args[0], op.args[1] elif (isinstance(s1, annmodel.SomeChar) and isinstance(s0, annmodel.SomeInteger)): mul_sources[op.result] = op.args[1], op.args[0] elif (op.opname == 'inplace_add' and op.args[1] in mul_sources and self.gettype(op.args[0]) is list): v_char, v_count = mul_sources[op.args[1]] new_op = SpaceOperation('extend_with_char_count', [op.args[0], v_char, v_count], op.result) block.operations[i] = new_op # a[b:c] # --> # d = newslice(b, c, None) # e = getitem(a, d) # --> # e = getslice(a, b, c) ##def transform_slice(self, block_subset): -- not used any more -- ## """Transforms a[b:c] to getslice(a, b, c).""" ## for block in block_subset: ## operations = block.operations[:] ## n_op = len(operations) ## for i in range(0, n_op-1): ## op1 = operations[i] ## op2 = operations[i+1] ## if (op1.opname == 'newslice' and ## self.gettype(op1.args[2]) is types.NoneType and ## op2.opname == 'getitem' and ## op1.result is op2.args[1]): ## new_op = SpaceOperation('getslice', ## (op2.args[0], op1.args[0], op1.args[1]), ## op2.result) ## block.operations[i+1:i+2] = [new_op] def transform_dead_op_vars(self, block_subset): # we redo the same simplification from simplify.py, # to kill dead (never-followed) links, # which can possibly remove more variables. from pypy.translator.simplify import transform_dead_op_vars_in_blocks transform_dead_op_vars_in_blocks(block_subset) def transform_dead_code(self, block_subset): """Remove dead code: these are the blocks that are not annotated at all because the annotation considered that no conditional jump could reach them.""" for block in block_subset: for link in block.exits: if link not in self.links_followed: lst = list(block.exits) lst.remove(link) block.exits = tuple(lst) if not block.exits: # oups! cannot reach the end of this block cutoff_alwaysraising_block(self, block) elif block.exitswitch == c_last_exception: # exceptional exit if block.exits[0].exitcase is not None: # killed the non-exceptional path! cutoff_alwaysraising_block(self, block) if len(block.exits) == 1: block.exitswitch = None block.exits[0].exitcase = None def cutoff_alwaysraising_block(self, block): "Fix a block whose end can never be reached at run-time." # search the operation that cannot succeed can_succeed = [op for op in block.operations if op.result in self.bindings] cannot_succeed = [op for op in block.operations if op.result not in self.bindings] n = len(can_succeed) # check consistency assert can_succeed == block.operations[:n] assert cannot_succeed == block.operations[n:] assert 0 <= n < len(block.operations) # chop off the unreachable end of the block del block.operations[n+1:] s_impossible = annmodel.SomeImpossibleValue() self.bindings[block.operations[n].result] = s_impossible # insert the equivalent of 'raise AssertionError' graph = self.annotated[block] msg = "Call to %r should have raised an exception" % (getattr(graph, 'func', None),) c1 = Constant(AssertionError) c2 = Constant(AssertionError(msg)) errlink = Link([c1, c2], graph.exceptblock) block.recloseblock(errlink, *block.exits) # record new link to make the transformation idempotent self.links_followed[errlink] = True # fix the annotation of the exceptblock.inputargs etype, evalue = graph.exceptblock.inputargs s_type = annmodel.SomeObject() s_type.knowntype = type s_type.is_type_of = [evalue] s_value = annmodel.SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) self.setbinding(etype, s_type) self.setbinding(evalue, s_value) # make sure the bookkeeper knows about AssertionError self.bookkeeper.getuniqueclassdef(AssertionError) def insert_stackcheck(ann): from pypy.tool.algo.graphlib import Edge, make_edge_dict, break_cycles edges = [] graphs_to_patch = {} for callposition, (caller, callee) in ann.translator.callgraph.items(): if getattr(getattr(callee, 'func', None), 'insert_stack_check_here', False): graphs_to_patch[callee] = True continue edge = Edge(caller, callee) edge.callposition = callposition edges.append(edge) for graph in graphs_to_patch: v = Variable() ann.setbinding(v, annmodel.SomeImpossibleValue()) unwind_op = SpaceOperation('simple_call', [Constant(stack_check)], v) graph.startblock.operations.insert(0, unwind_op) edgedict = make_edge_dict(edges) for edge in break_cycles(edgedict, edgedict): caller = edge.source _, _, call_tag = edge.callposition if call_tag: caller_block, _ = call_tag else: ann.warning("cycle detected but no information on where to insert " "stack_check()") continue # caller block found, insert stack_check() v = Variable() # push annotation on v ann.setbinding(v, annmodel.SomeImpossibleValue()) unwind_op = SpaceOperation('simple_call', [Constant(stack_check)], v) caller_block.operations.insert(0, unwind_op) def insert_ll_stackcheck(translator): from pypy.translator.backendopt.support import find_calls_from from pypy.rpython.module.ll_stack import ll_stack_check from pypy.tool.algo.graphlib import Edge, make_edge_dict, break_cycles rtyper = translator.rtyper graph = rtyper.annotate_helper(ll_stack_check, []) rtyper.specialize_more_blocks() stack_check_ptr = rtyper.getcallable(graph) stack_check_ptr_const = Constant(stack_check_ptr, lltype.typeOf(stack_check_ptr)) edges = [] graphs_to_patch = {} insert_in = {} for caller in translator.graphs: for block, callee in find_calls_from(translator, caller): if getattr(getattr(callee, 'func', None), 'insert_stack_check_here', False): insert_in[callee.startblock] = True continue edge = Edge(caller, callee) edge.block = block edges.append(edge) edgedict = make_edge_dict(edges) for edge in break_cycles(edgedict, edgedict): block = edge.block insert_in[block] = True for block in insert_in: v = Variable() v.concretetype = lltype.Void unwind_op = SpaceOperation('direct_call', [stack_check_ptr_const], v) block.operations.insert(0, unwind_op) default_extra_passes = [ transform_allocate, transform_extend_with_str_slice, transform_extend_with_char_count, ] def transform_graph(ann, extra_passes=None, block_subset=None): """Apply set of transformations available.""" # WARNING: this produces incorrect results if the graph has been # modified by t.simplify() after it had been annotated. if extra_passes is None: extra_passes = default_extra_passes if block_subset is None: block_subset = fully_annotated_blocks(ann) if not isinstance(block_subset, dict): block_subset = dict.fromkeys(block_subset) if ann.translator: checkgraphs(ann, block_subset) transform_dead_code(ann, block_subset) for pass_ in extra_passes: pass_(ann, block_subset) # do this last, after the previous transformations had a # chance to remove dependency on certain variables transform_dead_op_vars(ann, block_subset) if ann.translator: checkgraphs(ann, block_subset)
Python
"""Flow Graph Simplification 'Syntactic-ish' simplifications on a flow graph. simplify_graph() applies all simplifications defined in this file. """ import py from pypy.objspace.flow.model import SpaceOperation from pypy.objspace.flow.model import Variable, Constant, Block, Link from pypy.objspace.flow.model import c_last_exception from pypy.objspace.flow.model import checkgraph, traverse, mkentrymap from pypy.rpython.lltypesystem import lloperation def get_funcobj(func): """ Return an object which is supposed to have attributes such as graph and _callable """ if hasattr(func, '_obj'): return func._obj # lltypesystem else: return func # ootypesystem def get_graph(arg, translator): from pypy.translator.translator import graphof if isinstance(arg, Variable): return None f = arg.value from pypy.rpython.lltypesystem import lltype from pypy.rpython.ootypesystem import ootype if not isinstance(f, lltype._ptr) and not isinstance(f, ootype._callable): return None funcobj = get_funcobj(f) try: callable = funcobj._callable # external function calls don't have a real graph if getattr(callable, "suggested_primitive", False): return None except (AttributeError, KeyError, AssertionError): return None try: return funcobj.graph except AttributeError: return None try: callable = funcobj._callable return graphof(translator, callable) except (AttributeError, KeyError, AssertionError): return None def replace_exitswitch_by_constant(block, const): assert isinstance(const, Constant) assert const != c_last_exception newexits = [link for link in block.exits if link.exitcase == const.value] assert len(newexits) == 1 newexits[0].exitcase = None if hasattr(newexits[0], 'llexitcase'): newexits[0].llexitcase = None block.exitswitch = None block.recloseblock(*newexits) return newexits # ____________________________________________________________ def eliminate_empty_blocks(graph): """Eliminate basic blocks that do not contain any operations. When this happens, we need to replace the preceeding link with the following link. Arguments of the links should be updated.""" def visit(link): if isinstance(link, Link): while not link.target.operations: block1 = link.target if block1.exitswitch is not None: break if not block1.exits: break exit = block1.exits[0] assert block1 is not exit.target, ( "the graph contains an empty infinite loop") outputargs = [] for v in exit.args: if isinstance(v, Variable): # this variable is valid in the context of block1 # but it must come from 'link' i = block1.inputargs.index(v) v = link.args[i] outputargs.append(v) link.args = outputargs link.target = exit.target # the while loop above will simplify recursively the new link traverse(visit, graph) def transform_ovfcheck(graph): """The special function calls ovfcheck and ovfcheck_lshift need to be translated into primitive operations. ovfcheck is called directly after an operation that should be turned into an overflow-checked version. It is considered a syntax error if the resulting <op>-ovf is not defined in baseobjspace.py . ovfcheck_lshift is special because there is no preceding operation. Instead, it will be replaced by an OP_LSHIFT_OVF operation. The exception handling of the original operation is completely ignored. Only exception handlers for the ovfcheck function call are taken into account. This gives us the best possible control over situations where we want exact contol over certain operations. Example: try: array1[idx-1] = ovfcheck(array1[idx-1] + array2[idx+1]) except OverflowError: ... assuming two integer arrays, we are only checking the element addition for overflows, but the indexing is not checked. """ # General assumption: # empty blocks have been eliminated. # ovfcheck can appear in the same block with its operation. # this is the case if no exception handling was provided. # Otherwise, we have a block ending in the operation, # followed by a block with a single ovfcheck call. from pypy.rlib.rarithmetic import ovfcheck, ovfcheck_lshift from pypy.objspace.flow.objspace import op_appendices from pypy.objspace.flow.objspace import implicit_exceptions covf = Constant(ovfcheck) covfls = Constant(ovfcheck_lshift) appendix = op_appendices[OverflowError] renaming = {} seen_ovfblocks = {} # get all blocks blocks = {} def visit(block): if isinstance(block, Block): blocks[block] = True traverse(visit, graph) def is_ovfcheck(bl): ops = bl.operations return (ops and ops[-1].opname == "simple_call" and ops[-1].args[0] == covf) def is_ovfshiftcheck(bl): ops = bl.operations return (ops and ops[-1].opname == "simple_call" and ops[-1].args[0] == covfls) def is_single(bl): return is_ovfcheck(bl) and len(bl.operations) > 1 def is_paired(bl): if bl.exits: ovfblock = bl.exits[0].target return (bl.exits and is_ovfcheck(ovfblock) and len(ovfblock.operations) == 1) def rename(v): return renaming.get(v, v) def remove_last_op(bl): delop = bl.operations.pop() assert delop.opname == "simple_call" assert len(delop.args) == 2 renaming[delop.result] = rename(delop.args[1]) for exit in bl.exits: exit.args = [rename(a) for a in exit.args] def check_syntax(ovfblock, block=None): """check whether ovfblock is reachable more than once or if they cheated about the argument""" if block: link = block.exits[0] for lprev, ltarg in zip(link.args, ovfblock.inputargs): renaming[ltarg] = rename(lprev) arg = ovfblock.operations[0].args[-1] res = block.operations[-1].result opname = block.operations[-1].opname else: arg = ovfblock.operations[-1].args[-1] res = ovfblock.operations[-2].result opname = ovfblock.operations[-2].opname if rename(arg) != rename(res) or ovfblock in seen_ovfblocks: raise SyntaxError("ovfcheck in %s: The checked operation %s" " is misplaced" % (graph.name, opname)) exlis = implicit_exceptions.get("%s_%s" % (opname, appendix), []) if OverflowError not in exlis: raise SyntaxError("ovfcheck in %s: Operation %s has no" " overflow variant" % (graph.name, opname)) blocks_to_join = False for block in blocks: if is_ovfshiftcheck(block): # ovfcheck_lshift: # simply rewrite the operation op = block.operations[-1] op.opname = "lshift" # augmented later op.args = op.args[1:] elif is_single(block): # remove the call to ovfcheck and keep the exceptions check_syntax(block) remove_last_op(block) seen_ovfblocks[block] = True elif is_paired(block): # remove the block's exception links link = block.exits[0] ovfblock = link.target check_syntax(ovfblock, block) block.recloseblock(link) block.exitswitch = None # remove the ovfcheck call from the None target remove_last_op(ovfblock) seen_ovfblocks[ovfblock] = True blocks_to_join = True else: continue op = block.operations[-1] op.opname = "%s_%s" % (op.opname, appendix) if blocks_to_join: join_blocks(graph) def simplify_exceptions(graph): """The exception handling caused by non-implicit exceptions starts with an exitswitch on Exception, followed by a lengthy chain of is_/issubtype tests. We collapse them all into the block's single list of exits. """ clastexc = c_last_exception renaming = {} def rename(v): return renaming.get(v, v) def visit(block): if not (isinstance(block, Block) and block.exitswitch == clastexc and block.exits[-1].exitcase is Exception): return covered = [link.exitcase for link in block.exits[1:-1]] seen = [] preserve = list(block.exits[:-1]) exc = block.exits[-1] last_exception = exc.last_exception last_exc_value = exc.last_exc_value query = exc.target switches = [] # collect the targets while len(query.exits) == 2: newrenaming = {} for lprev, ltarg in zip(exc.args, query.inputargs): newrenaming[ltarg] = rename(lprev) op = query.operations[0] if not (op.opname in ("is_", "issubtype") and newrenaming.get(op.args[0]) == last_exception): break renaming.update(newrenaming) case = query.operations[0].args[-1].value assert issubclass(case, py.builtin.BaseException) lno, lyes = query.exits assert lno.exitcase == False and lyes.exitcase == True if case not in seen: is_covered = False for cov in covered: if issubclass(case, cov): is_covered = True break if not is_covered: switches.append( (case, lyes) ) seen.append(case) exc = lno query = exc.target if Exception not in seen: switches.append( (Exception, exc) ) # construct the block's new exits exits = [] for case, oldlink in switches: link = oldlink.copy(rename) assert case is not None link.last_exception = last_exception link.last_exc_value = last_exc_value # make the above two variables unique renaming2 = {} def rename2(v): return renaming2.get(v, v) for v in link.getextravars(): renaming2[v] = Variable(v) link = link.copy(rename2) link.exitcase = case link.prevblock = block exits.append(link) block.recloseblock(*(preserve + exits)) traverse(visit, graph) def transform_xxxitem(graph): # xxx setitem too for block in graph.iterblocks(): if block.operations and block.exitswitch == c_last_exception: last_op = block.operations[-1] if last_op.opname == 'getitem': postfx = [] for exit in block.exits: if exit.exitcase is IndexError: postfx.append('idx') elif exit.exitcase is KeyError: postfx.append('key') if postfx: last_op.opname = last_op.opname + '_' + '_'.join(postfx) def remove_dead_exceptions(graph): """Exceptions can be removed if they are unreachable""" clastexc = c_last_exception def issubclassofmember(cls, seq): for member in seq: if member and issubclass(cls, member): return True return False def visit(block): if not (isinstance(block, Block) and block.exitswitch == clastexc): return exits = [] seen = [] for link in block.exits: case = link.exitcase # check whether exceptions are shadowed if issubclassofmember(case, seen): continue # see if the previous case can be merged while len(exits) > 1: prev = exits[-1] if not (issubclass(prev.exitcase, link.exitcase) and prev.target is link.target and prev.args == link.args): break exits.pop() exits.append(link) seen.append(case) block.recloseblock(*exits) traverse(visit, graph) def join_blocks(graph): """Links can be deleted if they are the single exit of a block and the single entry point of the next block. When this happens, we can append all the operations of the following block to the preceeding block (but renaming variables with the appropriate arguments.) """ entrymap = mkentrymap(graph) block = graph.startblock seen = {block: True} stack = list(block.exits) while stack: link = stack.pop() if (link.prevblock.exitswitch is None and len(entrymap[link.target]) == 1 and link.target.exits): # stop at the returnblock assert len(link.prevblock.exits) == 1 renaming = {} for vprev, vtarg in zip(link.args, link.target.inputargs): renaming[vtarg] = vprev def rename(v): return renaming.get(v, v) def rename_op(op): args = [rename(a) for a in op.args] op = SpaceOperation(op.opname, args, rename(op.result), op.offset) #op = SpaceOperation(op.opname, args, rename(op.result)) return op for op in link.target.operations: link.prevblock.operations.append(rename_op(op)) exits = [] for exit in link.target.exits: newexit = exit.copy(rename) exits.append(newexit) newexitswitch = rename(link.target.exitswitch) link.prevblock.exitswitch = newexitswitch link.prevblock.recloseblock(*exits) if isinstance(newexitswitch, Constant) and newexitswitch != c_last_exception: exits = replace_exitswitch_by_constant(link.prevblock, newexitswitch) stack.extend(exits) else: if link.target not in seen: stack.extend(link.target.exits) seen[link.target] = True def remove_assertion_errors(graph): """Remove branches that go directly to raising an AssertionError, assuming that AssertionError shouldn't occur at run-time. Note that this is how implicit exceptions are removed (see _implicit_ in flowcontext.py). """ def visit(block): if isinstance(block, Block): for i in range(len(block.exits)-1, -1, -1): exit = block.exits[i] if not (exit.target is graph.exceptblock and exit.args[0] == Constant(AssertionError)): continue # can we remove this exit without breaking the graph? if len(block.exits) < 2: break if block.exitswitch == c_last_exception: if exit.exitcase is None: break if len(block.exits) == 2: # removing the last non-exceptional exit block.exitswitch = None exit.exitcase = None # remove this exit lst = list(block.exits) del lst[i] block.recloseblock(*lst) traverse(visit, graph) # _____________________________________________________________________ # decide whether a function has side effects def op_has_side_effects(op): return lloperation.LL_OPERATIONS[op.opname].sideeffects def has_no_side_effects(translator, graph, seen=None): #is the graph specialized? if no we can't say anything #don't cache the result though if translator.rtyper is None: return False else: if graph.startblock not in translator.rtyper.already_seen: return False if seen is None: seen = {} elif graph in seen: return True newseen = seen.copy() newseen[graph] = True for block in graph.iterblocks(): if block is graph.exceptblock: return False # graphs explicitly raising have side-effects for op in block.operations: if rec_op_has_side_effects(translator, op, newseen): return False return True def rec_op_has_side_effects(translator, op, seen=None): if op.opname == "direct_call": g = get_graph(op.args[0], translator) if g is None: return True if not has_no_side_effects(translator, g, seen): return True elif op.opname == "indirect_call": graphs = op.args[-1].value if graphs is None: return True for g in graphs: if not has_no_side_effects(translator, g, seen): return True else: return op_has_side_effects(op) # ___________________________________________________________________________ # remove operations if their result is not used and they have no side effects def transform_dead_op_vars(graph, translator=None): """Remove dead operations and variables that are passed over a link but not used in the target block. Input is a graph.""" blocks = {} def visit(block): if isinstance(block, Block): blocks[block] = True traverse(visit, graph) return transform_dead_op_vars_in_blocks(blocks, translator) # the set of operations that can safely be removed # (they have no side effects, at least in R-Python) CanRemove = {} for _op in ''' newtuple newlist newdict newslice is_true is_ id type issubtype repr str len hash getattr getitem pos neg nonzero abs hex oct ord invert add sub mul truediv floordiv div mod divmod pow lshift rshift and_ or_ xor int float long lt le eq ne gt ge cmp coerce contains iter get'''.split(): CanRemove[_op] = True from pypy.rpython.lltypesystem.lloperation import enum_ops_without_sideeffects for _op in enum_ops_without_sideeffects(): CanRemove[_op] = True del _op CanRemoveBuiltins = { isinstance: True, hasattr: True, } def transform_dead_op_vars_in_blocks(blocks, translator=None): """Remove dead operations and variables that are passed over a link but not used in the target block. Input is a set of blocks""" read_vars = {} # set of variables really used variable_flow = {} # map {Var: list-of-Vars-it-depends-on} def canremove(op, block): if op.opname not in CanRemove: return False if block.exitswitch != c_last_exception: return True # cannot remove the exc-raising operation return op is not block.operations[-1] # compute variable_flow and an initial read_vars for block in blocks: # figure out which variables are ever read for op in block.operations: if not canremove(op, block): # mark the inputs as really needed for arg in op.args: read_vars[arg] = True else: # if CanRemove, only mark dependencies of the result # on the input variables deps = variable_flow.setdefault(op.result, []) deps.extend(op.args) if isinstance(block.exitswitch, Variable): read_vars[block.exitswitch] = True if block.exits: for link in block.exits: if link.target not in blocks: for arg, targetarg in zip(link.args, link.target.inputargs): read_vars[arg] = True read_vars[targetarg] = True else: for arg, targetarg in zip(link.args, link.target.inputargs): deps = variable_flow.setdefault(targetarg, []) deps.append(arg) else: # return and except blocks implicitely use their input variable(s) for arg in block.inputargs: read_vars[arg] = True # an input block's inputargs should not be modified, even if some # of the function's input arguments are not actually used if block.isstartblock: for arg in block.inputargs: read_vars[arg] = True # flow read_vars backwards so that any variable on which a read_vars # depends is also included in read_vars def flow_read_var_backward(pending): pending = list(pending) for var in pending: for prevvar in variable_flow.get(var, []): if prevvar not in read_vars: read_vars[prevvar] = True pending.append(prevvar) flow_read_var_backward(read_vars) for block in blocks: # look for removable operations whose result is never used for i in range(len(block.operations)-1, -1, -1): op = block.operations[i] if op.result not in read_vars: if canremove(op, block): del block.operations[i] elif op.opname == 'simple_call': # XXX we want to have a more effective and safe # way to check if this operation has side effects # ... if op.args and isinstance(op.args[0], Constant): func = op.args[0].value try: if func in CanRemoveBuiltins: del block.operations[i] except TypeError: # func is not hashable pass elif op.opname == 'direct_call': if translator is not None: graph = get_graph(op.args[0], translator) if (graph is not None and has_no_side_effects(translator, graph) and (block.exitswitch != c_last_exception or i != len(block.operations)- 1)): del block.operations[i] # look for output variables never used # warning: this must be completely done *before* we attempt to # remove the corresponding variables from block.inputargs! # Otherwise the link.args get out of sync with the # link.target.inputargs. for link in block.exits: assert len(link.args) == len(link.target.inputargs) for i in range(len(link.args)-1, -1, -1): if link.target.inputargs[i] not in read_vars: del link.args[i] # the above assert would fail here for block in blocks: # look for input variables never used # The corresponding link.args have already been all removed above for i in range(len(block.inputargs)-1, -1, -1): if block.inputargs[i] not in read_vars: del block.inputargs[i] def remove_identical_vars(graph): """When the same variable is passed multiple times into the next block, pass it only once. This enables further optimizations by the annotator, which otherwise doesn't realize that tests performed on one of the copies of the variable also affect the other.""" # This algorithm is based on DataFlowFamilyBuilder, used as a # "phi node remover" (in the SSA sense). 'variable_families' is a # UnionFind object that groups variables by families; variables from the # same family can be identified, and if two input arguments of a block # end up in the same family, then we really remove one of them in favor # of the other. # # The idea is to identify as much variables as possible by trying # iteratively two kinds of phi node removal: # # * "vertical", by identifying variables from different blocks, when # we see that a value just flows unmodified into the next block without # needing any merge (this is what backendopt.ssa.SSI_to_SSA() would do # as well); # # * "horizontal", by identifying two input variables of the same block, # when these two variables' phi nodes have the same argument -- i.e. # when for all possible incoming paths they would get twice the same # value (this is really the purpose of remove_identical_vars()). # from pypy.translator.backendopt.ssa import DataFlowFamilyBuilder builder = DataFlowFamilyBuilder(graph) variable_families = builder.get_variable_families() # vertical removal while True: if not builder.merge_identical_phi_nodes(): # horizontal removal break if not builder.complete(): # vertical removal break for block, links in mkentrymap(graph).items(): if block is graph.startblock: continue renaming = {} family2blockvar = {} kills = [] for i, v in enumerate(block.inputargs): v1 = variable_families.find_rep(v) if v1 in family2blockvar: # already seen -- this variable can be shared with the # previous one renaming[v] = family2blockvar[v1] kills.append(i) else: family2blockvar[v1] = v if renaming: block.renamevariables(renaming) # remove the now-duplicate input variables kills.reverse() # starting from the end for i in kills: del block.inputargs[i] for link in links: del link.args[i] def coalesce_is_true(graph): """coalesce paths that go through an is_true and a directly successive is_true both on the same value, transforming the link into the second is_true from the first to directly jump to the correct target out of the second.""" candidates = [] def has_is_true_exitpath(block): tgts = [] start_op = block.operations[-1] cond_v = start_op.args[0] if block.exitswitch == start_op.result: for exit in block.exits: tgt = exit.target if tgt == block: continue rrenaming = dict(zip(tgt.inputargs,exit.args)) if len(tgt.operations) == 1 and tgt.operations[0].opname == 'is_true': tgt_op = tgt.operations[0] if tgt.exitswitch == tgt_op.result and rrenaming.get(tgt_op.args[0]) == cond_v: tgts.append((exit.exitcase, tgt)) return tgts def visit(block): if isinstance(block, Block) and block.operations and block.operations[-1].opname == 'is_true': tgts = has_is_true_exitpath(block) if tgts: candidates.append((block, tgts)) traverse(visit, graph) while candidates: cand, tgts = candidates.pop() newexits = list(cand.exits) for case, tgt in tgts: exit = cand.exits[case] rrenaming = dict(zip(tgt.inputargs,exit.args)) rrenaming[tgt.operations[0].result] = cand.operations[-1].result def rename(v): return rrenaming.get(v,v) newlink = tgt.exits[case].copy(rename) newexits[case] = newlink cand.recloseblock(*newexits) newtgts = has_is_true_exitpath(cand) if newtgts: candidates.append((cand, newtgts)) # ____________________________________________________________ def detect_list_comprehension(graph): """Look for the pattern: Replace it with marker operations: v0 = newlist() v2 = newlist() v1 = hint(v0, iterable, {'maxlength'}) loop start loop start ... ... exactly one append per loop v1.append(..) and nothing else done with v2 ... ... loop end v2 = hint(v1, {'fence'}) """ # NB. this assumes RPythonicity: we can only iterate over something # that has a len(), and this len() cannot change as long as we are # using the iterator. from pypy.translator.backendopt.ssa import DataFlowFamilyBuilder builder = DataFlowFamilyBuilder(graph) variable_families = builder.get_variable_families() c_append = Constant('append') newlist_v = {} iter_v = {} append_v = [] loopnextblocks = [] # collect relevant operations based on the family of their result for block in graph.iterblocks(): if (len(block.operations) == 1 and block.operations[0].opname == 'next' and block.exitswitch == c_last_exception and len(block.exits) == 2 and block.exits[1].exitcase is StopIteration and block.exits[0].exitcase is None): # it's a straightforward loop start block loopnextblocks.append((block, block.operations[0].args[0])) continue for op in block.operations: if op.opname == 'newlist' and not op.args: vlist = variable_families.find_rep(op.result) newlist_v[vlist] = block if op.opname == 'iter': viter = variable_families.find_rep(op.result) iter_v[viter] = block loops = [] for block, viter in loopnextblocks: viterfamily = variable_families.find_rep(viter) if viterfamily in iter_v: # we have a next(viter) operation where viter comes from a # single known iter() operation. Check that the iter() # operation is in the block just before. iterblock = iter_v[viterfamily] if (len(iterblock.exits) == 1 and iterblock.exitswitch is None and iterblock.exits[0].target is block): # yes - simple case. loops.append((block, iterblock, viterfamily)) if not newlist_v or not loops: return # XXX works with Python 2.4 only: find calls to append encoded as # getattr/simple_call pairs for block in graph.iterblocks(): for i in range(len(block.operations)-1): op = block.operations[i] if op.opname == 'getattr' and op.args[1] == c_append: vlist = variable_families.find_rep(op.args[0]) if vlist in newlist_v: op2 = block.operations[i+1] if (op2.opname == 'simple_call' and len(op2.args) == 2 and op2.args[0] is op.result): append_v.append((op.args[0], op.result, block)) if not append_v: return detector = ListComprehensionDetector(graph, loops, newlist_v, variable_families) graphmutated = False for location in append_v: if graphmutated: # new variables introduced, must restart the whole process return detect_list_comprehension(graph) try: detector.run(*location) except DetectorFailed: pass else: graphmutated = True class DetectorFailed(Exception): pass class ListComprehensionDetector(object): def __init__(self, graph, loops, newlist_v, variable_families): self.graph = graph self.loops = loops self.newlist_v = newlist_v self.variable_families = variable_families self.reachable_cache = {} def enum_blocks_from(self, fromblock, avoid): found = {avoid: True} pending = [fromblock] while pending: block = pending.pop() if block in found: continue yield block found[block] = True for exit in block.exits: pending.append(exit.target) def enum_reachable_blocks(self, fromblock, stop_at, stay_within=None): if fromblock is stop_at: return found = {stop_at: True} pending = [fromblock] while pending: block = pending.pop() if block in found: continue found[block] = True for exit in block.exits: if stay_within is None or exit.target in stay_within: yield exit.target pending.append(exit.target) def reachable_within(self, fromblock, toblock, avoid, stay_within): if toblock is avoid: return False for block in self.enum_reachable_blocks(fromblock, avoid, stay_within): if block is toblock: return True return False def reachable(self, fromblock, toblock, avoid): if toblock is avoid: return False try: return self.reachable_cache[fromblock, toblock, avoid] except KeyError: pass future = [fromblock] for block in self.enum_reachable_blocks(fromblock, avoid): self.reachable_cache[fromblock, block, avoid] = True if block is toblock: return True future.append(block) # 'toblock' is unreachable from 'fromblock', so it is also # unreachable from any of the 'future' blocks for block in future: self.reachable_cache[block, toblock, avoid] = False return False def vlist_alive(self, block): # check if 'block' is in the "cone" of blocks where # the vlistfamily lives try: return self.vlistcone[block] except KeyError: result = bool(self.contains_vlist(block.inputargs)) self.vlistcone[block] = result return result def vlist_escapes(self, block): # check if the vlist "escapes" to uncontrolled places in that block try: return self.escapes[block] except KeyError: for op in block.operations: if op.result is self.vmeth: continue # the single getattr(vlist, 'append') is ok if op.opname == 'getitem': continue # why not allow getitem(vlist, index) too if self.contains_vlist(op.args): result = True break else: result = False self.escapes[block] = result return result def contains_vlist(self, args): for arg in args: if self.variable_families.find_rep(arg) is self.vlistfamily: return arg else: return None def remove_vlist(self, args): removed = 0 for i in range(len(args)-1, -1, -1): arg = self.variable_families.find_rep(args[i]) if arg is self.vlistfamily: del args[i] removed += 1 assert removed == 1 def run(self, vlist, vmeth, appendblock): # first check that the 'append' method object doesn't escape for op in appendblock.operations: if op.opname == 'simple_call' and op.args[0] is vmeth: pass elif vmeth in op.args: raise DetectorFailed # used in another operation for link in appendblock.exits: if vmeth in link.args: raise DetectorFailed # escapes to a next block self.vmeth = vmeth self.vlistfamily = self.variable_families.find_rep(vlist) newlistblock = self.newlist_v[self.vlistfamily] self.vlistcone = {newlistblock: True} self.escapes = {self.graph.returnblock: True, self.graph.exceptblock: True} # in which loop are we? for loopnextblock, iterblock, viterfamily in self.loops: # check that the vlist is alive across the loop head block, # which ensures that we have a whole loop where the vlist # doesn't change if not self.vlist_alive(loopnextblock): continue # no - unrelated loop # check that we cannot go from 'newlist' to 'append' without # going through the 'iter' of our loop (and the following 'next'). # This ensures that the lifetime of vlist is cleanly divided in # "before" and "after" the loop... if self.reachable(newlistblock, appendblock, avoid=iterblock): continue # ... with the possible exception of links from the loop # body jumping back to the loop prologue, between 'newlist' and # 'iter', which we must forbid too: if self.reachable(loopnextblock, iterblock, avoid=newlistblock): continue # there must not be a larger number of calls to 'append' than # the number of elements that 'next' returns, so we must ensure # that we cannot go from 'append' to 'append' again without # passing 'next'... if self.reachable(appendblock, appendblock, avoid=loopnextblock): continue # ... and when the iterator is exhausted, we should no longer # reach 'append' at all. assert loopnextblock.exits[1].exitcase is StopIteration stopblock = loopnextblock.exits[1].target if self.reachable(stopblock, appendblock, avoid=newlistblock): continue # now explicitly find the "loop body" blocks: they are the ones # from which we can reach 'append' without going through 'iter'. # (XXX inefficient) loopbody = {} for block in self.graph.iterblocks(): if (self.vlist_alive(block) and self.reachable(block, appendblock, iterblock)): loopbody[block] = True # if the 'append' is actually after a 'break' or on a path that # can only end up in a 'break', then it won't be recorded as part # of the loop body at all. This is a strange case where we have # basically proved that the list will be of length 1... too # uncommon to worry about, I suspect if appendblock not in loopbody: continue # This candidate loop is acceptable if the list is not escaping # too early, i.e. in the loop header or in the loop body. loopheader = list(self.enum_blocks_from(newlistblock, avoid=loopnextblock)) escapes = False for block in loopheader + loopbody.keys(): assert self.vlist_alive(block) if self.vlist_escapes(block): escapes = True break if not escapes: break # accept this loop! else: raise DetectorFailed # no suitable loop # Found a suitable loop, let's patch the graph: assert iterblock not in loopbody assert loopnextblock in loopbody assert stopblock not in loopbody # at StopIteration, the new list is exactly of the same length as # the one we iterate over if it's not possible to skip the appendblock # in the body: exactlength = not self.reachable_within(loopnextblock, loopnextblock, avoid = appendblock, stay_within = loopbody) # - add a hint(vlist, iterable, {'maxlength'}) in the iterblock, # where we can compute the known maximum length link = iterblock.exits[0] vlist = self.contains_vlist(link.args) assert vlist for op in iterblock.operations: res = self.variable_families.find_rep(op.result) if res is viterfamily: break else: raise AssertionError("lost 'iter' operation") vlength = Variable('maxlength') vlist2 = Variable(vlist) chint = Constant({'maxlength': True}) iterblock.operations += [ SpaceOperation('hint', [vlist, op.args[0], chint], vlist2)] link.args = list(link.args) for i in range(len(link.args)): if link.args[i] is vlist: link.args[i] = vlist2 # - wherever the list exits the loop body, add a 'hint({fence})' from pypy.translator.unsimplify import insert_empty_block for block in loopbody: for link in block.exits: if link.target not in loopbody: vlist = self.contains_vlist(link.args) if vlist is None: continue # list not passed along this link anyway hints = {'fence': True} if (exactlength and block is loopnextblock and link.target is stopblock): hints['exactlength'] = True chints = Constant(hints) newblock = insert_empty_block(None, link) index = link.args.index(vlist) vlist2 = newblock.inputargs[index] vlist3 = Variable(vlist2) newblock.inputargs[index] = vlist3 newblock.operations.append( SpaceOperation('hint', [vlist3, chints], vlist2)) # done! # ____ all passes & simplify_graph all_passes = [ eliminate_empty_blocks, remove_assertion_errors, join_blocks, coalesce_is_true, transform_dead_op_vars, remove_identical_vars, transform_ovfcheck, simplify_exceptions, transform_xxxitem, remove_dead_exceptions, ] def simplify_graph(graph, passes=True): # can take a list of passes to apply, True meaning all """inplace-apply all the existing optimisations to the graph.""" if passes is True: passes = all_passes checkgraph(graph) for pass_ in passes: pass_(graph) checkgraph(graph) def cleanup_graph(graph): checkgraph(graph) eliminate_empty_blocks(graph) join_blocks(graph) remove_identical_vars(graph) checkgraph(graph)
Python
from pypy.translator.flex.modules.flex import * from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc def flash_main( x=1 ): i = Image() i.source = load_resource("py_grossini_png") w = castToWindow( x ) w.addChild(i) r = load_sound_resource("py_sal_mp3") r.play()
Python
from pypy.rpython.extfunc import genericcallable, register_external from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc from pypy.translator.flex.asmgen import add_import def flexTrace(s): pass register_external(flexTrace, args=[str], export_name="_consts_0.flexTrace") def trace(s): pass register_external(trace, args=[str], export_name="trace") def addChild(what): pass register_external(addChild, args=None, export_name="addChild") add_import("mx.controls.Button") class Event(BasicExternal): _fields = { 'localX':int, 'localY':int, 'stageX':int, 'stageY':int, } class Button(BasicExternal): _render_class = "mx.controls.Button" _fields = { 'label': str, 'labelPlacement':str, } _methods = { #'move': MethodDesc([int, int]), #'addEventListener':MethodDesc([str, genericcallable([Event])]) } add_import("mx.controls.Image") class Image(BasicExternal): _render_class = "mx.controls.Image" _fields = { 'data': str, 'source' : str, 'x': int, 'y': int, 'width':int, 'height':int, 'rotation':int, } _methods = { 'load': MethodDesc([str]), 'move': MethodDesc([int,int]), } add_import("flash.display.Sprite") class Sprite(BasicExternal): _render_class = "flash.display.Sprite" _fields = { 'data': str, 'source' : str, 'x': int, 'y': int, 'width':int, 'height':int, 'rotation':int, } _methods = { 'load': MethodDesc([str]), 'move': MethodDesc([int,int]), 'addChild': MethodDesc([Image]), } class Window(BasicExternal): _fields = { 'layout': str, } _methods = { 'addChild': MethodDesc([Image]), 'setActualSize': MethodDesc([int, int]), 'addEventListener':MethodDesc([str, genericcallable([Event])]) } class SpriteWindow(BasicExternal): _fields = { 'layout': str, } _methods = { 'addChild': MethodDesc([Sprite]), 'setActualSize': MethodDesc([int, int]), 'addEventListener':MethodDesc([str, genericcallable([Event])]) } def castToWindow(i): pass register_external(castToWindow, args=[int], result=Window, export_name="_consts_0.castToWindow") def castToSpriteWindow(i): pass register_external(castToSpriteWindow, args=[Window], result=SpriteWindow, export_name="_consts_0.castToSpriteWindow") add_import("flash.net.URLRequest") class URLRequest(BasicExternal): _render_class = "flash.net.URLRequest" _fields = { } _methods = { } def newURLRequest(s): pass register_external(newURLRequest, args=[str], result=URLRequest, export_name="new URLRequest") add_import("flash.media.Sound") class Sound(Button): _render_class = "flash.media.Sound" _fields = { 'data': str, } _methods = { 'load': MethodDesc([URLRequest]), 'play': MethodDesc([]), } def partial(i): pass register_external(partial, args=[genericcallable([Event, str]), str], result=genericcallable([Event]), export_name="_consts_0.partial") add_import("mx.core.SoundAsset") class SoundAsset(Sound): _render_class = "mx.core.SoundAsset" def load_resource(what): pass register_external(load_resource, args=[str], result=str, export_name="load_resource") def load_sprite(what): pass register_external(load_sprite, args=[str], result=Image, export_name="load_sprite") def load_sound_resource(what): pass register_external(load_sound_resource, args=[str], result=SoundAsset, export_name="load_sound_resource")
Python
""" Support classes needed for javascript to translate """
Python
""" mochikit wrappers """ from pypy.rpython.extfunc import genericcallable, register_external from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc from pypy.translator.js.modules import dom # MochiKit.LoggingPane def createLoggingPane(var): pass register_external(createLoggingPane, args=[bool]) # MochiKit.Logging def log(data): print data register_external(log, args=None) def logDebug(data): print "D:", data register_external(logDebug, args=None) def logWarning(data): print "Warning:", data register_external(logWarning, args=None) def logError(data): print "ERROR:", data register_external(logError, args=None) def logFatal(data): print "FATAL:", data register_external(logFatal, args=None) # MochiKit.DOM def escapeHTML(data): return data register_external(escapeHTML, args=[str], result=str) # MochiKit.Base def serializeJSON(data): pass register_external(serializeJSON, args=None, result=str) # MochiKit.Signal class Event(BasicExternal): pass Event._fields = { '_event': dom.Event, } Event._methods = { 'preventDefault': MethodDesc([]), } def connect(src, signal, dest): print 'connecting signal %s' % (signal,) register_external(connect, args=[dom.EventTarget, str, genericcallable([Event])], result=int) def disconnect(id): pass register_external(disconnect, args=[int]) def disconnectAll(src, signal): print 'disconnecting all handlers for signal: %s' % (signal,) register_external(disconnectAll, args=[dom.EventTarget, str])
Python
def get_init(): return True class Sound: def __init__(self, filename): self.filename = filename
Python
class Sprite: def __init__(self): pass class RenderPlain: def __init__(self, sprites): pass def update(self): pass def draw(self, surface): pass
Python
def get(): return [Event() for x in range(2) ] class Event: def __init__(self): self.type = 1
Python
def init(): pass class Rect: pass class Surface: def __init__(self, size): self.size = size def convert(self): return Surface(self.size) def fill(self, color): pass def blit(self, surface, position): pass blit._annspecialcase_ = 'specialize:argtype(2)' def get_size(self): return self.size def get_rect(self, centerx=1): return Rect() def get_width(self): return self.size[0] def get_at(self, position): return (100,100,100) def set_colorkey(self, colorkey, options): pass class Display: def get_surface(self): return Surface((10,10)) def set_mode(self, (x, y)): return Surface((x,y)) def set_caption(self, caption): pass def flip(self): pass def get_rect(self): pass display = Display() class Mouse: def set_visible(self, bool): pass mouse = Mouse()
Python
import pygame class Font: def __init__(self, fontfile, size): self.size = size def render(self, text, alpha, color): return pygame.Surface( (len(text)*self.size, self.size) )
Python
from pygame import * import mixer import sprite import font import time import event import image class error(Exception): pass
Python
import pygame def load(filename): return pygame.Surface((10,10))
Python
ACTIVEEVENT = 1 ANYFORMAT = 268435456 ASYNCBLIT = 4 AUDIO_S16 = 32784 AUDIO_S16LSB = 32784 AUDIO_S16MSB = 36880 AUDIO_S16SYS = 36880 AUDIO_S8 = 32776 AUDIO_U16 = 16 AUDIO_U16LSB = 16 AUDIO_U16MSB = 4112 AUDIO_U16SYS = 4112 AUDIO_U8 = 8 DOUBLEBUF = 1073741824 FULLSCREEN = -2147483648 GL_ACCUM_ALPHA_SIZE = 11 GL_ACCUM_BLUE_SIZE = 10 GL_ACCUM_GREEN_SIZE = 9 GL_ACCUM_RED_SIZE = 8 GL_ALPHA_SIZE = 3 GL_BLUE_SIZE = 2 GL_BUFFER_SIZE = 4 GL_DEPTH_SIZE = 6 GL_DOUBLEBUFFER = 5 GL_GREEN_SIZE = 1 GL_MULTISAMPLEBUFFERS = 13 GL_MULTISAMPLESAMPLES = 14 GL_RED_SIZE = 0 GL_STENCIL_SIZE = 7 GL_STEREO = 12 HAT_CENTERED = 0 HAT_DOWN = 4 HAT_LEFT = 8 HAT_LEFTDOWN = 12 HAT_LEFTUP = 9 HAT_RIGHT = 2 HAT_RIGHTDOWN = 6 HAT_RIGHTUP = 3 HAT_UP = 1 HWACCEL = 256 HWPALETTE = 536870912 HWSURFACE = 1 IYUV_OVERLAY = 1448433993 JOYAXISMOTION = 7 JOYBALLMOTION = 8 JOYBUTTONDOWN = 10 JOYBUTTONUP = 11 JOYHATMOTION = 9 KEYDOWN = 2 KEYUP = 3 KMOD_ALT = 768 KMOD_CAPS = 8192 KMOD_CTRL = 192 KMOD_LALT = 256 KMOD_LCTRL = 64 KMOD_LMETA = 1024 KMOD_LSHIFT = 1 KMOD_META = 3072 KMOD_MODE = 16384 KMOD_NONE = 0 KMOD_NUM = 4096 KMOD_RALT = 512 KMOD_RCTRL = 128 KMOD_RMETA = 2048 KMOD_RSHIFT = 2 KMOD_SHIFT = 3 K_0 = 48 K_1 = 49 K_2 = 50 K_3 = 51 K_4 = 52 K_5 = 53 K_6 = 54 K_7 = 55 K_8 = 56 K_9 = 57 K_AMPERSAND = 38 K_ASTERISK = 42 K_AT = 64 K_BACKQUOTE = 96 K_BACKSLASH = 92 K_BACKSPACE = 8 K_BREAK = 318 K_CAPSLOCK = 301 K_CARET = 94 K_CLEAR = 12 K_COLON = 58 K_COMMA = 44 K_DELETE = 127 K_DOLLAR = 36 K_DOWN = 274 K_END = 279 K_EQUALS = 61 K_ESCAPE = 27 K_EURO = 321 K_EXCLAIM = 33 K_F1 = 282 K_F10 = 291 K_F11 = 292 K_F12 = 293 K_F13 = 294 K_F14 = 295 K_F15 = 296 K_F2 = 283 K_F3 = 284 K_F4 = 285 K_F5 = 286 K_F6 = 287 K_F7 = 288 K_F8 = 289 K_F9 = 290 K_FIRST = 0 K_GREATER = 62 K_HASH = 35 K_HELP = 315 K_HOME = 278 K_INSERT = 277 K_KP0 = 256 K_KP1 = 257 K_KP2 = 258 K_KP3 = 259 K_KP4 = 260 K_KP5 = 261 K_KP6 = 262 K_KP7 = 263 K_KP8 = 264 K_KP9 = 265 K_KP_DIVIDE = 267 K_KP_ENTER = 271 K_KP_EQUALS = 272 K_KP_MINUS = 269 K_KP_MULTIPLY = 268 K_KP_PERIOD = 266 K_KP_PLUS = 270 K_LALT = 308 K_LAST = 323 K_LCTRL = 306 K_LEFT = 276 K_LEFTBRACKET = 91 K_LEFTPAREN = 40 K_LESS = 60 K_LMETA = 310 K_LSHIFT = 304 K_LSUPER = 311 K_MENU = 319 K_MINUS = 45 K_MODE = 313 K_NUMLOCK = 300 K_PAGEDOWN = 281 K_PAGEUP = 280 K_PAUSE = 19 K_PERIOD = 46 K_PLUS = 43 K_POWER = 320 K_PRINT = 316 K_QUESTION = 63 K_QUOTE = 39 K_QUOTEDBL = 34 K_RALT = 307 K_RCTRL = 305 K_RETURN = 13 K_RIGHT = 275 K_RIGHTBRACKET = 93 K_RIGHTPAREN = 41 K_RMETA = 309 K_RSHIFT = 303 K_RSUPER = 312 K_SCROLLOCK = 302 K_SEMICOLON = 59 K_SLASH = 47 K_SPACE = 32 K_SYSREQ = 317 K_TAB = 9 K_UNDERSCORE = 95 K_UNKNOWN = 0 K_UP = 273 K_a = 97 K_b = 98 K_c = 99 K_d = 100 K_e = 101 K_f = 102 K_g = 103 K_h = 104 K_i = 105 K_j = 106 K_k = 107 K_l = 108 K_m = 109 K_n = 110 K_o = 111 K_p = 112 K_q = 113 K_r = 114 K_s = 115 K_t = 116 K_u = 117 K_v = 118 K_w = 119 K_x = 120 K_y = 121 K_z = 122 MOUSEBUTTONDOWN = 5 MOUSEBUTTONUP = 6 MOUSEMOTION = 4 NOEVENT = 0 NOFRAME = 32 NUMEVENTS = 32 OPENGL = 2 OPENGLBLIT = 10 PREALLOC = 16777216 QUIT = 12 RESIZABLE = 16 RLEACCEL = 16384 RLEACCELOK = 8192 SRCALPHA = 65536 SRCCOLORKEY = 4096 SWSURFACE = 0 SYSWMEVENT = 13 TIMER_RESOLUTION = 10 USEREVENT = 24 UYVY_OVERLAY = 1498831189 VIDEOEXPOSE = 17 VIDEORESIZE = 16 YUY2_OVERLAY = 844715353 YV12_OVERLAY = 842094169 YVYU_OVERLAY = 1431918169
Python
class Clock: def tick(self, delta): pass
Python
"""Document Object Model support this provides a mock browser API, both the standard DOM level 2 stuff as the browser-specific additions in addition this provides the necessary descriptions that allow rpython code that calls the browser DOM API to be translated note that the API is not and will not be complete: more exotic features will most probably not behave as expected, or are not implemented at all http://www.w3.org/DOM/ - main standard http://www.w3schools.com/dhtml/dhtml_dom.asp - more informal stuff http://developer.mozilla.org/en/docs/Gecko_DOM_Reference - Gecko reference """ import time import re import urllib from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc from pypy.rlib.nonconst import NonConstant from pypy.rpython.extfunc import genericcallable, register_external from xml.dom import minidom from pypy.annotation.signature import annotation from pypy.annotation import model as annmodel # EventTarget is the base class for Nodes and Window class EventTarget(BasicExternal): def addEventListener(self, type, listener, useCapture): if not hasattr(self._original, '_events'): self._original._events = [] # XXX note that useCapture is ignored... self._original._events.append((type, listener, useCapture)) def dispatchEvent(self, event): if event._cancelled: return event.currentTarget = self if event.target is None: event.target = self if event.originalTarget is None: event.originalTarget = self if hasattr(self._original, '_events'): for etype, handler, capture in self._original._events: if etype == event.type: handler(event) if event._cancelled or event.cancelBubble: return parent = getattr(self, 'parentNode', None) if parent is not None: parent.dispatchEvent(event) def removeEventListener(self, type, listener, useCapture): if not hasattr(self._original, '_events'): raise ValueError('no registration for listener') filtered = [] for data in self._original._events: if data != (type, listener, useCapture): filtered.append(data) if filtered == self._original._events: raise ValueError('no registration for listener') self._original._events = filtered # XML node (level 2 basically) implementation # the following classes are mostly wrappers around minidom nodes that try to # mimic HTML DOM behaviour by implementing browser API and changing the # behaviour a bit class Node(EventTarget): """base class of all node types""" _original = None def __init__(self, node=None): self._original = node def __getattr__(self, name): """attribute access gets proxied to the contained minidom node all returned minidom nodes are wrapped as Nodes """ try: return super(Node, self).__getattr__(name) except AttributeError: pass if (name not in self._fields and (not hasattr(self, '_methods') or name not in self._methods)): raise NameError, name value = getattr(self._original, name) return _wrap(value) def __setattr__(self, name, value): """set an attribute on the wrapped node""" if name in dir(self) or name.startswith('_'): return super(Node, self).__setattr__(name, value) if name not in self._fields: raise NameError, name setattr(self._original, name, value) def __eq__(self, other): original = getattr(other, '_original', other) return original is self._original def __ne__(self, other): original = getattr(other, '_original', other) return original is not self._original def getElementsByTagName(self, name): name = name.lower() return self.__getattr__('getElementsByTagName')(name) def __repr__(self): return '<%s %s>' % (self.__class__.__name__, self.nodeName) def _getClassName(self): return self.getAttribute('class') def _setClassName(self, name): self.setAttribute('class', name) className = property(_getClassName, _setClassName) def _getId(self): return self.getAttribute('id') def _setId(self, id): self.setAttribute('id', id) id = property(_getId, _setId) class Element(Node): nodeType = 1 style = None def _style(self): style = getattr(self._original, '_style', None) if style is not None: return style styles = {} if self._original.hasAttribute('style'): for t in self._original.getAttribute('style').split(';'): name, value = t.split(':') dashcharpairs = re.findall('-\w', name) for p in dashcharpairs: name = name.replace(p, p[1].upper()) styles[name.strip()] = value.strip() style = Style(styles) self._original._style = style return style style = property(_style) def _nodeName(self): return self._original.nodeName.upper() nodeName = property(_nodeName) def _get_innerHTML(self): ret = [] for child in self.childNodes: ret.append(_serialize_html(child)) return ''.join(ret) def _set_innerHTML(self, html): dom = minidom.parseString('<doc>%s</doc>' % (html,)) while self.childNodes: self.removeChild(self.lastChild) for child in dom.documentElement.childNodes: child = self.ownerDocument.importNode(child, True) self._original.appendChild(child) del dom innerHTML = property(_get_innerHTML, _set_innerHTML) def scrollIntoView(self): pass class Attribute(Node): nodeType = 2 class Text(Node): nodeType = 3 class Comment(Node): nodeType = 8 class Document(Node): nodeType = 9 def createEvent(self, group=''): """create an event note that the group argument is ignored """ if group in ('KeyboardEvent', 'KeyboardEvents'): return KeyEvent() elif group in ('MouseEvent', 'MouseEvents'): return MouseEvent() return Event() def getElementById(self, id): nodes = self.getElementsByTagName('*') for node in nodes: if node.getAttribute('id') == id: return node # the standard DOM stuff that doesn't directly deal with XML # note that we're mimicking the standard (Mozilla) APIs, so things tested # against this code may not work in Internet Explorer # XXX note that we store the events on the wrapped minidom node to avoid losing # them on re-wrapping class Event(BasicExternal): def initEvent(self, type, bubbles, cancelable): self.type = type self.cancelBubble = not bubbles self.cancelable = cancelable self.target = None self.currentTarget = None self.originalTarget = None self._cancelled = False def preventDefault(self): if not self.cancelable: raise TypeError('event can not be canceled') self._cancelled = True def stopPropagation(self): self.cancelBubble = True class KeyEvent(Event): pass class MouseEvent(Event): pass class Style(BasicExternal): def __init__(self, styles={}): for name, value in styles.iteritems(): setattr(self, name, value) def __getattr__(self, name): if name not in self._fields: raise AttributeError, name return None def _tostring(self): ret = [] for name in sorted(self._fields): value = getattr(self, name, None) if value is not None: ret.append(' ') for char in name: if char.upper() == char: char = '-%s' % (char.lower(),) ret.append(char) ret.append(': %s;' % (value,)) return ''.join(ret[1:]) # non-DOM ('DOM level 0') stuff # Window is the main environment, the root node of the JS object tree class Location(BasicExternal): _fields = { 'hostname' : str, 'href' : str, 'hash' : str, 'host' : str, 'pathname' : str, 'port' : str, 'protocol' : str, 'search' : str, } _methods = { 'assign' : MethodDesc([str]), 'reload' : MethodDesc([bool]), 'replace' : MethodDesc([str]), 'toString' : MethodDesc([], str), } class Navigator(BasicExternal): def __init__(self): self.appName = 'Netscape' class Window(EventTarget): def __init__(self, html=('<html><head><title>Untitled document</title>' '</head><body></body></html>'), parent=None): super(Window, self).__init__() self._html = html self.document = Document(minidom.parseString(html)) # references to windows self.content = self self.self = self self.window = self self.parent = parent or self self.top = self.parent while 1: if self.top.parent is self.top: break self.top = self.top.parent # other properties self.closed = True self._location = 'about:blank' self._original = self # for EventTarget interface (XXX a bit nasty) self.navigator = Navigator() def __getattr__(self, name): return globals()[name] def _getLocation(self): return self._location def _setLocation(self, newloc): url = urllib.urlopen(newloc) html = url.read() self.document = Document(minidom.parseString(html)) location = property(_getLocation, _setLocation) scrollX = 0 scrollMaxX = 0 scrollY = 0 scrollMaxY = 0 def some_fun(): pass def setTimeout(func, delay): pass register_external(setTimeout, args=[genericcallable([]), int], result=None) window = Window() document = window.document Window._render_name = 'window' Document._render_name = 'document' # rtyper stuff EventTarget._fields = { 'onabort' : genericcallable([Event]), 'onblur' : genericcallable([Event]), 'onchange' : genericcallable([Event]), 'onclick' : genericcallable([MouseEvent]), 'onclose' : genericcallable([MouseEvent]), 'ondblclick' : genericcallable([MouseEvent]), 'ondragdrop' : genericcallable([MouseEvent]), 'onerror' : genericcallable([MouseEvent]), 'onfocus' : genericcallable([Event]), 'onkeydown' : genericcallable([KeyEvent]), 'onkeypress' : genericcallable([KeyEvent]), 'onkeyup' : genericcallable([KeyEvent]), 'onload' : genericcallable([KeyEvent]), 'onmousedown' : genericcallable([MouseEvent]), 'onmousemove' : genericcallable([MouseEvent]), 'onmouseup' : genericcallable([MouseEvent]), 'onmouseover' : genericcallable([MouseEvent]), 'onresize' : genericcallable([Event]), 'onscroll' : genericcallable([MouseEvent]), 'onselect' : genericcallable([MouseEvent]), 'onsubmit' : genericcallable([MouseEvent]), 'onunload' : genericcallable([Event]), } lambda_returning_true = genericcallable([Event]) EventTarget._methods = { 'addEventListener' : MethodDesc([str, lambda_returning_true, bool]), 'dispatchEvent' : MethodDesc([str], bool), 'removeEventListener' : MethodDesc([str, lambda_returning_true, bool]), } Node._fields = EventTarget._fields.copy() Node._fields.update({ 'childNodes' : [Element], 'firstChild' : Element, 'lastChild' : Element, 'localName' : str, 'name' : str, 'namespaceURI' : str, 'nextSibling' : Element, 'nodeName' : str, 'nodeType' : int, 'nodeValue' : str, 'ownerDocument' : Document, 'parentNode' : Element, 'prefix' : str, 'previousSibling': Element, 'tagName' : str, 'textContent' : str, }) Node._methods = EventTarget._methods.copy() Node._methods.update({ 'appendChild' : MethodDesc([Element]), 'cloneNode' : MethodDesc([int], Element), 'getElementsByTagName' : MethodDesc([str], [Element]), 'hasChildNodes' : MethodDesc([], bool), 'insertBefore' : MethodDesc([Element], Element), 'normalize' : MethodDesc([]), 'removeChild' : MethodDesc([Element]), 'replaceChild' : MethodDesc([Element], Element), }) Element._fields = Node._fields.copy() Element._fields.update({ 'attributes' : [Attribute], 'className' : str, 'clientHeight' : int, 'clientWidth' : int, 'clientLeft' : int, 'clientTop' : int, 'dir' : str, 'innerHTML' : str, 'id' : str, 'lang' : str, 'offsetHeight' : int, 'offsetLeft' : int, 'offsetParent' : int, 'offsetTop' : int, 'offsetWidth' : int, 'scrollHeight' : int, 'scrollLeft' : int, 'scrollTop' : int, 'scrollWidth' : int, 'disabled': bool, # HTML specific 'style' : Style, 'tabIndex' : int, # XXX: From HTMLInputElement to make pythonconsole work. 'value': str, 'checked': bool, # IMG specific 'src': str, }) Element._methods = Node._methods.copy() Element._methods.update({ 'getAttribute' : MethodDesc([str], str), 'getAttributeNS' : MethodDesc([str], str), 'getAttributeNode' : MethodDesc([str], Element), 'getAttributeNodeNS' : MethodDesc([str], Element), 'hasAttribute' : MethodDesc([str], bool), 'hasAttributeNS' : MethodDesc([str], bool), 'hasAttributes' : MethodDesc([], bool), 'removeAttribute' : MethodDesc([str]), 'removeAttributeNS' : MethodDesc([str]), 'removeAttributeNode' : MethodDesc([Element], str), 'setAttribute' : MethodDesc([str, str]), 'setAttributeNS' : MethodDesc([str]), 'setAttributeNode' : MethodDesc([Element], Element), 'setAttributeNodeNS' : MethodDesc([str, Element], Element), # HTML specific 'blur' : MethodDesc([]), 'click' : MethodDesc([]), 'focus' : MethodDesc([]), 'scrollIntoView' : MethodDesc([]), 'supports' : MethodDesc([str, float]), }) Document._fields = Node._fields.copy() Document._fields.update({ 'characterSet' : str, # 'contentWindow' : Window(), XXX doesn't exist, only on iframe 'doctype' : str, 'documentElement' : Element, 'styleSheets' : [Style], 'alinkColor' : str, 'bgColor' : str, 'body' : Element, 'cookie' : str, 'defaultView' : Window, 'domain' : str, 'embeds' : [Element], 'fgColor' : str, 'forms' : [Element], 'height' : int, 'images' : [Element], 'lastModified' : str, 'linkColor' : str, 'links' : [Element], 'referrer' : str, 'title' : str, 'URL' : str, 'vlinkColor' : str, 'width' : int, }) Document._methods = Node._methods.copy() Document._methods.update({ 'createAttribute' : MethodDesc([str], Element), 'createDocumentFragment' : MethodDesc([], Element), 'createElement' : MethodDesc([str], Element), 'createElementNS' : MethodDesc([str], Element), 'createEvent' : MethodDesc([str], Event), 'createTextNode' : MethodDesc([str], Element), #'createRange' : MethodDesc(["aa"], Range()) - don't know what to do here 'getElementById' : MethodDesc([str], Element), 'getElementsByName' : MethodDesc([str], [Element]), 'importNode' : MethodDesc([Element, bool], Element), 'clear' : MethodDesc([]), 'close' : MethodDesc([]), 'open' : MethodDesc([]), 'write' : MethodDesc([str]), 'writeln' : MethodDesc([str]), }) Window._fields = EventTarget._fields.copy() Window._fields.update({ 'content' : Window, 'closed' : bool, # 'crypto' : Crypto() - not implemented in Gecko, leave alone 'defaultStatus' : str, 'document' : Document, # 'frameElement' : - leave alone 'frames' : [Window], 'history' : [str], 'innerHeight' : int, 'innerWidth' : int, 'length' : int, 'location' : Location, 'name' : str, # 'preference' : # denied in gecko 'opener' : Window, 'outerHeight' : int, 'outerWidth' : int, 'pageXOffset' : int, 'pageYOffset' : int, 'parent' : Window, # 'personalbar' : - disallowed # 'screen' : Screen() - not part of the standard, allow it if you want 'screenX' : int, 'screenY' : int, 'scrollMaxX' : int, 'scrollMaxY' : int, 'scrollX' : int, 'scrollY' : int, 'self' : Window, 'status' : str, 'top' : Window, 'window' : Window, 'navigator': Navigator, }) Window._methods = Node._methods.copy() Window._methods.update({ 'alert' : MethodDesc([str]), 'atob' : MethodDesc([str], str), 'back' : MethodDesc([]), 'blur' : MethodDesc([]), 'btoa' : MethodDesc([str], str), 'close' : MethodDesc([]), 'confirm' : MethodDesc([str], bool), 'dump' : MethodDesc([str]), 'escape' : MethodDesc([str], str), #'find' : MethodDesc(["aa"], - gecko only 'focus' : MethodDesc([]), 'forward' : MethodDesc([]), 'getComputedStyle' : MethodDesc([Element, str], Style), 'home' : MethodDesc([]), 'open' : MethodDesc([str]), }) Style._fields = { 'azimuth' : str, 'background' : str, 'backgroundAttachment' : str, 'backgroundColor' : str, 'backgroundImage' : str, 'backgroundPosition' : str, 'backgroundRepeat' : str, 'border' : str, 'borderBottom' : str, 'borderBottomColor' : str, 'borderBottomStyle' : str, 'borderBottomWidth' : str, 'borderCollapse' : str, 'borderColor' : str, 'borderLeft' : str, 'borderLeftColor' : str, 'borderLeftStyle' : str, 'borderLeftWidth' : str, 'borderRight' : str, 'borderRightColor' : str, 'borderRightStyle' : str, 'borderRightWidth' : str, 'borderSpacing' : str, 'borderStyle' : str, 'borderTop' : str, 'borderTopColor' : str, 'borderTopStyle' : str, 'borderTopWidth' : str, 'borderWidth' : str, 'bottom' : str, 'captionSide' : str, 'clear' : str, 'clip' : str, 'color' : str, 'content' : str, 'counterIncrement' : str, 'counterReset' : str, 'cssFloat' : str, 'cssText' : str, 'cue' : str, 'cueAfter' : str, 'onBefore' : str, 'cursor' : str, 'direction' : str, 'displays' : str, 'elevation' : str, 'emptyCells' : str, 'font' : str, 'fontFamily' : str, 'fontSize' : str, 'fontSizeAdjust' : str, 'fontStretch' : str, 'fontStyle' : str, 'fontVariant' : str, 'fontWeight' : str, 'height' : str, 'left' : str, 'length' : str, 'letterSpacing' : str, 'lineHeight' : str, 'listStyle' : str, 'listStyleImage' : str, 'listStylePosition' : str, 'listStyleType' : str, 'margin' : str, 'marginBottom' : str, 'marginLeft' : str, 'marginRight' : str, 'marginTop' : str, 'markerOffset' : str, 'marks' : str, 'maxHeight' : str, 'maxWidth' : str, 'minHeight' : str, 'minWidth' : str, 'MozBinding' : str, 'MozOpacity' : str, 'orphans' : str, 'outline' : str, 'outlineColor' : str, 'outlineStyle' : str, 'outlineWidth' : str, 'overflow' : str, 'padding' : str, 'paddingBottom' : str, 'paddingLeft' : str, 'paddingRight' : str, 'paddingTop' : str, 'page' : str, 'pageBreakAfter' : str, 'pageBreakBefore' : str, 'pageBreakInside' : str, 'parentRule' : str, 'pause' : str, 'pauseAfter' : str, 'pauseBefore' : str, 'pitch' : str, 'pitchRange' : str, 'playDuring' : str, 'position' : str, 'quotes' : str, 'richness' : str, 'right' : str, 'size' : str, 'speak' : str, 'speakHeader' : str, 'speakNumeral' : str, 'speakPunctuation' : str, 'speechRate' : str, 'stress' : str, 'tableLayout' : str, 'textAlign' : str, 'textDecoration' : str, 'textIndent' : str, 'textShadow' : str, 'textTransform' : str, 'top' : str, 'unicodeBidi' : str, 'verticalAlign' : str, 'visibility' : str, 'voiceFamily' : str, 'volume' : str, 'whiteSpace' : str, 'widows' : str, 'width' : str, 'wordSpacing' : str, 'zIndex' : str, } Event._fields = { 'bubbles': bool, 'cancelBubble': bool, 'cancelable': bool, 'currentTarget': Element, 'detail': int, 'relatedTarget': Element, 'target': Element, 'type': str, 'returnValue': bool, 'which': int, 'keyCode' : int, 'charCode': int, 'altKey' : bool, 'ctrlKey' : bool, 'shiftKey': bool, } Event._methods = { 'initEvent': MethodDesc([str, bool, bool]), 'preventDefault': MethodDesc([]), 'stopPropagation': MethodDesc([]), } KeyEvent._methods = Event._methods.copy() KeyEvent._fields = Event._fields.copy() Navigator._methods = { } Navigator._fields = { 'appName': str, } class _FunctionWrapper(object): """makes sure function return values are wrapped if appropriate""" def __init__(self, callable): self._original = callable def __call__(self, *args, **kwargs): args = list(args) for i, arg in enumerate(args): if isinstance(arg, Node): args[i] = arg._original for name, arg in kwargs.iteritems(): if isinstance(arg, Node): kwargs[arg] = arg._original value = self._original(*args, **kwargs) return _wrap(value) _typetoclass = { 1: Element, 2: Attribute, 3: Text, 8: Comment, 9: Document, } def _wrap(value): if isinstance(value, minidom.Node): nodeclass = _typetoclass[value.nodeType] return nodeclass(value) elif callable(value): return _FunctionWrapper(value) # nothing fancier in minidom, i hope... # XXX and please don't add anything fancier either ;) elif isinstance(value, list): return [_wrap(x) for x in value] return value # some helper functions def _quote_html(text): for char, e in [('&', 'amp'), ('<', 'lt'), ('>', 'gt'), ('"', 'quot'), ("'", 'apos')]: text = text.replace(char, '&%s;' % (e,)) return text _singletons = ['link', 'meta'] def _serialize_html(node): ret = [] if node.nodeType in [3, 8]: return node.nodeValue elif node.nodeType == 1: original = getattr(node, '_original', node) nodeName = original.nodeName ret += ['<', nodeName] if len(node.attributes): for aname in node.attributes.keys(): if aname == 'style': continue attr = node.attributes[aname] ret.append(' %s="%s"' % (attr.nodeName, _quote_html(attr.nodeValue))) styles = getattr(original, '_style', None) if styles: ret.append(' style="%s"' % (_quote_html(styles._tostring()),)) if len(node.childNodes) or nodeName not in _singletons: ret.append('>') for child in node.childNodes: if child.nodeType == 1: ret.append(_serialize_html(child)) else: ret.append(_quote_html(child.nodeValue)) ret += ['</', nodeName, '>'] else: ret.append(' />') else: raise ValueError('unsupported node type %s' % (node.nodeType,)) return ''.join(ret) def alert(msg): window.alert(msg) # initialization # set the global 'window' instance to an empty HTML document, override using # dom.window = Window(html) (this will also set dom.document)
Python
import string import types ## json.py implements a JSON (http://json.org) reader and writer. ## Copyright (C) 2005 Patrick D. Logan ## Contact mailto:patrickdlogan@stardecisions.com ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class _StringGenerator(object): def __init__(self, string): self.string = string self.index = -1 def peek(self): i = self.index + 1 if i < len(self.string): return self.string[i] else: return None def next(self): self.index += 1 if self.index < len(self.string): return self.string[self.index] else: raise StopIteration def all(self): return self.string class WriteException(Exception): pass class ReadException(Exception): pass class JsonReader(object): hex_digits = {'A': 10,'B': 11,'C': 12,'D': 13,'E': 14,'F':15} escapes = {'t':'\t','n':'\n','f':'\f','r':'\r','b':'\b'} def read(self, s): self._generator = _StringGenerator(s) result = self._read() return result def _read(self): self._eatWhitespace() peek = self._peek() if peek is None: raise ReadException, "Nothing to read: '%s'" % self._generator.all() if peek == '{': return self._readObject() elif peek == '[': return self._readArray() elif peek == '"': return self._readString() elif peek == '-' or peek.isdigit(): return self._readNumber() elif peek == 't': return self._readTrue() elif peek == 'f': return self._readFalse() elif peek == 'n': return self._readNull() elif peek == '/': self._readComment() return self._read() else: raise ReadException, "Input is not valid JSON: '%s'" % self._generator.all() def _readTrue(self): self._assertNext('t', "true") self._assertNext('r', "true") self._assertNext('u', "true") self._assertNext('e', "true") return True def _readFalse(self): self._assertNext('f', "false") self._assertNext('a', "false") self._assertNext('l', "false") self._assertNext('s', "false") self._assertNext('e', "false") return False def _readNull(self): self._assertNext('n', "null") self._assertNext('u', "null") self._assertNext('l', "null") self._assertNext('l', "null") return None def _assertNext(self, ch, target): if self._next() != ch: raise ReadException, "Trying to read %s: '%s'" % (target, self._generator.all()) def _readNumber(self): isfloat = False result = self._next() peek = self._peek() while peek is not None and (peek.isdigit() or peek == "."): isfloat = isfloat or peek == "." result = result + self._next() peek = self._peek() try: if isfloat: return float(result) else: return int(result) except ValueError: raise ReadException, "Not a valid JSON number: '%s'" % result def _readString(self): result = "" assert self._next() == '"' try: while self._peek() != '"': ch = self._next() if ch == "\\": ch = self._next() if ch in 'brnft': ch = self.escapes[ch] elif ch == "u": ch4096 = self._next() ch256 = self._next() ch16 = self._next() ch1 = self._next() n = 4096 * self._hexDigitToInt(ch4096) n += 256 * self._hexDigitToInt(ch256) n += 16 * self._hexDigitToInt(ch16) n += self._hexDigitToInt(ch1) ch = unichr(n) elif ch not in '"/\\': raise ReadException, "Not a valid escaped JSON character: '%s' in %s" % (ch, self._generator.all()) result = result + ch except StopIteration: raise ReadException, "Not a valid JSON string: '%s'" % self._generator.all() assert self._next() == '"' return result def _hexDigitToInt(self, ch): try: result = self.hex_digits[ch.upper()] except KeyError: try: result = int(ch) except ValueError: raise ReadException, "The character %s is not a hex digit." % ch return result def _readComment(self): assert self._next() == "/" second = self._next() if second == "/": self._readDoubleSolidusComment() elif second == '*': self._readCStyleComment() else: raise ReadException, "Not a valid JSON comment: %s" % self._generator.all() def _readCStyleComment(self): try: done = False while not done: ch = self._next() done = (ch == "*" and self._peek() == "/") if not done and ch == "/" and self._peek() == "*": raise ReadException, "Not a valid JSON comment: %s, '/*' cannot be embedded in the comment." % self._generator.all() self._next() except StopIteration: raise ReadException, "Not a valid JSON comment: %s, expected */" % self._generator.all() def _readDoubleSolidusComment(self): try: ch = self._next() while ch != "\r" and ch != "\n": ch = self._next() except StopIteration: pass def _readArray(self): result = [] assert self._next() == '[' done = self._peek() == ']' while not done: item = self._read() result.append(item) self._eatWhitespace() done = self._peek() == ']' if not done: ch = self._next() if ch != ",": raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch) assert ']' == self._next() return result def _readObject(self): result = {} assert self._next() == '{' done = self._peek() == '}' while not done: key = self._read() if type(key) is not types.StringType: raise ReadException, "Not a valid JSON object key (should be a string): %s" % key self._eatWhitespace() ch = self._next() if ch != ":": raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch) self._eatWhitespace() val = self._read() result[key] = val self._eatWhitespace() done = self._peek() == '}' if not done: ch = self._next() if ch != ",": raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch) assert self._next() == "}" return result def _eatWhitespace(self): p = self._peek() while p is not None and p in string.whitespace or p == '/': if p == '/': self._readComment() else: self._next() p = self._peek() def _peek(self): return self._generator.peek() def _next(self): return self._generator.next() class JsonWriter(object): def _append(self, s): self._results.append(s) def write(self, obj, escaped_forward_slash=False): self._escaped_forward_slash = escaped_forward_slash self._results = [] self._write(obj) return "".join(self._results) def _write(self, obj): ty = type(obj) if ty is types.DictType: n = len(obj) self._append("{") for k, v in obj.items(): self._write(k) self._append(":") self._write(v) n = n - 1 if n > 0: self._append(",") self._append("}") elif ty is types.ListType or ty is types.TupleType: n = len(obj) self._append("[") for item in obj: self._write(item) n = n - 1 if n > 0: self._append(",") self._append("]") elif ty is types.StringType or ty is types.UnicodeType: self._append('"') obj = obj.replace('\\', r'\\') if self._escaped_forward_slash: obj = obj.replace('/', r'\/') obj = obj.replace('"', r'\"') obj = obj.replace('\b', r'\b') obj = obj.replace('\f', r'\f') obj = obj.replace('\n', r'\n') obj = obj.replace('\r', r'\r') obj = obj.replace('\t', r'\t') self._append(obj) self._append('"') elif ty is types.IntType or ty is types.LongType: self._append(str(obj)) elif ty is types.FloatType: self._append("%f" % obj) elif obj is True: self._append("true") elif obj is False: self._append("false") elif obj is None: self._append("null") else: raise WriteException, "Cannot write in JSON: %s" % repr(obj) def write(obj, escaped_forward_slash=False): return JsonWriter().write(obj, escaped_forward_slash) def read(s): return JsonReader().read(s)
Python
''' reference material: http://webreference.com/javascript/reference/core_ref/ http://webreference.com/programming/javascript/ http://mochikit.com/ http://www.mozilla.org/js/spidermonkey/ svn co http://codespeak.net/svn/kupu/trunk/ecmaunit ''' import py import os from pypy.rpython.rmodel import inputconst from pypy.rpython.typesystem import getfunctionptr from pypy.rpython.lltypesystem import lltype from pypy.rpython.ootypesystem import ootype from pypy.tool.udir import udir from pypy.translator.flex.log import log from pypy.translator.flex.asmgen import AsmGen import pypy.translator.flex.asmgen as asmgen from pypy.translator.flex.jts import JTS from pypy.translator.flex.opcodes import opcodes from pypy.translator.flex.function import Function from pypy.translator.flex.database import LowLevelDatabase from pypy.translator.oosupport.genoo import GenOO from heapq import heappush, heappop from StringIO import StringIO def _path_join(root_path, *paths): path = root_path for p in paths: path = os.path.join(path, p) return path class Tee(object): def __init__(self, *args): self.outfiles = args def write(self, s): for outfile in self.outfiles: outfile.write(s) def close(self): for outfile in self.outfiles: if outfile is not sys.stdout: outfile.close() class JS(GenOO): TypeSystem = JTS opcodes = opcodes Function = Function Database = LowLevelDatabase def __init__(self, translator, functions=[], stackless=False, compress=False, \ logging=False, use_debug=False): if not isinstance(functions, list): functions = [functions] GenOO.__init__(self, udir, translator, None) pending_graphs = [translator.annotator.bookkeeper.getdesc(f).cachedgraph(None) for f in functions ] for graph in pending_graphs: self.db.pending_function(graph) self.db.translator = translator self.use_debug = use_debug self.assembly_name = self.translator.graphs[0].name self.tmpfile = udir.join(self.assembly_name + '.js') def gen_pendings(self): while self.db._pending_nodes: node = self.db._pending_nodes.pop() to_render = [] nparent = node while nparent.order != 0: nparent = nparent.parent to_render.append(nparent) to_render.reverse() for i in to_render: i.render(self.ilasm) node.render(self.ilasm) def generate_communication_proxy(self): """ Render necessary stuff aroundc communication proxies """ for proxy in self.db.proxies: proxy.render(self.ilasm) def create_assembler(self): out = self.tmpfile.open('w') return AsmGen(out, self.assembly_name) def generate_source(self): self.ilasm = self.create_assembler() self.fix_names() self.gen_entrypoint() constants_code_generator = asmgen.CodeGenerator(open("py/_consts_0.as", "w")) constants_code_generator.write("package py ") constants_code_generator.openblock() constants_code_generator.writeline("public var _consts_0 = {};") constants_code_generator.closeblock() constants_code_generator = asmgen.CodeGenerator(open("py/__load_consts_flex.as", "w")) constants_code_generator.write("package py ") constants_code_generator.openblock() constants_code_generator.writeline("import flash.net.*;"); while self.db._pending_nodes: self.gen_pendings() self.ilasm.push_gen( constants_code_generator ) self.db.gen_constants(self.ilasm, self.db._pending_nodes) self.ilasm.pop_gen() self.ilasm.push_gen( constants_code_generator ) self.ilasm.end_consts() const_filename = _path_join(os.path.dirname(__file__), 'jssrc', 'library.as') constants_code_generator.write( open(const_filename).read() ) constants_code_generator.closeblock() self.ilasm.close() self.ilasm.pop_gen() self.ilasm.close() assert len(self.ilasm.right_hand) == 0 return self.tmpfile.strpath def write_source(self): # write down additional functions # FIXME: when used with browser option it should probably # not be used as inlined, rather another script to load # this is just workaround self.generate_source() sio = StringIO() data = self.tmpfile.open().read() self.copy_py_resource() src_filename = _path_join(os.path.dirname(__file__), 'jssrc', 'misc.as') flex_filename = _path_join(os.path.dirname(__file__), 'jssrc', 'flex.mxml') f = self.tmpfile.open("w") lib = open(src_filename).read() resources = self.load_resources() flex = open(flex_filename).read() self.ilasm = AsmGen(sio, self.assembly_name ) self.generate_communication_proxy() f.write(flex%(lib, data, resources)) f.close() self.filename = self.tmpfile return self.tmpfile def copy_py_resource( self ): src = _path_join(os.path.dirname(__file__), 'jssrc', 'PyResource.as') data = open(src).read() dst = open("py/PyResource.as", "w") dst.write( data ) dst.close() src = _path_join(os.path.dirname(__file__), 'jssrc', 'load_resource.as') data = open(src).read() dst = open("py/load_resource.as", "w") dst.write( data ) dst.close() src = _path_join(os.path.dirname(__file__), 'jssrc', 'load_sprite.as') data = open(src).read() dst = open("py/load_sprite.as", "w") dst.write( data ) dst.close() src = _path_join(os.path.dirname(__file__), 'jssrc', 'load_sound_resource.as') data = open(src).read() dst = open("py/load_sound_resource.as", "w") dst.write( data ) dst.close() def load_resources( self ): """load resoucers from data directory and create embeded flex resources""" data = 'data' entry_fmt ="""\t<py:PyResource resource="@Embed(source='%s/%s')" id="py_%s_%s"/>\n""" list_entry = "" flex_valid_format = ['png','jpeg','jpg','svg','gif','swf','mp3','ttf','fon'] # if we don't have the directory, don't have any resource if not os.access(data, os.F_OK): return "" lr = os.listdir(data) for r in lr: n,e = r.split('.') if not (e.lower() in flex_valid_format): print "*** Warning: file '%s' has an unrecognized extension: '%s'. Skipping" % (r,e) continue entry = entry_fmt % (data,r,n,e) list_entry += entry return list_entry
Python
"""Contains high level javascript compilation function """ import autopath #from pypy.translator.flex.test.runtest import compile_function #from pypy.translator.translator import TranslationContext from pypy.translator.driver import TranslationDriver from pypy.translator.flex.js import JS from pypy.tool.error import AnnotatorError, FlowingError, debug from pypy.rlib.nonconst import NonConstant from pypy.annotation.policy import AnnotatorPolicy from py.compat import optparse from pypy.config.config import OptionDescription, BoolOption, StrOption from pypy.config.config import Config, to_optparse import py import sys from pypy.objspace.flow.model import Constant from pypy.annotation import model as annmodel from pypy.annotation.bookkeeper import getbookkeeper from pypy.annotation import specialize from pypy.interpreter import baseobjspace js_optiondescr = OptionDescription("jscompile", "", [ BoolOption("view", "View flow graphs", default=False, cmdline="--view"), BoolOption("use_pdb", "Use debugger", default=False, cmdline="--pdb"), StrOption("output", "File to save results (default output.mxml)", default="output.mxml", cmdline="--output")]) class FunctionNotFound(Exception): pass class BadSignature(Exception): pass class JsPolicy(AnnotatorPolicy): allow_someobjects = False def get_args(func_data): l = [] for i in xrange(func_data.func_code.co_argcount): l.append("NonConstant(%s)" % repr(func_data.func_defaults[i])) return ",".join(l) def get_arg_names(func_data): return ",".join(func_data.func_code.co_varnames\ [:func_data.func_code.co_argcount]) def rpython2javascript_main(argv, jsconfig): if len(argv) == 0: print "usage: module <function_names>" sys.exit(0) module_name = argv[0] if not module_name.endswith('.py'): module_name += ".py" mod = py.path.local(module_name).pyimport() if len(argv) == 1: function_names = [] for function_name in dir(mod): function = getattr(mod, function_name) if callable(function) and getattr(function, '_client', False): function_names.append( function_name ) if not function_names: print "Cannot find any function with _client=True in %s"\ % module_name sys.exit(1) else: function_names = argv[1:] source = rpython2javascript(mod, function_names, jsconfig=jsconfig) if not source: print "Exiting, source not generated" sys.exit(1) open(jsconfig.output, "w").write(source) print "Written file %s" % jsconfig.output # some strange function source source_ssf_base = """ import %(module_name)s from pypy.translator.flex.helper import __show_traceback from pypy.rlib.nonconst import NonConstant as NonConst %(function_defs)s def some_strange_function_which_will_never_be_called(): %(functions)s """ wrapped_function_def_base = """ def %(fun_name)s(%(arg_names)s): try: traceback_handler.enter(NonConst("entrypoint"), NonConst("()"), NonConst(""), NonConst(0)) %(module_name)s.%(fun_name)s(%(arg_names)s) traceback_handler.leave(NonConst("entrypoint")) except Exception, e: new_tb = traceback_handler.tb[:] __show_traceback(new_tb, str(e)) %(fun_name)s.explicit_traceback = True """ function_base = "%(module_name)s.%(fun_name)s(%(args)s)" wrapped_function_base = "%(fun_name)s(%(args)s)" def get_source_ssf(mod, module_name, function_names): #source_ssf = "\n".join(["import %s" % module_name, "def some_strange_function_which_will_never_be_called():"] + [" "+\ # module_name+"."+fun_name+get_args(mod.__dict__[fun_name]) for fun_name in function_names]) function_list = [] function_def_list = [] for fun_name in function_names: args = get_args(mod.__dict__[fun_name]) arg_names = get_arg_names(mod.__dict__[fun_name]) base = function_base function_list.append(py.code.Source(base % locals())) function_defs = "\n\n".join([str(i) for i in function_def_list]) functions = "\n".join([str(i.indent()) for i in function_list]) retval = source_ssf_base % locals() print retval return retval def rpython2javascript(mod, function_names, jsconfig=None, use_pdb=False): if isinstance(function_names, str): function_names = [function_names] # avoid confusion if mod is None: # this means actual module, which is quite hairy to get in python, # so we cheat import sys mod = sys.modules[sys._getframe(1).f_globals['__name__']] if jsconfig is None: jsconfig = Config(js_optiondescr) if use_pdb: jsconfig.use_pdb = True module_name = mod.__name__ if not function_names and 'main' in mod.__dict__: function_names.append('main') for func_name in function_names: if func_name not in mod.__dict__: raise FunctionNotFound("function %r was not found in module %r" % (func_name, module_name)) func_code = mod.__dict__[func_name] if func_code.func_defaults: lgt = len(func_code.func_defaults) else: lgt = 0 if func_code.func_code.co_argcount > 0 and func_code.func_code. \ co_argcount != lgt: raise BadSignature("Function %s does not have default arguments" % func_name) source_ssf = get_source_ssf(mod, module_name, function_names) exec(source_ssf) in globals() # now we gonna just cut off not needed function # XXX: Really do that #options = optparse.Values(defaults=DEFAULT_OPTIONS) from pypy.config.pypyoption import get_pypy_config config = get_pypy_config(translating=True) driver = TranslationDriver(config=config) try: driver.setup(some_strange_function_which_will_never_be_called, [], policy = JsPolicy()) driver.proceed(["compile_flex"]) if jsconfig.view: driver.translator.view() return driver.gen.tmpfile.open().read() # XXX: Add some possibility to write down selected file except Exception, e: # do something nice with it raise debug(driver, use_pdb)
Python
try: set except NameError: from sets import Set as set from pypy.objspace.flow import model as flowmodel from pypy.rpython.lltypesystem.lltype import Signed, Unsigned, Void, Bool, Float from pypy.rpython.lltypesystem.lltype import SignedLongLong, UnsignedLongLong from pypy.rpython.ootypesystem import ootype from pypy.translator.oosupport.metavm import Generator,InstructionList from pypy.translator.oosupport import function from pypy.translator.flex.log import log from types import FunctionType import re class BaseGenerator(object): def load(self, v): if isinstance(v, flowmodel.Variable): if v.name in self.argset: selftype, selfname = self.args[0] if self.is_method and v.name == selfname: self.ilasm.load_self() else: self.ilasm.load_arg(v) else: self.ilasm.load_local(v) elif isinstance(v, flowmodel.Constant): self.db.load_const(v.concretetype, v.value, self.ilasm) elif isinstance(v, str): self.ilasm.load_const("'" + v + "'") else: assert False def store(self, v): assert isinstance(v, flowmodel.Variable) if v.concretetype is not Void: self.ilasm.store_local(v) else: self.ilasm.store_void() def change_name(self, name, to_name): self.ilasm.change_name(name, to_name) def add_comment(self, text): pass def function_signature(self, graph): return self.cts.graph_to_signature(graph, False) def class_name(self, ooinstance): return ooinstance._name def emit(self, instr, *args): self.ilasm.emit(instr, *args) def call_graph(self, graph): self.db.pending_function(graph) func_sig = self.function_signature(graph) self.ilasm.call(func_sig) def call_external(self, name, args): self.ilasm.call((name, args)) #def call_signature(self, signature): # self.ilasm.call(signature) def cast_to(self, lltype): cts_type = self.cts.lltype_to_cts(lltype, False) self.ilasm.castclass(cts_type) def new(self, obj): log("newobj", obj) self.ilasm.new(self.cts.obj_name(obj)) def set_field(self, obj, name): self.ilasm.set_field(obj, name) #self.ilasm.set_field(self.field_name(obj,name)) def get_field(self, useless_stuff, name): self.ilasm.get_field(name) def call_method(self, obj, name): func_name, signature = self.cts.method_signature(obj, name) self.ilasm.call_method(obj, name, signature) def call_external_method(self, name, arg_len): self.ilasm.call_method(None, name, [0]*arg_len) def instantiate(self): self.ilasm.runtimenew() def downcast(self, TYPE): pass def load_special(self, v): # special case for loading value # when setting builtin field we need to load function instead of None # FIXME: we cheat here if isinstance(v, flowmodel.Constant) and v.concretetype is ootype.Void and isinstance(v.value, FunctionType): graph = self.db.translator.annotator.bookkeeper.getdesc(v.value).cachedgraph(None) self.db.pending_function(graph) name = graph.name self.ilasm.load_str(name) else: self.load(v) def cast_function(self, name, num): self.ilasm.cast_function(name, num) def prefix_op(self, st): self.ilasm.prefix_op(st) def load_str(self, s): self.ilasm.load_str(s) def load_void(self): self.ilasm.load_void() def list_setitem(self, base_obj, item, val): self.load(base_obj) self.load(val) self.load(item) self.ilasm.list_setitem() def list_getitem(self, base_obj, item): self.load(base_obj) self.load(item) self.ilasm.list_getitem() def push_primitive_constant(self, TYPE, value): self.db.load_const(TYPE, value, self.ilasm) def branch_unconditionally(self, target_label): self.ilasm.jump_block(self.block_map[target_label]) def branch_conditionally(self, exitcase, target_label): self.ilasm.branch_if(exitcase) self.ilasm.jump_block(self.block_map[target_label]) self.ilasm.close_branch() class Function(function.Function, BaseGenerator): def __init__(self, db, graph, name=None, is_method=False, is_entrypoint=False, _class=None): self._class = _class super(Function, self).__init__(db, graph, name, is_method, is_entrypoint) self._set_args() self._set_locals() self.order = 0 self.name = name or self.db.get_uniquename(self.graph, self.graph.name) def _setup_link(self, link, is_exc_link = False): target = link.target for to_load, to_store in zip(link.args, target.inputargs): if to_load.concretetype is not Void: if is_exc_link and isinstance(to_load, flowmodel.Variable) and re.match("last_exc_value", to_load.name): self.ilasm.load_str("exc") else: self.load(to_load) self.store(to_store) def _create_generator(self, ilasm): return self def begin_render(self): block_map = {} for blocknum, block in enumerate(self.graph.iterblocks()): block_map[self._get_block_name(block)] = blocknum self.block_map = block_map if self.is_method: args = self.args[1:] # self is implicit else: args = self.args if self.is_method: self.ilasm.begin_method(self.name, self._class, [i[1] for i in args]) else: self.ilasm.begin_function(self.name, args) self.ilasm.set_locals(",".join([i[1] for i in self.locals])) self.ilasm.begin_for() def render_return_block(self, block): return_var = block.inputargs[0] if return_var.concretetype is not Void: self.load(return_var) self.ilasm.ret() else: self.ilasm.load_void() self.ilasm.ret() def end_render(self): self.ilasm.end_for() self.ilasm.end_function() def render_raise_block(self, block): self.ilasm.throw(block.inputargs[1]) def end_try(self, target_label): self.ilasm.jump_block(self.block_map[target_label]) self.ilasm.catch() #self.ilasm.close_branch() def record_ll_meta_exc(self, ll_meta_exc): pass def begin_catch(self, llexitcase): real_name = self.cts.lltype_to_cts(llexitcase._inst.class_._INSTANCE) s = "_consts_0.isinstanceof(exc, %s)"%real_name self.ilasm.branch_if_string(s) def end_catch(self, target_label): """ Ends the catch block, and branchs to the given target_label as the last item in the catch block """ self.ilasm.close_branch() def store_exception_and_link(self, link): self._setup_link(link, True) self.ilasm.jump_block(self.block_map[self._get_block_name(link.target)]) def after_except_block(self): #self.ilasm.close_branch() self.ilasm.throw_real("exc") self.ilasm.close_branch() def set_label(self, label): self.ilasm.write_case(self.block_map[label]) #self.ilasm.label(label) def begin_try(self): self.ilasm.begin_try() def clean_stack(self): self.ilasm.clean_stack()
Python
import py Option = py.test.config.Option option = py.test.config.addoptions("pypy-ojs options", Option('--use-browser', action="store", dest="browser", type="string", default="", help="run Javascript tests in your default browser"), Option('--tg', action="store_true", dest="tg", default=False, help="Use TurboGears machinery for testing") )
Python
""" backend generator routines """ from pypy.translator.flex.log import log from pypy.objspace.flow.model import Variable from StringIO import StringIO import_list = [] def add_import(name): import_list.append(name) class CodeGenerator(object): def __init__(self, out, indentstep = 4, startblock = '{', endblock = '}'): self._out = out self._indent = 0 self._bol = True # begin of line self._indentstep = indentstep self._startblock = startblock self._endblock = endblock def write(self, s, indent = 0): indent = self._indent + (indent * self._indentstep) if self._bol: self._out.write(' ' * indent) self._out.write(s) self._bol = (s and s[-1] == '\n') def writeline(self, s=''): self.write(s) self.write('\n') def openblock(self): self.writeline(self._startblock) self._indent += self._indentstep def closeblock(self): self._indent -= self._indentstep self.writeline(self._endblock) def close(self): self._out.close() class Queue(object): def __init__(self, l, subst_table): self.l = l[:] self.subst_table = subst_table def pop(self): el = self.l.pop() return self.subst_table.get(el, el) def __getattr__(self,attr): return getattr(self.l, attr) def __len__(self): return len(self.l) def __nonzero__(self): return len(self.l) > 0 def empty(self): self.l = [] def __repr__(self): return "<Queue %s>" % (repr(self.l),) class AsmGen(object): """ JS 'assembler' generator routines """ def __init__(self, outfile, name): self.outfile = outfile self.name = name self.subst_table = {} self.right_hand = Queue([], self.subst_table) self.codegenerator = CodeGenerator(outfile) self.gen_stack = [] self.push = True def set_push(self, value): self.push = value def push_gen(self, generator): self.gen_stack.append( self.codegenerator ) if isinstance(generator, str): generator = CodeGenerator(open(generator, "w") ) self.codegenerator = generator def pop_gen(self): #self.codegenerator.close() self.codegenerator = self.gen_stack.pop() def close(self): self.outfile.close() def begin_function(self, name, arglist): if self.push: self.push_gen("py/"+name+".as") self.codegenerator.write("package py ") self.codegenerator.openblock() self.codegenerator.writeline("import py._consts_0;") self.codegenerator.writeline("import ll_os_path.ll_join;") for iname in import_list: self.codegenerator.writeline("import "+iname+";") args = ",".join([i[1] for i in arglist]) self.codegenerator.write("public function %s (%s) "%(name, args)) self.codegenerator.openblock() def begin_method(self, name, _class, arglist): if self.push: self.push_gen("py/"+name+".as") self.codegenerator.write("package py ") self.codegenerator.openblock() self.codegenerator.writeline("import py._consts_0;") self.codegenerator.writeline("import ll_os_path.ll_join;") for iname in import_list: self.codegenerator.writeline("import "+iname+";") args = ",".join(arglist) self.codegenerator.write("%s.prototype.%s = function (%s)"%(_class, name, args)) self.codegenerator.openblock() def end_function(self): self.codegenerator.closeblock() self.codegenerator.writeline("") if self.push: self.codegenerator.closeblock() self.pop_gen() def begin_class(self, name, base="Object"): self.codegenerator.write("package py ") self.codegenerator.openblock() self.codegenerator.writeline("import py._consts_0;") self.codegenerator.writeline("import ll_os_path.ll_join;") for iname in import_list: self.codegenerator.writeline("import "+iname+";") self.codegenerator.write("dynamic public class %s extends %s "%(name, base)) self.codegenerator.openblock() def end_class(self): self.codegenerator.closeblock() self.codegenerator.closeblock() self.codegenerator.writeline("") def load_arg(self, v): self.right_hand.append(v.name) def store_local(self, v): self.store_name(v.name) def store_name(self, name): name = self.subst_table.get(name, name) element = self.right_hand.pop() if element != name: self.codegenerator.writeline("%s = %s;"%(name, element)) def load_local(self, v): self.right_hand.append(v.name) def load_const(self, v): self.right_hand.append(v) def ret(self): self.codegenerator.writeline("return ( %s );"%self.right_hand.pop()) def emit(self, opcode, *args): v1 = self.right_hand.pop() v2 = self.right_hand.pop() self.right_hand.append("(%s%s%s)"%(v2, opcode, v1)) def call(self, func): func_name, args = func l = [self.right_hand.pop() for i in xrange(len(args))] l.reverse() real_args = ",".join(l) self.right_hand.append("%s ( %s )" % (func_name, real_args)) def branch_if(self, exitcase): def mapping(exitc): if exitc in ['True', 'False']: return exitc.lower() return exitc arg = self.right_hand.pop() if hasattr(arg,'name'): arg_name = self.subst_table.get(arg.name, arg.name) else: arg_name = arg self.branch_if_string("%s == %s"%(arg_name, mapping(str(exitcase)))) def branch_if_string(self, arg): self.codegenerator.writeline("if (%s)"%arg) self.codegenerator.openblock() def branch_elsif_string(self, arg): self.codegenerator.closeblock() self.codegenerator.writeline("else if (%s)"%arg) self.codegenerator.openblock() def branch_elsif(self, arg, exitcase): self.codegenerator.closeblock() self.branch_if(arg, exitcase, "else if") def branch_while(self, arg, exitcase): def mapping(exitc): if exitc in ['True', 'False']: return exitc.lower() return exitc arg_name = self.subst_table.get(arg.name, arg.name) self.codegenerator.write("while ( %s == %s )"%(arg_name, mapping(str(exitcase)))) self.codegenerator.openblock() def branch_while_true(self): self.codegenerator.write("while (true)") self.codegenerator.openblock() def branch_else(self): self.right_hand.pop() self.codegenerator.closeblock() self.codegenerator.write("else") self.codegenerator.openblock() def close_branch(self): self.codegenerator.closeblock() def label(self, *args): self.codegenerator.openblock() def change_name(self, from_name, to_name): if isinstance(from_name,Variable) and isinstance(to_name,Variable): self.subst_table[from_name.name] = to_name.name def cast_function(self, name, num): # FIXME: redundancy with call args = [self.right_hand.pop() for i in xrange(num)] args.reverse() arg_list = ",".join(args) self.right_hand.append("%s ( %s )"%(name, arg_list)) def prefix_op(self, st): self.right_hand.append("%s%s"%(st, self.right_hand.pop())) #def field(self, f_name, cts_type): # pass def set_locals(self, loc_string): if loc_string != '': self.codegenerator.writeline("var %s;"%loc_string) def set_static_field(self, _type, namespace, _class, varname): self.codegenerator.writeline("%s.prototype.%s = %s;"%(_class, varname, self.right_hand.pop())) def set_field(self, useless_parameter, name): v = self.right_hand.pop() self.codegenerator.writeline("%s.%s = %s;"%(self.right_hand.pop(), name, v)) #self.right_hand.append(None) def call_method(self, obj, name, signature): l = [self.right_hand.pop() for i in signature] l.reverse() args = ",".join(l) self.right_hand.append("%s.%s(%s)"%(self.right_hand.pop(), name, args)) def get_field(self, name): self.right_hand.append("%s.%s"%(self.right_hand.pop(), name)) def new(self, obj): log("New: %r"%obj) self.right_hand.append("new %s()"%obj) def runtimenew(self): self.right_hand.append("new %s()" % self.right_hand.pop()) def load_self(self): self.right_hand.append("this") def store_void(self): if not len(self.right_hand): return v = self.right_hand.pop() if v is not None and v.find('('): self.codegenerator.writeline(v+";") def begin_consts(self, name): # load consts, maybe more try to use stack-based features? #self.codegenerator.writeline("var %s = {}"%name) self.codegenerator.writeline("public function __load_consts_flex() ") self.codegenerator.openblock() def end_consts(self): self.codegenerator.closeblock() def new_obj(self): self.right_hand.append("{}") def new_list(self): self.right_hand.append("[]") # FIXME: will refactor later load_str = load_const def list_setitem(self): item = self.right_hand.pop() value = self.right_hand.pop() lst = self.right_hand.pop() self.right_hand.append("%s[%s]=%s"%(lst, item, value)) def list_getitem(self): item = self.right_hand.pop() lst = self.right_hand.pop() self.right_hand.append("%s[%s]"%(lst, item)) def load_void(self): self.right_hand.append("undefined") def load_void_obj(self): self.right_hand.append("{}") def begin_try(self): self.codegenerator.write("try ") self.codegenerator.openblock() def catch(self): self.codegenerator.closeblock() self.codegenerator.write("catch (exc)") self.codegenerator.openblock() def begin_for(self): self.codegenerator.writeline("var block = 0;") self.codegenerator.write("for(;;)") self.codegenerator.openblock() self.codegenerator.write("switch(block)") self.codegenerator.openblock() def write_case(self, num): self.codegenerator.writeline("case %d:"%num) def jump_block(self, num): self.codegenerator.writeline("block = %d;"%num) self.codegenerator.writeline("break;") def end_for(self): self.codegenerator.closeblock() self.codegenerator.closeblock() def inherits(self, subclass_name, parent_name): self.codegenerator.writeline("inherits(%s,%s);"%(subclass_name, parent_name)) def throw(self, var): self.throw_real(var.name) def throw_real(self, s): # use throwit wrapper function... because of compiler weirdness with flex compiler. self.codegenerator.writeline("_consts_0.throwit(%s);"%s) def clean_stack(self): self.right_hand.empty()
Python
#!/usr/bin/env python """ In this example I'll show how to manipulate DOM tree from inside RPython code Note that this is low-level API to manipulate it, which might be suitable if you don't like boilerplate on top. There is ongoing effort to provide API of somewhat higher level, which will be way easier to manipulate. """ from pypy.translator.js.lib import server from pypy.translator.js.main import rpython2javascript from pypy.translator.js.modules.dom import document # dom manipulating module HTML = ''' <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body> <table id="atable"> <tr><td>A row</td></tr> </table> <a href="#" onclick="addrow()">Add row</a> <a href="#" onclick="delrow()">Del row</a> </body> </html> ''' # these are exposed functions def addrow(): # we need to call a helper, similiar to document in JS tr = document.createElement("tr") td = document.createElement("td") td.appendChild(document.createTextNode("A row")) tr.appendChild(td) document.getElementById("atable").appendChild(tr) def delrow(): table = document.getElementById("atable") # note -1 working here like in python, this is last element in list table.removeChild(table.childNodes[-1]) class Handler(server.TestHandler): def index(self): return HTML index.exposed = True def source_js(self): return "text/javascript", rpython2javascript(None, ["addrow", "delrow"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ In this example, we'll show how to add javascript to our simple server from previous example """ from pypy.translator.js.lib import server import sys # here we have virtual script "source.js" which we generate # on-the-fly when requested HTML = """ <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body onload="show()"> </body> </html> """ from pypy.translator.js.main import rpython2javascript # here we import rpython -> javascript conversion utility from pypy.translator.js.modules import dom # and here we import functions from modules that we want to use # this is function which will be translated into javascript, # we can put it in a different module if we like so def show(): dom.alert("Alert") class Handler(server.TestHandler): def index(self): return HTML index.exposed = True # here we generate javascript, this will be accessed when # asked for source.js def source_js(self): # this returns content-type (if not text/html) # and generated javascript code # None as argument means current module, while "show" is the # name of function to be exported (under same name) return "text/javascript", rpython2javascript(None, ["show"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ In this example I'll show how to manipulate DOM tree from inside RPython code Note that this is low-level API to manipulate it, which might be suitable if you don't like boilerplate on top. There is ongoing effort to provide API of somewhat higher level, which will be way easier to manipulate. """ from pypy.translator.js.lib import server from pypy.translator.js.main import rpython2javascript from pypy.translator.js.modules.dom import document # dom manipulating module HTML = ''' <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body> <table id="atable"> <tr><td>A row</td></tr> </table> <a href="#" onclick="addrow()">Add row</a> <a href="#" onclick="delrow()">Del row</a> </body> </html> ''' # these are exposed functions def addrow(): # we need to call a helper, similiar to document in JS tr = document.createElement("tr") td = document.createElement("td") td.appendChild(document.createTextNode("A row")) tr.appendChild(td) document.getElementById("atable").appendChild(tr) def delrow(): table = document.getElementById("atable") # note -1 working here like in python, this is last element in list table.removeChild(table.childNodes[-1]) class Handler(server.TestHandler): def index(self): return HTML index.exposed = True def source_js(self): return "text/javascript", rpython2javascript(None, ["addrow", "delrow"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ In this example, we'll show how to add javascript to our simple server from previous example """ from pypy.translator.js.lib import server import sys # here we have virtual script "source.js" which we generate # on-the-fly when requested HTML = """ <html> <head> <script src="source.js"/> <title>pypy.js tutorial</title> </head> <body onload="show()"> </body> </html> """ from pypy.translator.js.main import rpython2javascript # here we import rpython -> javascript conversion utility from pypy.translator.js.modules import dom # and here we import functions from modules that we want to use # this is function which will be translated into javascript, # we can put it in a different module if we like so def show(): dom.alert("Alert") class Handler(server.TestHandler): def index(self): return HTML index.exposed = True # here we generate javascript, this will be accessed when # asked for source.js def source_js(self): # this returns content-type (if not text/html) # and generated javascript code # None as argument means current module, while "show" is the # name of function to be exported (under same name) return "text/javascript", rpython2javascript(None, ["show"]) source_js.exposed = True # server start, same as before if __name__ == '__main__': server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ This is simple all-in-one self-containing server, which just shows almost-empty HTML page """ # here we import server, which is derivative of # BaseHTTPServer from python standard library from pypy.translator.js.lib import server # We create handler, which will handle all our requests class Handler(server.TestHandler): def index(self): # provide some html contents return "<html><head></head><body><p>Something</p></body></html>" # this line is necessary to make server show something, # otherwise method is considered private-only index.exposed = True if __name__ == '__main__': # let's start our server, # this will create running server instance on port 8000 by default, # which will run until we press Control-C server.create_server(handler=Handler).serve_forever()
Python
#!/usr/bin/env python """ This is simple all-in-one self-containing server, which just shows almost-empty HTML page """ # here we import server, which is derivative of # BaseHTTPServer from python standard library from pypy.translator.js.lib import server # We create handler, which will handle all our requests class Handler(server.TestHandler): def index(self): # provide some html contents return "<html><head></head><body><p>Something</p></body></html>" # this line is necessary to make server show something, # otherwise method is considered private-only index.exposed = True if __name__ == '__main__': # let's start our server, # this will create running server instance on port 8000 by default, # which will run until we press Control-C server.create_server(handler=Handler).serve_forever()
Python
""" Communication proxy rendering """ from pypy.objspace.flow.model import Variable, Constant from pypy.rpython.ootypesystem.bltregistry import ArgDesc GET_METHOD_BODY = """ %(class)s.prototype.%(method)s = function ( %(args)s ) { var data,str; var x = new XMLHttpRequest(); data = %(data)s; str = "" for(i in data) { if (data[i]) { if (str.length == 0) { str += "?"; } else { str += "&"; } str += escape(i) + "=" + escape(data[i].toString()); } } //logDebug('%(call)s'+str); x.open("GET", '%(call)s' + str, true); x.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); x.onreadystatechange = function () { %(real_callback)s(x, callback) }; //x.setRequestHeader("Connection", "close"); //x.send(data); x.send(null); } """ POST_METHOD_BODY = """ %(class)s.prototype.%(method)s = function ( %(args)s ) { var data,str; var x = new XMLHttpRequest(); data = %(data)s; str = "" for(i in data) { if (data[i]) { if (str.length != 0) { str += "&"; } str += escape(i) + "=" + escape(data[i].toString()); } } //logDebug('%(call)s'+str); x.open("POST", '%(call)s', true); //x.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); x.onreadystatechange = function () { %(real_callback)s(x, callback) }; //x.setRequestHeader("Connection", "close"); //logDebug(str); x.send(str); //x.send(null); } """ CALLBACK_BODY = """ function %(real_callback)s (x, cb) { var d; if (x.readyState == 4) { if (x.responseText) { eval ( "d = " + x.responseText ); cb(d); } else { cb({}); } } } """ CALLBACK_XML_BODY = """ function %(real_callback)s (x, cb) { if (x.readyState == 4) { if (x.responseXML) { cb(x.responseXML.documentElement); } else { cb(null); } } } """ MOCHIKIT_BODY = """ %(class)s.prototype.%(method)s = function ( %(args)s ) { var data,str; data = %(data)s; loadJSONDoc('%(call)s', data).addCallback(callback); } """ USE_MOCHIKIT = True # FIXME: some option? class XmlHttp(object): """ Class for rendering xmlhttp request communication over normal js code """ def __init__(self, ext_obj, name, use_xml=False, base_url="", method="GET"): self.ext_obj = ext_obj self.name = name self.use_xml = use_xml self.base_url = base_url obj = self.ext_obj._TYPE._class_ if not base_url and hasattr(obj, '_render_base_path'): self.base_url = obj._render_base_path self.method = method def render(self, ilasm): self.render_body(ilasm) for method_name, method in self.ext_obj._TYPE._class_._methods.iteritems(): self.render_method(method_name, method, ilasm) def render_body(self, ilasm): ilasm.begin_function(self.name, []) ilasm.end_function() def render_method(self, method_name, method, ilasm): args, retval = method.args, method.retval.name if len(args) == 0 or args[-1].name != 'callback': args.append(ArgDesc('callback', lambda : None)) real_args = list(arg.name for arg in args) # FIXME: dirty JS here data = "{%s}" % ",".join(["'%s':%s" % (i,i) for i in real_args if i != 'callback']) real_callback = Variable("callback").name if len(self.base_url) > 0 and not self.base_url.endswith("/"): url = self.base_url + "/" +method_name else: url = self.base_url + method_name METHOD_BODY = globals()[self.method + "_METHOD_BODY"] if USE_MOCHIKIT and self.use_xml: assert 0, "Cannot use mochikit and xml requests at the same time" if USE_MOCHIKIT and self.method == "POST": assert 0, "Cannot use mochikit with POST method" if USE_MOCHIKIT: ilasm.codegenerator.write(MOCHIKIT_BODY % {'class':self.name, 'method':method_name,\ 'args':','.join(real_args), 'data':data, 'call':url}) else: if not self.use_xml: callback_body = CALLBACK_BODY else: callback_body = CALLBACK_XML_BODY ilasm.codegenerator.write(callback_body % {'real_callback':real_callback}) ilasm.codegenerator.write(METHOD_BODY % {'class':self.name, 'method':method_name,\ 'args':",".join(real_args), 'data':data, 'call':url,\ 'real_callback':real_callback})
Python
import py from pypy.tool.ansi_print import ansi_log log = py.log.Producer("flex") py.log.setconsumer("flex", ansi_log)
Python
#!/usr/bin/env python import urllib2 import os.path import sys import re import string url_root = "http://livedocs.adobe.com/flex/3/langref/package-summary.html" url_root = "file:///Users/gui/Downloads/flex3_documentation/langref/package-summary.html" dump_file = open('dump.txt', 'w') def get_page(url): # print ">> GET: " + url page = urllib2.urlopen(url) page = page.read() assert page, "Page is empty" return page re_all = re.compile(r'href="([\w/]*\w+/package-detail\.html)"\>([\w.]*\w+)\</a\>') def get_all(url): page = get_page(url) r = re_all m = r.findall(page) u = os.path.dirname(url) for url, name in m: url = os.path.join(u, url) dump_file.write("p: %s\n" % name) get_package(url) re_package = re.compile(r'summaryTableSecondCol">\<a href="(\w+\.html)">(\w+)') def get_package(url): page = get_page(url) r = re_package m = r.findall(page) u = os.path.dirname(url) for url, name in m: url = os.path.join(u, url) dump_file.write("c: %s\n" % name) get_class(url) re_class_inheritance_a = re.compile(r'inheritanceList">(.*)<\/td>') re_class_inheritance_b = re.compile(r'<img[^>]*>') re_class_inheritance_c = re.compile(r'<a\s*href="([^"]+)"\s*>([\w\s]+)</a>') def get_class_inheritance(page): r = re_class_inheritance_a m = r.search(page) if m: s = m.groups()[0] s = re_class_inheritance_b.sub('', s) m = re_class_inheritance_c.findall(s) for url, name in m: url = url.lstrip("./") if url.endswith('.html'): url = url[:-5] url = url.replace('/', '.') dump_file.write('i: %s\n' % url) else: m = re.search(r'<title>(.*)</title>', page) if m: print "Could not find inheritance chain in: '%s'" % m.groups()[0] else: raise Exception("Don't understand format of file:\n" + page) def get_class(url): page = get_page(url) get_class_inheritance(page) r = re.compile(r"""<div class="detailBody">\s*<code>(.*)</code>""") u = re.compile(r'href="(http://)?(?P<url>[\w/._*]+)\.html(#([\w_*]+))?"') a = re.compile(r'([\w_*]+)\s*<\/a>\s*$') t = re.compile(r'<[^>]+>') m = r.findall(page) for raw in m: raw = raw.strip() s = t.sub('', raw) if s.find('function') >= 0: v = u.findall(raw) if not a.search(raw): typ = ':void' s = s.rstrip(string.letters + string.whitespace + ':') elif v: s = s.rstrip(string.letters + string.whitespace) typ = v[-1][1] typ = typ.lstrip().lstrip('/.:') if typ in ['specialTypes']: typ = v[-1][3] typ = typ.replace('/', '.') else: typ = '' dump_file.write("f: %s%s\n" % (s, typ)) elif s.find(' const ') >= 0: dump_file.write("k: %s\n" % s) else: dump_file.write("a: %s\n" % s) get_all(url_root) # get_class('http://livedocs.adobe.com/flex/3/langref/air/net/ServiceMonitor.html')
Python
#!/usr/bin/env python from __future__ import with_statement import subprocess import os import os.path import re import sys import operator as op import string import logging __doc__ = """ Program to convert an intermediate text format that contains the package names, classes and function/attribute declarations for the entire Flex/Flash ActionScript Library. The information used to generate this intermediate file is extracted from the HTML documents of the online libraries. Usage: maketree INPUT_FILE OUTPUT_DIRECTORY Sample format of input file: p: package1.name c: ClassName1 i: ../../flash.net.SuperClass i: ../../flash.net.SuperSuperClass1 a: attribute1:Boolean a: attribute1:Boolean k: public static const CONSTVAL1:String = "binary" f: public function InstanceFunction1():Boolean f: protected function InstanceFunction2():void f: public static function StaticFunction1(arg1:Object):void c: ClassName1 ... p: package2.name c: ClassName3 ... """ class chdir: """ Implementation of "with chdir(path):" statement. """ def __init__(self, dirpath): self.dirpath = dirpath def __enter__(self): self.old = os.getcwd() os.chdir(self.dirpath) def __exit__(self, type, value, tb): os.chdir(self.old) def mkdir_ensure(path, isModule=False): """ Ensure that a certain directory path exists. If the isModule argument is True, it wil create a __init__.py file inside the directory. """ subprocess.call(['mkdir', '-p', path]) init_file = os.path.join(path, '__init__.py') if isModule and not os.path.exists(init_file): with open(init_file, 'w') as f: f.write('# automatically generated #\n') def builtin_types_as2py(type_as): """ Convert a builtin ActionScript 3 type into a native python equivalent. """ d = { 'String': 'str', 'Object': 'object', 'uint': 'long', 'Number': 'float', 'Boolean': 'bool', 'Array': 'list', 'void': 'None', } if d.has_key(type_as): return d[type_as] return type_as def _type_as2py(typ): typ = typ or 'str' typ = builtin_types_as2py(typ) if typ in ['object', 'Function', 'void', '*', '**']: typ = 'str' return True, typ return False, typ class AS3Tree(object): """ Represents an entire ActionScript 3 library. """ def __init__(self): self.packages = dict() def addPackage(self, pack): self.packages[pack.name] = pack def to_py(self, path): mkdir_ensure(path) os.chdir(path) for name, pack in self.packages.items(): pack.to_py() required_imports = set() required_imports.add('from pypy.translator.flex.asmgen import add_import') class AS3Package(object): """ Represents an ActionScript 3 package. """ def __init__(self, name): self.name = name self.classes = dict() def addClass(self, clas): """ Add a class to the package. """ self.classes[clas.name] = clas def _inheritanceTreeToList(self, class_name, d): """ Recursive aux function to convert a inheritance tree to a list that is ordered to comply with class dependencies. """ result = [] if d.has_key(class_name): for subclass in d[class_name]: assert type(subclass) is AS3Class result.append(subclass) result.extend(self._inheritanceTreeToList(subclass.name, d)) return result def _orderClassesByInheritance(self): """ Return this package's class objects ordered to comply with class dependencies. """ d = {} for name, clas in self.classes.items(): i = clas.inheritance if not i or i == 'Error' or i.find('.') >= 0: i = 'Object' if d.has_key(i): d[i].append(clas) else: d[i] = [clas] result = self._inheritanceTreeToList('Object', d) assert len(result) == len(self.classes) return result def to_py(self): classes = self._orderClassesByInheritance() assert self.name pth = self.name.replace('.', '/') pth, fil = pth.rsplit('/', 1) mkdir_ensure(pth, isModule=True) with chdir(pth): s = '' global required_imports for clas in classes: i = clas.to_py_inherit_module() if i: required_imports.add('import ' + i) s += clas.to_py() with open(fil + '.py', 'w') as fd: for i in required_imports: fd.write("%s\n" % i) fd.write(s) class AS3Class(object): """ Represents an ActionScript 3 class. """ def __init__(self, parent=None, name=None, package=None): self.parent = parent self.name = name self.package = package self.functions = [] self.constants = [] self.attributes = [] self.inheritance = None def addFunction(self, func): self.functions.append(func) def addConstant(self, cons): self.constants.append(cons) def addAttribute(self, attr): self.attributes.append(attr) def addInheritance(self, name): assert name if not self.inheritance: if name.startswith(self.parent.name): name = name[len(self.parent.name) + 1:] self.inheritance = name def to_py_inherit_module(self): i = self.to_py_inheritance() i = i.rstrip(string.ascii_letters).rstrip('.') return i def to_py_inheritance(self): if not self.inheritance: return 'object' return self.inheritance def to_py(self): """ Generate a rpython class. """ inherit = self.to_py_inheritance() inherit = builtin_types_as2py(inherit) if inherit == 'object': inherit = 'BasicExternal' self_path = "%s.%s" % (self.parent.name, self.name) s = "\nadd_import('%s')\n" % self_path s += "class %s(%s):\n" % (self.name, inherit) s += " _render_class = '%s'\n" % self_path if not any((self.functions, self.attributes, self.constants)): s += ' pass\n' s += ' _fields = {\n' for attr in self.attributes: s += attr.to_py() s += ' }\n' for cons in self.constants: s += cons.to_py() s += ' _methods = {\n' for func in self.functions: s += func.to_py() s += ' }\n' return s class AS3Constant(object): """ Represents a constant attribute of an ActionScript 3 class. """ def __init__(self, raw='', name='', typ='', val=''): self.raw = raw self.typ = typ self.name = name self.val = val def to_py(self): val = self.val or 'None' return " %s = %s\n" % (self.name, val) class AS3Attribute(object): """ Represents an attribute of an ActionScript 3 class. """ def __init__(self, raw='', name='', typ=''): self.raw = raw self.name = name self.typ = typ def to_py(self): isSpecial, typ = _type_as2py(self.typ) return " '%s': %s,\n" % (self.name, typ or 'None') class AS3Function(object): """ Represents an instance/class function of a ActionScript 3 class. """ def __init__(self, parent=None, raw='', name='', typ='', args=[], isStatic=False): self.parent = parent self.raw = raw assert typ, raw self.typ = typ self.name = name self.args = args self.isStatic = isStatic def to_py(self): s = '' name = self.name if name == self.parent.name: # __init__() return '' if self.isStatic: # TODO return '' global required_imports typ = self.typ.rstrip(string.letters + '*').rstrip('.') if typ: required_imports.add('import ' + typ) args = "" for arg in self.args: todo = '' isSpecialCase, typ = _type_as2py(arg.typ) if isSpecialCase: todo = ' # Fix This (type %s)' % arg.typ args += '\n ' + typ + ',' + todo isSpecialCase, typ = _type_as2py(self.typ) s += " '%s': MethodDesc([%s\n ], %s),\n\n" % (name, args, typ) return s class AS3FunctionArgument(object): """ Represents a function argument belonging to an ActionScript 3 class. """ def __init__(self, raw='', name='', typ='', value='', isEllipsis=False): self.raw = raw self.name = name self.typ = typ self.value = value self.isEllipsis = isEllipsis def __repr__(self): return '<%s: %s >' % (self.__class__.__name__, self.raw) def to_py(self): return self.name #+ ':' + str(builtin_types_as2py(self.typ)) class Parser(object): def __init__(self): self.tree = AS3Tree() self.last_p = None self.last_c = None def _package(self, s): p = AS3Package(name=s) self.tree.addPackage(p) self.last_p = p self.last_c = None def _class(self, s): c = AS3Class(name=s, package=self.last_p, parent=self.last_p) self.last_p.addClass(c) self.last_c = c _re_function_arg = re.compile(r'^\s*(?P<ellipsis>\.{3})?\s*(?P<name>\w+)\s*(:\s*(?P<typ>[\w*]+))?\s*(=\s*(?P<val>.*))?\s*$') def _function_arg(self, raw): """ Parses a function argument, returns an AS3FunctionArgument object. """ m = Parser._re_function_arg.search(raw) if not m: logging.warn('Function argument not valid: %s' % raw) return False d = m.groupdict() arg = AS3FunctionArgument(raw=raw, name=d['name'], isEllipsis=bool(d['ellipsis']), typ=d['typ']) return arg def _function_parse(self, raw): """ Parse the raw value of an f: line. """ l, r = raw.split(' function ', 1) isStatic = l.find('static') >= 0 name, args, typ = re.split('[()]', r, 2) typ = typ.rsplit(':', 1) if typ: typ = typ[-1].strip() args = filter(len, re.split('\s*,\s*', args)) resu = [] for arg in args: arg = self._function_arg(arg) if arg: resu.append(arg) else: logging.error("Could not parse a function of %s.%s: %s" % (self.last_p.name, self.last_c.name, raw)) break return name, resu, typ, isStatic def _function(self, raw): """ Takes the raw value of an f: line, adds an AS3Function object to the current class. """ name, args, typ, isStatic = self._function_parse(raw) f = AS3Function(parent=self.last_c, raw=raw, name=name, args=args, typ=typ, isStatic=isStatic) self.last_c.addFunction(f) def _inherit(self, raw): """ Get the superclass of the current class. """ assert raw self.last_c.addInheritance(raw) if not self.last_c.inheritance: del self.last_p.classes[self.last_c.name] name = self.last_p.name + '.' + self.last_c.name logging.warning("Class %s has no superclass: will be ignored." % name) def _attribute(self, raw): """ Takes the raw value of an a: line, returns an AS3Attribute object. """ name, typ = re.split('\s*:\s*', raw.strip()) typ_value = typ.split('=') if len(typ_value) == 2: typ = typ_value[0].strip() name = name.rstrip().split(" ")[-1] a = AS3Attribute(raw=raw, name=name, typ=typ) self.last_c.addAttribute(a) _re_constant = re.compile(r'(?P<name>\w+)\s*:\s*(?P<typ>[\w\*]+)\s*(=\s*(?P<val>.*))?') def _constant(self, raw): """ Parse the raw value of a k: line. """ m = Parser._re_constant.search(raw) assert m, "Could not parse const attribute:\n\t%s" % raw if m: d = m.groupdict() name = d['name'] typ = d['typ'] val = d['val'] k = AS3Constant(raw=raw, name=name, typ=typ, val=val) self.last_c.addConstant(k) def _line(self, line): """ Process one line. Ignore lines with unknown prefixes. """ c, s = line[:3], line[3:].rstrip() if c == 'p: ': self._package(s) elif c == 'c: ': self._class(s) elif c == 'f: ': self._function(s) elif c == 'a: ': self._attribute(s) elif c == 'k: ': self._constant(s) elif c == 'i: ': self._inherit(s) def parse(self, filename): """ Takes the filename of the intermediate dump file, returns an AS3Tree object. """ for line in open(filename, 'r'): self._line(line) return self.tree filename, dirname = sys.argv[1:3] parser = Parser() tree = parser.parse(filename) tree.to_py(os.path.abspath(dirname))
Python
#!/usr/bin/env python import urllib2 import os.path import sys import re import string url_root = "http://livedocs.adobe.com/flex/3/langref/package-summary.html" url_root = "file:///Users/gui/Downloads/flex3_documentation/langref/package-summary.html" dump_file = open('dump.txt', 'w') def get_page(url): # print ">> GET: " + url page = urllib2.urlopen(url) page = page.read() assert page, "Page is empty" return page re_all = re.compile(r'href="([\w/]*\w+/package-detail\.html)"\>([\w.]*\w+)\</a\>') def get_all(url): page = get_page(url) r = re_all m = r.findall(page) u = os.path.dirname(url) for url, name in m: url = os.path.join(u, url) dump_file.write("p: %s\n" % name) get_package(url) re_package = re.compile(r'summaryTableSecondCol">\<a href="(\w+\.html)">(\w+)') def get_package(url): page = get_page(url) r = re_package m = r.findall(page) u = os.path.dirname(url) for url, name in m: url = os.path.join(u, url) dump_file.write("c: %s\n" % name) get_class(url) re_class_inheritance_a = re.compile(r'inheritanceList">(.*)<\/td>') re_class_inheritance_b = re.compile(r'<img[^>]*>') re_class_inheritance_c = re.compile(r'<a\s*href="([^"]+)"\s*>([\w\s]+)</a>') def get_class_inheritance(page): r = re_class_inheritance_a m = r.search(page) if m: s = m.groups()[0] s = re_class_inheritance_b.sub('', s) m = re_class_inheritance_c.findall(s) for url, name in m: url = url.lstrip("./") if url.endswith('.html'): url = url[:-5] url = url.replace('/', '.') dump_file.write('i: %s\n' % url) else: m = re.search(r'<title>(.*)</title>', page) if m: print "Could not find inheritance chain in: '%s'" % m.groups()[0] else: raise Exception("Don't understand format of file:\n" + page) def get_class(url): page = get_page(url) get_class_inheritance(page) r = re.compile(r"""<div class="detailBody">\s*<code>(.*)</code>""") u = re.compile(r'href="(http://)?(?P<url>[\w/._*]+)\.html(#([\w_*]+))?"') a = re.compile(r'([\w_*]+)\s*<\/a>\s*$') t = re.compile(r'<[^>]+>') m = r.findall(page) for raw in m: raw = raw.strip() s = t.sub('', raw) if s.find('function') >= 0: v = u.findall(raw) if not a.search(raw): typ = ':void' s = s.rstrip(string.letters + string.whitespace + ':') elif v: s = s.rstrip(string.letters + string.whitespace) typ = v[-1][1] typ = typ.lstrip().lstrip('/.:') if typ in ['specialTypes']: typ = v[-1][3] typ = typ.replace('/', '.') else: typ = '' dump_file.write("f: %s%s\n" % (s, typ)) elif s.find(' const ') >= 0: dump_file.write("k: %s\n" % s) else: dump_file.write("a: %s\n" % s) get_all(url_root) # get_class('http://livedocs.adobe.com/flex/3/langref/air/net/ServiceMonitor.html')
Python
#!/usr/bin/env python from __future__ import with_statement import subprocess import os import os.path import re import sys import operator as op import string import logging __doc__ = """ Program to convert an intermediate text format that contains the package names, classes and function/attribute declarations for the entire Flex/Flash ActionScript Library. The information used to generate this intermediate file is extracted from the HTML documents of the online libraries. Usage: maketree INPUT_FILE OUTPUT_DIRECTORY Sample format of input file: p: package1.name c: ClassName1 i: ../../flash.net.SuperClass i: ../../flash.net.SuperSuperClass1 a: attribute1:Boolean a: attribute1:Boolean k: public static const CONSTVAL1:String = "binary" f: public function InstanceFunction1():Boolean f: protected function InstanceFunction2():void f: public static function StaticFunction1(arg1:Object):void c: ClassName1 ... p: package2.name c: ClassName3 ... """ class chdir: """ Implementation of "with chdir(path):" statement. """ def __init__(self, dirpath): self.dirpath = dirpath def __enter__(self): self.old = os.getcwd() os.chdir(self.dirpath) def __exit__(self, type, value, tb): os.chdir(self.old) def mkdir_ensure(path, isModule=False): """ Ensure that a certain directory path exists. If the isModule argument is True, it wil create a __init__.py file inside the directory. """ subprocess.call(['mkdir', '-p', path]) init_file = os.path.join(path, '__init__.py') if isModule and not os.path.exists(init_file): with open(init_file, 'w') as f: f.write('# automatically generated #\n') def builtin_types_as2py(type_as): """ Convert a builtin ActionScript 3 type into a native python equivalent. """ d = { 'String': 'str', 'Object': 'object', 'uint': 'long', 'Number': 'float', 'Boolean': 'bool', 'Array': 'list', 'void': 'None', } if d.has_key(type_as): return d[type_as] return type_as def _type_as2py(typ): typ = typ or 'str' typ = builtin_types_as2py(typ) if typ in ['object', 'Function', 'void', '*', '**']: typ = 'str' return True, typ return False, typ class AS3Tree(object): """ Represents an entire ActionScript 3 library. """ def __init__(self): self.packages = dict() def addPackage(self, pack): self.packages[pack.name] = pack def to_py(self, path): mkdir_ensure(path) os.chdir(path) for name, pack in self.packages.items(): pack.to_py() required_imports = set() required_imports.add('from pypy.translator.flex.asmgen import add_import') class AS3Package(object): """ Represents an ActionScript 3 package. """ def __init__(self, name): self.name = name self.classes = dict() def addClass(self, clas): """ Add a class to the package. """ self.classes[clas.name] = clas def _inheritanceTreeToList(self, class_name, d): """ Recursive aux function to convert a inheritance tree to a list that is ordered to comply with class dependencies. """ result = [] if d.has_key(class_name): for subclass in d[class_name]: assert type(subclass) is AS3Class result.append(subclass) result.extend(self._inheritanceTreeToList(subclass.name, d)) return result def _orderClassesByInheritance(self): """ Return this package's class objects ordered to comply with class dependencies. """ d = {} for name, clas in self.classes.items(): i = clas.inheritance if not i or i == 'Error' or i.find('.') >= 0: i = 'Object' if d.has_key(i): d[i].append(clas) else: d[i] = [clas] result = self._inheritanceTreeToList('Object', d) assert len(result) == len(self.classes) return result def to_py(self): classes = self._orderClassesByInheritance() assert self.name pth = self.name.replace('.', '/') pth, fil = pth.rsplit('/', 1) mkdir_ensure(pth, isModule=True) with chdir(pth): s = '' global required_imports for clas in classes: i = clas.to_py_inherit_module() if i: required_imports.add('import ' + i) s += clas.to_py() with open(fil + '.py', 'w') as fd: for i in required_imports: fd.write("%s\n" % i) fd.write(s) class AS3Class(object): """ Represents an ActionScript 3 class. """ def __init__(self, parent=None, name=None, package=None): self.parent = parent self.name = name self.package = package self.functions = [] self.constants = [] self.attributes = [] self.inheritance = None def addFunction(self, func): self.functions.append(func) def addConstant(self, cons): self.constants.append(cons) def addAttribute(self, attr): self.attributes.append(attr) def addInheritance(self, name): assert name if not self.inheritance: if name.startswith(self.parent.name): name = name[len(self.parent.name) + 1:] self.inheritance = name def to_py_inherit_module(self): i = self.to_py_inheritance() i = i.rstrip(string.ascii_letters).rstrip('.') return i def to_py_inheritance(self): if not self.inheritance: return 'object' return self.inheritance def to_py(self): """ Generate a rpython class. """ inherit = self.to_py_inheritance() inherit = builtin_types_as2py(inherit) if inherit == 'object': inherit = 'BasicExternal' self_path = "%s.%s" % (self.parent.name, self.name) s = "\nadd_import('%s')\n" % self_path s += "class %s(%s):\n" % (self.name, inherit) s += " _render_class = '%s'\n" % self_path if not any((self.functions, self.attributes, self.constants)): s += ' pass\n' s += ' _fields = {\n' for attr in self.attributes: s += attr.to_py() s += ' }\n' for cons in self.constants: s += cons.to_py() s += ' _methods = {\n' for func in self.functions: s += func.to_py() s += ' }\n' return s class AS3Constant(object): """ Represents a constant attribute of an ActionScript 3 class. """ def __init__(self, raw='', name='', typ='', val=''): self.raw = raw self.typ = typ self.name = name self.val = val def to_py(self): val = self.val or 'None' return " %s = %s\n" % (self.name, val) class AS3Attribute(object): """ Represents an attribute of an ActionScript 3 class. """ def __init__(self, raw='', name='', typ=''): self.raw = raw self.name = name self.typ = typ def to_py(self): isSpecial, typ = _type_as2py(self.typ) return " '%s': %s,\n" % (self.name, typ or 'None') class AS3Function(object): """ Represents an instance/class function of a ActionScript 3 class. """ def __init__(self, parent=None, raw='', name='', typ='', args=[], isStatic=False): self.parent = parent self.raw = raw assert typ, raw self.typ = typ self.name = name self.args = args self.isStatic = isStatic def to_py(self): s = '' name = self.name if name == self.parent.name: # __init__() return '' if self.isStatic: # TODO return '' global required_imports typ = self.typ.rstrip(string.letters + '*').rstrip('.') if typ: required_imports.add('import ' + typ) args = "" for arg in self.args: todo = '' isSpecialCase, typ = _type_as2py(arg.typ) if isSpecialCase: todo = ' # Fix This (type %s)' % arg.typ args += '\n ' + typ + ',' + todo isSpecialCase, typ = _type_as2py(self.typ) s += " '%s': MethodDesc([%s\n ], %s),\n\n" % (name, args, typ) return s class AS3FunctionArgument(object): """ Represents a function argument belonging to an ActionScript 3 class. """ def __init__(self, raw='', name='', typ='', value='', isEllipsis=False): self.raw = raw self.name = name self.typ = typ self.value = value self.isEllipsis = isEllipsis def __repr__(self): return '<%s: %s >' % (self.__class__.__name__, self.raw) def to_py(self): return self.name #+ ':' + str(builtin_types_as2py(self.typ)) class Parser(object): def __init__(self): self.tree = AS3Tree() self.last_p = None self.last_c = None def _package(self, s): p = AS3Package(name=s) self.tree.addPackage(p) self.last_p = p self.last_c = None def _class(self, s): c = AS3Class(name=s, package=self.last_p, parent=self.last_p) self.last_p.addClass(c) self.last_c = c _re_function_arg = re.compile(r'^\s*(?P<ellipsis>\.{3})?\s*(?P<name>\w+)\s*(:\s*(?P<typ>[\w*]+))?\s*(=\s*(?P<val>.*))?\s*$') def _function_arg(self, raw): """ Parses a function argument, returns an AS3FunctionArgument object. """ m = Parser._re_function_arg.search(raw) if not m: logging.warn('Function argument not valid: %s' % raw) return False d = m.groupdict() arg = AS3FunctionArgument(raw=raw, name=d['name'], isEllipsis=bool(d['ellipsis']), typ=d['typ']) return arg def _function_parse(self, raw): """ Parse the raw value of an f: line. """ l, r = raw.split(' function ', 1) isStatic = l.find('static') >= 0 name, args, typ = re.split('[()]', r, 2) typ = typ.rsplit(':', 1) if typ: typ = typ[-1].strip() args = filter(len, re.split('\s*,\s*', args)) resu = [] for arg in args: arg = self._function_arg(arg) if arg: resu.append(arg) else: logging.error("Could not parse a function of %s.%s: %s" % (self.last_p.name, self.last_c.name, raw)) break return name, resu, typ, isStatic def _function(self, raw): """ Takes the raw value of an f: line, adds an AS3Function object to the current class. """ name, args, typ, isStatic = self._function_parse(raw) f = AS3Function(parent=self.last_c, raw=raw, name=name, args=args, typ=typ, isStatic=isStatic) self.last_c.addFunction(f) def _inherit(self, raw): """ Get the superclass of the current class. """ assert raw self.last_c.addInheritance(raw) if not self.last_c.inheritance: del self.last_p.classes[self.last_c.name] name = self.last_p.name + '.' + self.last_c.name logging.warning("Class %s has no superclass: will be ignored." % name) def _attribute(self, raw): """ Takes the raw value of an a: line, returns an AS3Attribute object. """ name, typ = re.split('\s*:\s*', raw.strip()) typ_value = typ.split('=') if len(typ_value) == 2: typ = typ_value[0].strip() name = name.rstrip().split(" ")[-1] a = AS3Attribute(raw=raw, name=name, typ=typ) self.last_c.addAttribute(a) _re_constant = re.compile(r'(?P<name>\w+)\s*:\s*(?P<typ>[\w\*]+)\s*(=\s*(?P<val>.*))?') def _constant(self, raw): """ Parse the raw value of a k: line. """ m = Parser._re_constant.search(raw) assert m, "Could not parse const attribute:\n\t%s" % raw if m: d = m.groupdict() name = d['name'] typ = d['typ'] val = d['val'] k = AS3Constant(raw=raw, name=name, typ=typ, val=val) self.last_c.addConstant(k) def _line(self, line): """ Process one line. Ignore lines with unknown prefixes. """ c, s = line[:3], line[3:].rstrip() if c == 'p: ': self._package(s) elif c == 'c: ': self._class(s) elif c == 'f: ': self._function(s) elif c == 'a: ': self._attribute(s) elif c == 'k: ': self._constant(s) elif c == 'i: ': self._inherit(s) def parse(self, filename): """ Takes the filename of the intermediate dump file, returns an AS3Tree object. """ for line in open(filename, 'r'): self._line(line) return self.tree filename, dirname = sys.argv[1:3] parser = Parser() tree = parser.parse(filename) tree.to_py(os.path.abspath(dirname))
Python
""" JavaScript type system """ from pypy.rpython.ootypesystem import ootype from pypy.rpython.lltypesystem import lltype from pypy.translator.cli import oopspec from pypy.rpython.lltypesystem.lltype import Signed, Unsigned, Void, Bool, Float from pypy.rpython.lltypesystem.lltype import SignedLongLong, UnsignedLongLong, Primitive from pypy.rpython.lltypesystem.lltype import Char, UniChar from pypy.rpython.ootypesystem.ootype import String, _string, List, StaticMethod from pypy.rlib.objectmodel import Symbolic from pypy.translator.flex.log import log from types import FunctionType from pypy.rpython.extfunc import is_external from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc, ExternalType try: set except NameError: from sets import Set as set class JTS(object): """ Class implementing JavaScript type system calls with mapping similiar to cts """ def __init__(self, db): self.db = db #def __class(self, name): # return name.replace(".", "_") def escape_name(self, name): return name.replace('.', '_') def llvar_to_cts(self, var): return 'var ', var.name def lltype_to_cts(self, t): if isinstance(t, ootype.Instance): self.db.pending_class(t) return self.escape_name(t._name) elif isinstance(t, ootype.List): return "Array" elif isinstance(t, lltype.Primitive): return "var" elif isinstance(t, ootype.Record): return "Object" elif isinstance(t, ootype.String.__class__): return '""' elif isinstance(t, ootype.Dict): return "Object" elif isinstance(t, ootype.DictItemsIterator): return "Object" elif t is ootype.StringBuilder: return "StringBuilder" #return "var" raise NotImplementedError("Type %r" % (t,)) def graph_to_signature(self, graph, is_method = False, func_name = None): func_name = func_name or self.db.get_uniquename(graph,graph.name) args = [arg for arg in graph.getargs() if arg.concretetype is not ootype.Void] if is_method: args = args[1:] return func_name,args def method_signature(self, obj, name): # TODO: use callvirt only when strictly necessary if isinstance(obj, ootype.Instance): owner, meth = obj._lookup(name) METH = meth._TYPE return obj._name, METH.ARGS elif isinstance(obj, ootype.BuiltinType): meth = oopspec.get_method(obj, name) class_name = self.lltype_to_cts(obj) return class_name,meth.ARGS else: assert False def obj_name(self, obj): #import pdb #pdb.set_trace() if isinstance(obj, ExternalType): basic_external = obj._class_ if not hasattr(basic_external, "_render_class"): raise TypeError("This class %s can not be instantiated." % (basic_external,)) return basic_external._render_class return self.lltype_to_cts(obj) def primitive_repr(self, _type, v): if _type is Bool: if v == False: val = 'false' else: val = 'true' elif _type is Void: val = 'undefined' elif isinstance(_type,String.__class__): val = '%r'%v._str elif isinstance(_type,List): # FIXME: It's not ok to use always empty list val = "[]" elif isinstance(_type,StaticMethod): if hasattr(v, 'graph') and not is_external(v): self.db.pending_function(v.graph) else: self.db.pending_abstract_function(v) val = v._name val = val.replace('.', '_') if val == '?': val = 'undefined' elif _type is UniChar or _type is Char: #log("Constant %r"%v) s = repr(v) if s.startswith('u'): s = s[1:] if s != "'\''": s.replace("'", '"') val = s elif isinstance(v, Symbolic): val = v.expr elif isinstance(_type, Primitive): #log("Type: %r"%_type) val = str(v) else: assert False, "Unknown constant %r"%_type val = str(v) return val #def lltype_to_cts(self, t, include_class=True): # return 'var' ## if isinstance(t, ootype.Instance): ## self.db.pending_class(t) ## return self.__class(t._name, include_class) ## elif isinstance(t, ootype.Record): ## name = self.db.pending_record(t) ## return self.__class(name, include_class) ## elif isinstance(t, ootype.StaticMethod): ## return 'void' # TODO: is it correct to ignore StaticMethod? ## elif isinstance(t, ootype.List): ## item_type = self.lltype_to_cts(t._ITEMTYPE) ## return self.__class(PYPY_LIST % item_type, include_class) ## elif isinstance(t, ootype.Dict): ## key_type = self.lltype_to_cts(t._KEYTYPE) ## value_type = self.lltype_to_cts(t._VALUETYPE) ## return self.__class(PYPY_DICT % (key_type, value_type), include_class) ## elif isinstance(t, ootype.DictItemsIterator): ## key_type = self.lltype_to_cts(t._KEYTYPE) ## value_type = self.lltype_to_cts(t._VALUETYPE) ## return self.__class(PYPY_DICT_ITEMS_ITERATOR % (key_type, value_type), include_class) ## ## return _get_from_dict(_lltype_to_cts, t, 'Unknown type %s' % t)
Python
""" Opcode meaning objects, descendants of MicroInstruction """ #from pypy.translator.js.jsbuiltin import Builtins from pypy.translator.oosupport.metavm import PushArg, PushAllArgs, StoreResult,\ InstructionList, New, GetField, MicroInstruction from pypy.translator.flex.log import log from pypy.rpython.ootypesystem import ootype from types import FunctionType from pypy.objspace.flow.model import Constant class NewBuiltin(MicroInstruction): def __init__(self, arg): self.arg = arg def render(self, generator, op): generator.ilasm.new(self.arg) class _ListSetitem(MicroInstruction): def render(self, generator, op): generator.load(op.args[1]) generator.load(op.args[3]) generator.load(op.args[2]) generator.ilasm.list_setitem() ListSetitem = _ListSetitem() class _ListGetitem(MicroInstruction): def render(self, generator, op): generator.load(op.args[1]) generator.load(op.args[2]) generator.ilasm.list_getitem() ListGetitem = _ListGetitem() class _ListContains(MicroInstruction): def render(self, generator, op): generator.load(op.args[1]) generator.load(op.args[2]) generator.ilasm.list_getitem() generator.ilasm.load_void() generator.emit('!=') ListContains = _ListContains() class _Call(MicroInstruction): def render(self, generator, op): graph = op.args[0].value.graph self._render_function(generator, graph, op.args) def _render_builtin(self, generator, builtin, args): for func_arg in args[1:]: # push parameters generator.load(func_arg) generator.call_external(builtin, args[1:]) def _render_builtin_prepared_args(self, generator, builtin, args): for func_arg in args: generator.load_str(func_arg) generator.call_external(builtin, args) def _render_builtin_method(self, generator, builtin, args): for func_arg in args: generator.load_special(func_arg) generator.call_external_method(builtin, len(args)-1) def _render_function(self, generator, graph, args): for func_arg in args[1:]: # push parameters if func_arg.concretetype is not ootype.Void: generator.load(func_arg) generator.call_graph(graph) def _render_method(self, generator, method_name, args): this = args[0] for arg in args: # push parametes generator.load(arg) generator.call_method(this.concretetype, method_name) Call = _Call() class CallBuiltin(_Call): def __init__(self, builtin): if builtin == "": raise "foo" self.builtin = builtin def render(self, generator, op): self._render_builtin(generator, self.builtin, op.args) class CallBuiltinMethod(_Call): def __init__(self, builtin, slice=None, additional_args=[]): self.builtin = builtin self.slice = slice self.additional_args = additional_args def render(self, generator, op): if self.slice is not None: args = op.args[self.slice] else: args = op.args args += self.additional_args self._render_builtin_method(generator, self.builtin, args) class _SameAs(MicroInstruction): def render(self, generator, op): generator.change_name(op.result, op.args[0]) class _CastFun(MicroInstruction): def __init__(self, name, num): self.name = name self.num = num def render(self, generator, op): log("Args: %r"%op.args) generator.cast_function(self.name, self.num) class _Prefix(MicroInstruction): def __init__(self, st): self.st = st def render(self, generator, op): generator.prefix_op(self.st) class _NotImplemented(MicroInstruction): def __init__(self, reason): self.reason = reason def render(self, generator, op): raise NotImplementedError(self.reason) class _CastMethod(MicroInstruction): def __init__(self, method_name, num=0): self.method_name = method_name self.num = num def render(self, generator, op): generator.call_external_method(self.method_name, self.num) class _LoadConst(MicroInstruction): def __init__(self, value): self.value = value def render(self, generator, op): generator.load(Constant(self.value, ootype.typeOf(self.value))) class _GetBuiltinField(MicroInstruction): def render(self, generator, op): this = op.args[0] field = op.args[1].value[1:] generator.load(this) generator.get_field(None, field) class _GetPredefinedField(MicroInstruction): def __init__(self, field): self.field = field def render(self, generator, op): this = op.args[1] generator.load(this) generator.get_field(None, self.field) GetBuiltinField = _GetBuiltinField() class _SetBuiltinField(MicroInstruction): def render(self, generator, op): this = op.args[0] field = op.args[1].value if not field.startswith('o'): generator.load_void() else: value = op.args[2] field_name = field[1:] self.run_it(generator, this, field_name, value) def run_it(self, generator, this, field_name, value): generator.load(this) generator.load_special(value) generator.set_field(None, field_name) class _SetPredefinedField(_SetBuiltinField): def __init__(self, field): self.field = field def render(self, generator, op): value = op.args[2] this = op.args[1] self.run_it(generator, this, self.field, value) class _SetExternalField(_SetBuiltinField): def render(self, generator, op): self.run_it(generator, op.args[0], op.args[1].value, op.args[2]) SetBuiltinField = _SetBuiltinField() SetExternalField = _SetExternalField() class _CallMethod(_Call): def render(self, generator, op): method = op.args[0] self._render_method(generator, method.value, op.args[1:]) class _CallBuiltinObject(_Call): def render(self, generator, op): this = op.args[1].concretetype method = op.args[0] method_name = this._methods[method.value]._name[1:] generator.load(op.args[1]) self._render_builtin_method(generator, method_name, op.args[1:]) class _CallExternalObject(_Call): def render(self, generator, op): this = op.args[1].concretetype method = op.args[0] method_name = method.value #generator.load(op.args[1]) self._render_builtin_method(generator, method_name, op.args[1:]) CallBuiltinObject = _CallBuiltinObject() CallExternalObject = _CallExternalObject() class _IsInstance(MicroInstruction): def render(self, generator, op): # FIXME: just temporary hack generator.load(op.args[0]) generator.ilasm.load_const(op.args[1].value._name.replace('.', '_'))#[-1]) generator.cast_function("_consts_0.isinstanceof", 2) class _IndirectCall(MicroInstruction): def render(self, generator, op): for func_arg in op.args[1:]: # push parameters generator.load(func_arg) generator.call_external(op.args[0].name, op.args[1:]) class _SetTimeout(MicroInstruction): # FIXME: Dirty hack for javascript callback stuff def render(self, generator, op): val = op.args[1].value assert(isinstance(val, ootype._static_meth)) #if isinstance(val, ootype.StaticMethod): real_name = val._name generator.db.pending_function(val.graph) #generator.db.pending_function(val.graph) #else: # concrete = val.concretize() # real_name = concrete.value._name # generator.db.pending_function(concrete.value.graph) generator.load_str("'%s()'" % real_name) generator.load(op.args[2]) generator.call_external('setTimeout',[0]*2) class _DiscardStack(MicroInstruction): def render(self, generator, op): generator.clean_stack() class SetOnEvent(MicroInstruction): def __init__(self, field): self.field = field # FIXME: Dirty hack for javascript callback stuff def render(self, generator, op): val = op.args[1].value val = val.concretize().value assert(isinstance(val, ootype._static_meth)) real_name = val._name generator.db.pending_function(val.graph) generator.load_str("document") generator.load_str(real_name) generator.set_field(None, self.field) class _CheckLength(MicroInstruction): def render(self, generator, op): assert not generator.ilasm.right_hand class _ListRemove(MicroInstruction): def render(self, generator, op): generator.list_getitem(op.args[1], op.args[2]) generator.call_external('delete', [0]) ListRemove = _ListRemove() CheckLength = _CheckLength() SetTimeout = _SetTimeout() IndirectCall = _IndirectCall() IsInstance = _IsInstance() CallMethod = _CallMethod() CopyName = [PushAllArgs, _SameAs ()] CastString = _CastFun("_consts_0.convertToString", 1) SameAs = CopyName DiscardStack = _DiscardStack() def fix_opcodes(opcodes): for key, value in opcodes.iteritems(): if type(value) is str: value = InstructionList([PushAllArgs, value, StoreResult, CheckLength]) elif value == []: value = InstructionList([CheckLength]) elif value is not None: if StoreResult not in value: value.append(StoreResult) if CheckLength not in value: value.append(CheckLength) value = InstructionList(value) opcodes[key] = value
Python
""" JavaScript builtin mappings """ from pypy.translator.oosupport.metavm import InstructionList, PushAllArgs,\ _PushAllArgs from pypy.translator.flex.metavm import SetBuiltinField, ListGetitem, ListSetitem, \ GetBuiltinField, CallBuiltin, Call, SetTimeout, ListContains,\ NewBuiltin, SetOnEvent, ListRemove, CallBuiltinMethod, _GetPredefinedField,\ _SetPredefinedField from pypy.rpython.ootypesystem import ootype class _Builtins(object): def __init__(self): list_resize = _SetPredefinedField('length') self.builtin_map = { 'll_js_jseval' : CallBuiltin('eval'), 'set_on_keydown' : SetOnEvent('onkeydown'), 'set_on_keyup' : SetOnEvent('onkeyup'), 'setTimeout' : SetTimeout, 'll_int_str' : CallBuiltinMethod('toString', [2]), 'll_strconcat' : InstructionList([_PushAllArgs(slice(1, None)), '+']), 'll_int' : CallBuiltin('parseInt'), #'alert' : CallBuiltin('alert'), 'seval' : CallBuiltin('seval'), 'date': NewBuiltin('Date'), 'll_math.ll_math_fmod' : InstructionList([_PushAllArgs(slice(1, None)), '%']), 'll_time_time' : CallBuiltin('time'), 'll_time_clock' : CallBuiltin('clock'), 'll_os_write' : CallBuiltin('_consts_0.flexTrace'), } self.builtin_obj_map = { ootype.String.__class__: { 'll_strconcat' : InstructionList([_PushAllArgs(slice(1, None)), '+']), 'll_strlen' : _GetPredefinedField('length'), 'll_stritem_nonneg' : CallBuiltinMethod('charAt', slice(1,None)), 'll_streq' : InstructionList([_PushAllArgs(slice(1, None)), '==']), 'll_strcmp' : CallBuiltin('strcmp'), 'll_startswith' : CallBuiltin('startswith'), 'll_endswith' : CallBuiltin('endswith'), 'll_split_chr' : CallBuiltin('splitchr'), 'll_substring' : CallBuiltin('substring'), 'll_lower' : CallBuiltinMethod('toLowerCase', slice(1, None)), 'll_upper' : CallBuiltinMethod('toUpperCase', slice(1, None)), 'll_find' : CallBuiltin('findIndexOf'), 'll_find_char' : CallBuiltin('findIndexOf'), 'll_contains' : CallBuiltin('findIndexOfTrue'), 'll_replace_chr_chr' : CallBuiltinMethod('replace', slice(1, None), ['g']), 'll_count_char' : CallBuiltin('countCharOf'), 'll_count' : CallBuiltin('countOf'), }, ootype.List: { 'll_setitem_fast' : ListSetitem, 'll_getitem_fast' : ListGetitem, '_ll_resize' : list_resize, '_ll_resize_ge' : list_resize, '_ll_resize_le' : list_resize, 'll_length' : _GetPredefinedField('length'), }, ootype.Dict: { 'll_get' : ListGetitem, 'll_set' : ListSetitem, 'll_contains' : ListContains, 'll_get_items_iterator' : CallBuiltin('dict_items_iterator'), 'll_length' : CallBuiltin('get_dict_len'), 'll_remove' : ListRemove, 'll_clear': CallBuiltin('clear_dict'), }, ootype.Record: { 'll_get' : ListGetitem, 'll_set' : ListSetitem, 'll_contains' : ListContains, } } self.fix_opcodes() def fix_opcodes(self): from pypy.translator.flex.metavm import fix_opcodes #fix_opcodes(self.builtin_map) #for value in self.builtin_obj_map.values(): # fix_opcodes(value) Builtins = _Builtins()
Python