def test_register_external_tuple_args(self): """ Verify the annotation of a registered external function which takes a tuple argument. """ def function_with_tuple_arg(): """ Dummy function which is declared via register_external to take a tuple as an argument so that register_external's behavior for tuple-taking functions can be verified. """ register_external(function_with_tuple_arg, [(int,)], int) def f(): return function_with_tuple_arg((1,)) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) # Not a very good assertion, but at least it means _something_ happened. assert isinstance(s, annmodel.SomeInteger)
def test_register_external_return_goes_back(self): """ Check whether it works to pass the same list from one external fun to another [bookkeeper and list joining issues] """ def function_with_list(): pass register_external(function_with_list, [[int]], int) def function_returning_list(): pass register_external(function_returning_list, [], [int]) def f(): return function_with_list(function_returning_list()) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) assert isinstance(s, annmodel.SomeInteger)
def test_mixed_classes(): from pypy.rpython.extfunc import register_external class One(BasicExternal): pass class Two(One): pass def g(one): return 3 register_external(g, args=[One], result=int) def f(x): if x: return g(One()) return g(Two()) t = TranslationContext() a = t.buildannotator() s = a.build_types(f, [bool]) a.simplify() typer = t.buildrtyper(type_system="ootype") typer.specialize()
def register_stat_variant(name): if sys.platform.startswith('win'): _functions = { 'stat': '_stati64', 'fstat': '_fstati64', 'lstat': '_stati64' } # no lstat on Windows c_func_name = _functions[name] elif sys.platform.startswith('linux'): # because we always use _FILE_OFFSET_BITS 64 - this helps things work that are not a c compiler _functions = {'stat': 'stat64', 'fstat': 'fstat64', 'lstat': 'lstat64'} c_func_name = _functions[name] else: c_func_name = name arg_is_path = (name != 'fstat') if arg_is_path: ARG1 = rffi.CCHARP else: ARG1 = rffi.INT os_mystat = rffi.llexternal(c_func_name, [ARG1, STAT_STRUCT], rffi.INT, compilation_info=compilation_info) def os_mystat_llimpl(arg): stresult = lltype.malloc(STAT_STRUCT.TO, flavor='raw') try: if arg_is_path: arg = rffi.str2charp(arg) error = rffi.cast(rffi.LONG, os_mystat(arg, stresult)) if arg_is_path: rffi.free_charp(arg) if error != 0: raise OSError(rposix.get_errno(), "os_?stat failed") return build_stat_result(stresult) finally: lltype.free(stresult, flavor='raw') def fakeimpl(arg): st = getattr(os, name)(arg) fields = [TYPE for fieldname, TYPE in LL_STAT_FIELDS] TP = TUPLE_TYPE(fields) ll_tup = lltype.malloc(TP.TO) for i, (fieldname, TYPE) in enumerate(LL_STAT_FIELDS): val = getattr(st, fieldname) rffi.setintfield(ll_tup, 'item%d' % i, int(val)) return ll_tup if arg_is_path: s_arg = str else: s_arg = int register_external(getattr(os, name), [s_arg], s_StatResult, "ll_os.ll_os_%s" % (name, ), llimpl=func_with_new_name(os_mystat_llimpl, 'os_%s_llimpl' % (name, )), llfakeimpl=func_with_new_name(fakeimpl, 'os_%s_fake' % (name, )))
def register_stat_variant(name): if sys.platform.startswith('win'): _functions = {'stat': '_stati64', 'fstat': '_fstati64', 'lstat': '_stati64'} # no lstat on Windows c_func_name = _functions[name] elif sys.platform.startswith('linux'): # because we always use _FILE_OFFSET_BITS 64 - this helps things work that are not a c compiler _functions = {'stat': 'stat64', 'fstat': 'fstat64', 'lstat': 'lstat64'} c_func_name = _functions[name] else: c_func_name = name arg_is_path = (name != 'fstat') if arg_is_path: ARG1 = rffi.CCHARP else: ARG1 = rffi.INT os_mystat = rffi.llexternal(c_func_name, [ARG1, STAT_STRUCT], rffi.INT, compilation_info=compilation_info) def os_mystat_llimpl(arg): stresult = lltype.malloc(STAT_STRUCT.TO, flavor='raw') try: if arg_is_path: arg = rffi.str2charp(arg) error = rffi.cast(rffi.LONG, os_mystat(arg, stresult)) if arg_is_path: rffi.free_charp(arg) if error != 0: raise OSError(rposix.get_errno(), "os_?stat failed") return build_stat_result(stresult) finally: lltype.free(stresult, flavor='raw') def fakeimpl(arg): st = getattr(os, name)(arg) fields = [TYPE for fieldname, TYPE in LL_STAT_FIELDS] TP = TUPLE_TYPE(fields) ll_tup = lltype.malloc(TP.TO) for i, (fieldname, TYPE) in enumerate(LL_STAT_FIELDS): val = getattr(st, fieldname) rffi.setintfield(ll_tup, 'item%d' % i, int(val)) return ll_tup if arg_is_path: s_arg = str else: s_arg = int register_external(getattr(os, name), [s_arg], s_StatResult, "ll_os.ll_os_%s" % (name,), llimpl=func_with_new_name(os_mystat_llimpl, 'os_%s_llimpl' % (name,)), llfakeimpl=func_with_new_name(fakeimpl, 'os_%s_fake' % (name,)))
def test_register_external_signature(self): """ Test the standard interface for external functions. """ def dd(): pass register_external(dd, [int], int) def f(): return dd(3) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) assert isinstance(s, annmodel.SomeInteger)
def test_register_external_specialcase(self): """ When args=None, the external function accepts any arguments unmodified. """ def function_withspecialcase(arg): return repr(arg) register_external(function_withspecialcase, args=None, result=str) def f(): x = function_withspecialcase return x(33) + x("aaa") + x([]) + "\n" policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) assert isinstance(s, annmodel.SomeString)
def test_list_of_str0(self): str0 = annmodel.SomeString(no_nul=True) def os_execve(l): pass register_external(os_execve, [[str0]], None) def f(l): return os_execve(l) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) a.build_types(f, [[str]]) # Does not raise assert a.translator.config.translation.check_str_without_nul == False # Now enable the str0 check, and try again with a similar function a.translator.config.translation.check_str_without_nul = True def g(l): return os_execve(l) raises(Exception, a.build_types, g, [[str]]) a.build_types(g, [[str0]]) # Does not raise
def test_register_external_tuple_args(self): """ Verify the annotation of a registered external function which takes a tuple argument. """ def function_with_tuple_arg(): """ Dummy function which is declared via register_external to take a tuple as an argument so that register_external's behavior for tuple-taking functions can be verified. """ register_external(function_with_tuple_arg, [(int, )], int) def f(): return function_with_tuple_arg((1, )) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) # Not a very good assertion, but at least it means _something_ happened. assert isinstance(s, annmodel.SomeInteger)
def declare_new_w_star(name): """ stupid workaround for the python late-binding 'feature' """ def fake(status): return int(getattr(os, name)(status)) fake.func_name = 'fake_' + name os_c_func = rffi.llexternal(name, [lltype.Signed], lltype.Signed, _callable=fake, includes=["sys/wait.h", "sys/types.h"]) if name in w_star_returning_int: def lltypeimpl(status): return os_c_func(status) resulttype = int else: def lltypeimpl(status): return bool(os_c_func(status)) resulttype = bool lltypeimpl.func_name = name + '_lltypeimpl' register_external(getattr(os, name), [int], resulttype, "ll_os."+name, llimpl=lltypeimpl)
def test_raising_llimpl(): from pypy.rpython.extfunc import register_external def external(): pass def raising(): raise OSError(15, "abcd") ext = register_external(external, [], llimpl=raising, llfakeimpl=raising) def f(): # this is a useful llfakeimpl that raises an exception try: external() return True except OSError: return False res = interpret(f, []) assert not res
from pypy.rpython.extfunc import genericcallable, register_external from pypy.rpython.ootypesystem.bltregistry import BasicExternal, MethodDesc # For each wrapped function, we define an empty function, and then register it with an actionscript function: # This one is for debug output, so we can see our calls working def flexTrace(s): pass # This function has one arg, which is of type string # if there were a return type, it would be result=<type> # export_name refers to the corresponding Actionscript function. In this case it's _const_0.flexTrace, which is defined by us in library.as register_external(flexTrace, args=[str], export_name="_consts_0.flexTrace") # Wrapping a Actionscript class as a python class class Date(BasicExternal): # This ties the Python "Date" class to the Actionscript "Date" class _render_class = "Date" # This lists the methods. The required argument for MethodDesc is a list of arguments (which are all empty in this case). # The return types are specified by retval=<type> _methods = { 'getDate': MethodDesc([], retval=int), 'getFullYear': MethodDesc([], retval=int), 'getMonth': MethodDesc([], retval=int), 'getHours': MethodDesc([], retval=int), 'getMinutes': MethodDesc([], retval=int), } # The Date class in Actionscript doesn't require importing any libraries, but if it did, we would import the library with: # add_import(<libname>) # We would do it at the top level, not in flash_main
_PPC = RPPCAssembler _flush_icache = None def flush_icache(base, size): global _flush_icache if _flush_icache == None: cpath = py.magic.autopath().dirpath().join('_flush_icache.c') _flush_icache = cpath._getpymodule()._flush_icache _flush_icache(base, size) register_external(flush_icache, [int, int], None, "LL_flush_icache") NSAVEDREGISTERS = 19 DEBUG_TRAP = option.trap DEBUG_PRINT = option.debug_print _var_index = [0] class Var(GenVar): conditional = False def __init__(self): self.__magic_index = _var_index[0] _var_index[0] += 1
interp_curses.module_info.setupterm_called = True finally: lltype.free(intp, flavor='raw') def curses_setupterm_null_llimpl(fd): curses_setupterm(lltype.nullptr(rffi.CCHARP.TO), fd) def curses_setupterm_llimpl(term, fd): ll_s = rffi.str2charp(term) try: curses_setupterm(ll_s, fd) finally: rffi.free_charp(ll_s) register_external(interp_curses._curses_setupterm_null, [int], llimpl=curses_setupterm_null_llimpl, export_name='_curses.setupterm_null') register_external(interp_curses._curses_setupterm, [str, int], llimpl=curses_setupterm_llimpl, export_name='_curses.setupterm') def check_setup_invoked(): if not interp_curses.module_info.setupterm_called: raise interp_curses.curses_error("must call (at least) setupterm() first") def tigetstr_llimpl(cap): check_setup_invoked() ll_cap = rffi.str2charp(cap) try: ll_res = c_tigetstr(ll_cap) num = lltype.cast_ptr_to_int(ll_res)
lltype.Void, sandboxsafe=True, _nowrapper=True) def llimpl_arena_malloc(nbytes, zero): addr = llimpl_malloc(nbytes) if bool(addr): llimpl_arena_reset(addr, nbytes, zero) return addr llimpl_arena_malloc._always_inline_ = True register_external(arena_malloc, [int, int], llmemory.Address, 'll_arena.arena_malloc', llimpl=llimpl_arena_malloc, llfakeimpl=arena_malloc, sandboxsafe=True) register_external(arena_free, [llmemory.Address], None, 'll_arena.arena_free', llimpl=llimpl_free, llfakeimpl=arena_free, sandboxsafe=True) def llimpl_arena_reset(arena_addr, size, zero): if zero: if zero == 1: clear_large_memory_chunk(arena_addr, size)
llimpl_malloc = rffi.llexternal('malloc', [lltype.Signed], llmemory.Address, sandboxsafe=True, _nowrapper=True) llimpl_free = rffi.llexternal('free', [llmemory.Address], lltype.Void, sandboxsafe=True, _nowrapper=True) def llimpl_arena_malloc(nbytes, zero): addr = llimpl_malloc(nbytes) if bool(addr): llimpl_arena_reset(addr, nbytes, zero) return addr llimpl_arena_malloc._always_inline_ = True register_external(arena_malloc, [int, int], llmemory.Address, 'll_arena.arena_malloc', llimpl=llimpl_arena_malloc, llfakeimpl=arena_malloc, sandboxsafe=True) register_external(arena_free, [llmemory.Address], None, 'll_arena.arena_free', llimpl=llimpl_free, llfakeimpl=arena_free, sandboxsafe=True) def llimpl_arena_reset(arena_addr, size, zero): if zero: if zero == 1: clear_large_memory_chunk(arena_addr, size) else: llmemory.raw_memclear(arena_addr, size) llimpl_arena_reset._always_inline_ = True
if USE_SHORT_FLOAT_REPR: from pypy.rlib.rdtoa import strtod return strtod(s) sign, before_point, after_point, exponent = break_up_float(s) if not before_point and not after_point: raise ValueError return parts_to_float(sign, before_point, after_point, exponent) def oo_rstring_to_float(s): from pypy.rpython.annlowlevel import oostr from pypy.rpython.ootypesystem import ootype lls = oostr(s) return ootype.ooparse_float(lls) register_external(rstring_to_float, [SomeString(can_be_None=False)], float, llimpl=rstring_to_float_impl, ooimpl=oo_rstring_to_float, sandboxsafe=True) # float as string -> sign, beforept, afterpt, exponent def break_up_float(s): i = 0 sign = '' before_point = '' after_point = '' exponent = '' if s[i] in '+-': sign = s[i] i += 1
try: if c_tcgetattr(fd, c_struct) < 0: raise OSError(rposix.get_errno(), 'tcgetattr failed') cc = [chr(c_struct.c_c_cc[i]) for i in range(NCCS)] ispeed = c_cfgetispeed(c_struct) ospeed = c_cfgetospeed(c_struct) result = (intmask(c_struct.c_c_iflag), intmask(c_struct.c_c_oflag), intmask(c_struct.c_c_cflag), intmask(c_struct.c_c_lflag), intmask(ispeed), intmask(ospeed), cc) return result finally: lltype.free(c_struct, flavor='raw') register_external(rtermios.tcgetattr, [int], (int, int, int, int, int, int, [str]), llimpl=tcgetattr_llimpl, export_name='termios.tcgetattr') def tcsetattr_llimpl(fd, when, attributes): c_struct = lltype.malloc(TERMIOSP.TO, flavor='raw') try: c_struct.c_c_iflag = r_uint(attributes[0]) c_struct.c_c_oflag = r_uint(attributes[1]) c_struct.c_c_cflag = r_uint(attributes[2]) c_struct.c_c_lflag = r_uint(attributes[3]) ispeed = r_uint(attributes[4]) ospeed = r_uint(attributes[5]) cc = attributes[6] for i in range(NCCS): c_struct.c_c_cc[i] = rffi.r_uchar(ord(cc[i][0]))
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,
def f(): return d(callback) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) assert isinstance(s, annmodel.SomeFloat) assert a.translator._graphof(callback) def dd(): pass register_external(dd, [int], int) def test_register_external_signature(): def f(): return dd(3) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) assert isinstance(s, annmodel.SomeInteger) def function_with_tuple_arg(): """
os_getenv = rffi.llexternal('getenv', [rffi.CCHARP], rffi.CCHARP) def getenv_llimpl(name): l_name = rffi.str2charp(name) l_result = os_getenv(l_name) if l_result: result = rffi.charp2str(l_result) else: result = None rffi.free_charp(l_name) return result register_external(r_getenv, [str], annmodel.SomeString(can_be_None=True), export_name='ll_os.ll_os_getenv', llimpl=getenv_llimpl) # ____________________________________________________________ def r_putenv(name, value): just_a_placeholder class EnvKeepalive: pass envkeepalive = EnvKeepalive() envkeepalive.byname = {}
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() window._render_name = 'window' document = window.document 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]),
""" mochikit wrappers """ from pypy.rpython.extfunc import genericcallable from pypy.rpython.extfunc import 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
just_a_placeholder # should return None if name not found os_getenv = rffi.llexternal('getenv', [rffi.CCHARP], rffi.CCHARP) def getenv_llimpl(name): l_name = rffi.str2charp(name) l_result = os_getenv(l_name) if l_result: result = rffi.charp2str(l_result) else: result = None rffi.free_charp(l_name) return result register_external(r_getenv, [str0], annmodel.SomeString(can_be_None=True, no_nul=True), export_name='ll_os.ll_os_getenv', llimpl=getenv_llimpl) # ____________________________________________________________ def r_putenv(name, value): just_a_placeholder class EnvKeepalive: pass envkeepalive = EnvKeepalive() envkeepalive.byname = {} os_putenv = rffi.llexternal('putenv', [rffi.CCHARP], rffi.INT) def putenv_llimpl(name, value):
'y': int, 'label':str, 'labelPlacement':str, } _methods = { 'addEventListener':MethodDesc([str, genericcallable([Event])]), 'move': MethodDesc([int, int]) } # These Get and Set from the globally accesible Actionscript Dictionary object (see library.as) def getGlobal(s): pass register_external(getGlobal, args=[str], export_name="_consts_0.getGlobal", result=TextArea) def setGlobal(s): pass register_external(setGlobal, args=[str, TextArea], export_name="_consts_0.setGlobal") # Window stuff; note the use of Control class Window(BasicExternal): _methods = { 'addChild': MethodDesc([Control]), }
return 2.5 def f(): return d(callback) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) assert isinstance(s, annmodel.SomeFloat) assert a.translator._graphof(callback) def dd(): pass register_external(dd, [int], int) def test_register_external_signature(): def f(): return dd(3) policy = AnnotatorPolicy() policy.allow_someobjects = False a = RPythonAnnotator(policy=policy) s = a.build_types(f, []) assert isinstance(s, annmodel.SomeInteger) def function_with_tuple_arg(): """ Dummy function which is declared via register_external to take a tuple as
def curses_setupterm_null_llimpl(fd): curses_setupterm(lltype.nullptr(rffi.CCHARP.TO), fd) def curses_setupterm_llimpl(term, fd): ll_s = rffi.str2charp(term) try: curses_setupterm(ll_s, fd) finally: rffi.free_charp(ll_s) register_external(interp_curses._curses_setupterm_null, [int], llimpl=curses_setupterm_null_llimpl, export_name='_curses.setupterm_null') register_external(interp_curses._curses_setupterm, [str, int], llimpl=curses_setupterm_llimpl, export_name='_curses.setupterm') def check_setup_invoked(): if not interp_curses.module_info.setupterm_called: raise interp_curses.curses_error( "must call (at least) setupterm() first") def tigetstr_llimpl(cap): check_setup_invoked() ll_cap = rffi.str2charp(cap)
def numeric_formatting_impl(): conv = localeconv() decimal_point = rffi.charp2str(conv.c_decimal_point) thousands_sep = rffi.charp2str(conv.c_thousands_sep) grouping = rffi.charp2str(conv.c_grouping) return decimal_point, thousands_sep, grouping def oo_numeric_formatting(): return ".", "", "" register_external( numeric_formatting, [], (str, str, str), llimpl=numeric_formatting_impl, ooimpl=oo_numeric_formatting, sandboxsafe=True, ) _setlocale = external("setlocale", [rffi.INT, rffi.CCHARP], rffi.CCHARP) def setlocale(category, locale): if cConfig.LC_MAX is not None: if not cConfig.LC_MIN <= category <= cConfig.LC_MAX: raise LocaleError("invalid locale category") ll_result = _setlocale(rffi.cast(rffi.INT, category), locale) if not ll_result: raise LocaleError("unsupported locale setting")
sign, before_point, after_point, exponent = break_up_float(s) if not before_point and not after_point: raise ValueError return parts_to_float(sign, before_point, after_point, exponent) def oo_rstring_to_float(s): from pypy.rpython.annlowlevel import oostr from pypy.rpython.ootypesystem import ootype lls = oostr(s) return ootype.ooparse_float(lls) register_external(rstring_to_float, [SomeString(can_be_None=False)], float, llimpl=rstring_to_float_impl, ooimpl=oo_rstring_to_float, sandboxsafe=True) # float as string -> sign, beforept, afterpt, exponent def break_up_float(s): i = 0 sign = '' before_point = '' after_point = '' exponent = '' if s[i] in '+-': sign = s[i]
except ImportError: pass else: from pypy.rpython.module import ll_termios # the following functions all take one float, return one float # and are part of math.h for name in ll_math.unary_math_functions: llimpl = getattr(ll_math, 'll_math_%s' % name, None) try: f = getattr(math, name) except AttributeError: f = getattr(rfloat, name) register_external(f, [float], float, export_name="ll_math.ll_math_%s" % name, sandboxsafe=True, llimpl=llimpl) _register = [ # (module, [(method name, arg types, return type), ...], ...) (rfloat, [ ('isinf', [float], bool), ('isnan', [float], bool), ('isfinite', [float], bool), ('copysign', [float, float], float), ]), (math, [ ('floor', [float], float), ('sqrt', [float], float), ('log', [float], float), ('log10', [float], float),
# XXX any better implementation on Windows? # Should use VirtualAlloc() to reserve the range of pages, # and commit some pages gradually with support from the GC. # Or it might be enough to decommit the pages and recommit # them immediately. clear_large_memory_chunk = llmemory.raw_memclear def llimpl_arena_malloc(nbytes, zero): addr = llmemory.raw_malloc(nbytes) if zero and bool(addr): clear_large_memory_chunk(addr, nbytes) return addr register_external(arena_malloc, [int, bool], llmemory.Address, 'll_arena.arena_malloc', llimpl=llimpl_arena_malloc, llfakeimpl=arena_malloc, sandboxsafe=True) def llimpl_arena_free(arena_addr): llmemory.raw_free(arena_addr) register_external(arena_free, [llmemory.Address], None, 'll_arena.arena_free', llimpl=llimpl_arena_free, llfakeimpl=arena_free, sandboxsafe=True) def llimpl_arena_reset(arena_addr, size, zero): if zero: if zero == 1: clear_large_memory_chunk(arena_addr, size) else:
""" mochikit wrappers """ from pypy.rpython.extfunc import genericcallable from pypy.rpython.extfunc import 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
import termios except ImportError: pass else: from pypy.rpython.module import ll_termios # the following functions all take one float, return one float # and are part of math.h for name in ll_math.unary_math_functions: llimpl = getattr(ll_math, 'll_math_%s' % name, None) try: f = getattr(math, name) except AttributeError: f = getattr(rfloat, name) register_external(f, [float], float, export_name="ll_math.ll_math_%s" % name, sandboxsafe=True, llimpl=llimpl) _register = [ # (module, [(method name, arg types, return type), ...], ...) (rfloat, [ ('isinf', [float], bool), ('isnan', [float], bool), ('isfinite', [float], bool), ('copysign', [float, float], float), ]), (math, [ ('floor', [float], float), ('sqrt', [float], float), ('log', [float], float), ('log10', [float], float), ('sin', [float], float),
# ------------------------------- os.execv ------------------------------ if hasattr(os, 'execv'): os_execv = rffi.llexternal('execv', [rffi.CCHARP, rffi.CCHARPP], lltype.Signed) def execv_lltypeimpl(path, args): l_path = rffi.str2charp(path) l_args = rffi.liststr2charpp(args) os_execv(l_path, l_args) rffi.free_charpp(l_args) rffi.free_charp(l_path) raise OSError(rffi.c_errno, "execv failed") register_external(os.execv, [str, [str]], s_ImpossibleValue, llimpl= execv_lltypeimpl, export_name="ll_os.ll_os_execv") # ------------------------------- os.dup -------------------------------- os_dup = rffi.llexternal('dup', [lltype.Signed], lltype.Signed, _callable=os.dup) def dup_lltypeimpl(fd): newfd = os_dup(fd) if newfd == -1: raise OSError(rffi.c_errno, "dup failed") return newfd register_external(os.dup, [int], int, llimpl=dup_lltypeimpl, export_name="ll_os.ll_os_dup", oofakeimpl=os.dup) # ------------------------------- os.dup2 -------------------------------
c_struct = lltype.malloc(TERMIOSP.TO, flavor='raw') try: if c_tcgetattr(fd, c_struct) < 0: raise OSError(rposix.get_errno(), 'tcgetattr failed') cc = [chr(c_struct.c_c_cc[i]) for i in range(NCCS)] ispeed = c_cfgetispeed(c_struct) ospeed = c_cfgetospeed(c_struct) result = (intmask(c_struct.c_c_iflag), intmask(c_struct.c_c_oflag), intmask(c_struct.c_c_cflag), intmask(c_struct.c_c_lflag), intmask(ispeed), intmask(ospeed), cc) return result finally: lltype.free(c_struct, flavor='raw') register_external(rtermios.tcgetattr, [int], (int, int, int, int, int, int, [str]), llimpl=tcgetattr_llimpl, export_name='termios.tcgetattr') def tcsetattr_llimpl(fd, when, attributes): c_struct = lltype.malloc(TERMIOSP.TO, flavor='raw') try: c_struct.c_c_iflag = r_uint(attributes[0]) c_struct.c_c_oflag = r_uint(attributes[1]) c_struct.c_c_cflag = r_uint(attributes[2]) c_struct.c_c_lflag = r_uint(attributes[3]) ispeed = r_uint(attributes[4]) ospeed = r_uint(attributes[5]) cc = attributes[6] for i in range(NCCS): c_struct.c_c_cc[i] = rffi.r_uchar(ord(cc[i][0])) if c_cfsetispeed(c_struct, ispeed) < 0: raise OSError(rposix.get_errno(), 'tcsetattr failed')
class RPPCAssembler(make_rassembler(MyPPCAssembler)): def emit(self, value): self.mc.write(value) _PPC = RPPCAssembler _flush_icache = None def flush_icache(base, size): global _flush_icache if _flush_icache == None: cpath = py.magic.autopath().dirpath().join('_flush_icache.c') _flush_icache = cpath._getpymodule()._flush_icache _flush_icache(base, size) register_external(flush_icache, [int, int], None, "LL_flush_icache") NSAVEDREGISTERS = 19 DEBUG_TRAP = option.trap DEBUG_PRINT = option.debug_print _var_index = [0] class Var(GenVar): conditional = False def __init__(self): self.__magic_index = _var_index[0] _var_index[0] += 1 def __repr__(self): return "v%d" % self.__magic_index