code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
from ctypes import c_char, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint
from ctypes import c_long, c_ulong, c_longlong, c_ulonglong, c_float
from ctypes import c_double, c_wchar, c_char_p
from pypy.annotation import model as annmodel
from pypy.rpython.rctypes.implementation import CTypesCallEntry, CTypesObjEntry
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.rctypes import rcarithmetic as rcarith
ctypes_annotation_list = {
c_char: lltype.Char,
#c_wchar: lltype.UniChar,
c_byte: rcarith.CByte,
c_ubyte: rcarith.CUByte,
c_short: rcarith.CShort,
c_ushort: rcarith.CUShort,
c_int: rcarith.CInt,
c_uint: rcarith.CUInt,
c_long: rcarith.CLong,
c_ulong: rcarith.CULong,
c_longlong: rcarith.CLonglong,
c_ulonglong: rcarith.CULonglong,
#c_float: lltype.Float,
c_double: lltype.Float,
} # nb. platform-dependent duplicate ctypes are removed
def return_lltype(c_type):
ll_type = ctypes_annotation_list[c_type]
if isinstance(ll_type, lltype.Number):
return ll_type.normalized()
return ll_type
class CallEntry(CTypesCallEntry):
"Annotation and rtyping of calls to primitive c_xxx types."
def specialize_call(self, hop):
r_primitive = hop.r_result
hop.exception_cannot_occur()
v_result = r_primitive.allocate_instance(hop.llops)
if len(hop.args_s):
v_value, = hop.inputargs(r_primitive.ll_type)
r_primitive.setvalue(hop.llops, v_result, v_value)
return v_result
class ObjEntry(CTypesObjEntry):
"Annotation and rtyping of instances of the primitive c_xxx type."
def get_repr(self, rtyper, s_primitive):
from pypy.rpython.rctypes.rprimitive import PrimitiveRepr
ll_type = ctypes_annotation_list[self.type]
return PrimitiveRepr(rtyper, s_primitive, ll_type)
def get_field_annotation(self, s_primitive, fieldname):
assert fieldname == 'value'
return self.get_s_value()
def get_s_value(self):
ll_type = return_lltype(self.type)
return annmodel.lltype_to_annotation(ll_type)
s_return_trick = property(get_s_value)
for _ctype in ctypes_annotation_list:
CallEntry._register_value(_ctype)
ObjEntry._register_type(_ctype)
| Python |
#! /usr/bin/env python
import os, py, sys
import ctypes
from pypy.translator.tool.cbuild import build_executable
from pypy.tool.udir import udir
# ____________________________________________________________
#
# Helpers for simple cases
def getstruct(name, c_header_source, interesting_fields):
class CConfig:
_header_ = c_header_source
STRUCT = Struct(name, interesting_fields)
return configure(CConfig)['STRUCT']
def getsimpletype(name, c_header_source, ctype_hint=ctypes.c_int):
class CConfig:
_header_ = c_header_source
TYPE = SimpleType(name, ctype_hint)
return configure(CConfig)['TYPE']
def getconstantinteger(name, c_header_source):
class CConfig:
_header_ = c_header_source
CONST = ConstantInteger(name)
return configure(CConfig)['CONST']
def getdefined(macro, c_header_source):
class CConfig:
_header_ = c_header_source
DEFINED = Defined(macro)
return configure(CConfig)['DEFINED']
# ____________________________________________________________
#
# General interface
class ConfigResult:
def __init__(self, CConfig, info, entries):
self.CConfig = CConfig
self.result = {}
self.info = info
self.entries = entries
def get_entry_result(self, entry):
try:
return self.result[entry]
except KeyError:
pass
name = self.entries[entry]
info = self.info[name]
self.result[entry] = entry.build_result(info, self)
def get_result(self):
return dict([(name, self.result[entry])
for entry, name in self.entries.iteritems()])
def configure(CConfig):
"""Examine the local system by running the C compiler.
The CConfig class contains CConfigEntry attribues that describe
what should be inspected; configure() returns a dict mapping
names to the results.
"""
entries = []
for key in dir(CConfig):
value = getattr(CConfig, key)
if isinstance(value, CConfigEntry):
entries.append((key, value))
filepath = uniquefilepath()
f = filepath.open('w')
print >> f, C_HEADER
print >> f
for path in getattr(CConfig, '_includes_', ()): # optional
print >> f, '#include <%s>' % (path,)
print >> f, getattr(CConfig, '_header_', '') # optional
print >> f
for key, entry in entries:
print >> f, 'void dump_section_%s(void) {' % (key,)
for line in entry.prepare_code():
if line and line[0] != '#':
line = '\t' + line
print >> f, line
print >> f, '}'
print >> f
print >> f, 'int main(void) {'
for key, entry in entries:
print >> f, '\tprintf("-+- %s\\n");' % (key,)
print >> f, '\tdump_section_%s();' % (key,)
print >> f, '\tprintf("---\\n");'
print >> f, '\treturn 0;'
print >> f, '}'
f.close()
include_dirs = getattr(CConfig, '_include_dirs_', [])
infolist = list(run_example_code(filepath, include_dirs))
assert len(infolist) == len(entries)
resultinfo = {}
resultentries = {}
for info, (key, entry) in zip(infolist, entries):
resultinfo[key] = info
resultentries[entry] = key
result = ConfigResult(CConfig, resultinfo, resultentries)
for name, entry in entries:
result.get_entry_result(entry)
return result.get_result()
# ____________________________________________________________
class CConfigEntry(object):
"Abstract base class."
class Struct(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined structure.
"""
def __init__(self, name, interesting_fields, ifdef=None):
self.name = name
self.interesting_fields = interesting_fields
self.ifdef = ifdef
def prepare_code(self):
if self.ifdef is not None:
yield '#ifdef %s' % (self.ifdef,)
yield 'typedef %s ctypesplatcheck_t;' % (self.name,)
yield 'typedef struct {'
yield ' char c;'
yield ' ctypesplatcheck_t s;'
yield '} ctypesplatcheck2_t;'
yield ''
yield 'ctypesplatcheck_t s;'
if self.ifdef is not None:
yield 'dump("defined", 1);'
yield 'dump("align", offsetof(ctypesplatcheck2_t, s));'
yield 'dump("size", sizeof(ctypesplatcheck_t));'
for fieldname, fieldtype in self.interesting_fields:
yield 'dump("fldofs %s", offsetof(ctypesplatcheck_t, %s));'%(
fieldname, fieldname)
yield 'dump("fldsize %s", sizeof(s.%s));' % (
fieldname, fieldname)
if fieldtype in integer_class:
yield 's.%s = 0; s.%s = ~s.%s;' % (fieldname,
fieldname,
fieldname)
yield 'dump("fldunsigned %s", s.%s > 0);' % (fieldname,
fieldname)
if self.ifdef is not None:
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if self.ifdef is not None:
if not info['defined']:
return None
alignment = 1
layout = [None] * info['size']
for fieldname, fieldtype in self.interesting_fields:
if isinstance(fieldtype, Struct):
offset = info['fldofs ' + fieldname]
size = info['fldsize ' + fieldname]
c_fieldtype = config_result.get_entry_result(fieldtype)
layout_addfield(layout, offset, c_fieldtype, fieldname)
alignment = max(alignment, ctype_alignment(c_fieldtype))
else:
offset = info['fldofs ' + fieldname]
size = info['fldsize ' + fieldname]
sign = info.get('fldunsigned ' + fieldname, False)
if (size, sign) != size_and_sign(fieldtype):
fieldtype = fixup_ctype(fieldtype, fieldname, (size, sign))
layout_addfield(layout, offset, fieldtype, fieldname)
alignment = max(alignment, ctype_alignment(fieldtype))
# try to enforce the same alignment as the one of the original
# structure
if alignment < info['align']:
choices = [ctype for ctype in alignment_types
if ctype_alignment(ctype) == info['align']]
assert choices, "unsupported alignment %d" % (info['align'],)
choices = [(ctypes.sizeof(ctype), i, ctype)
for i, ctype in enumerate(choices)]
csize, _, ctype = min(choices)
for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
else:
raise AssertionError("unenforceable alignment %d" % (
info['align'],))
n = 0
for i, cell in enumerate(layout):
if cell is not None:
continue
layout_addfield(layout, i, ctypes.c_char, '_pad%d' % (n,))
n += 1
# build the ctypes Structure
seen = {}
fields = []
for cell in layout:
if cell in seen:
continue
fields.append((cell.name, cell.ctype))
seen[cell] = True
class S(ctypes.Structure):
_fields_ = fields
name = self.name
if name.startswith('struct '):
name = name[7:]
S.__name__ = name
return S
class SimpleType(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined simple numeric type.
"""
def __init__(self, name, ctype_hint=ctypes.c_int, ifdef=None):
self.name = name
self.ctype_hint = ctype_hint
self.ifdef = ifdef
def prepare_code(self):
if self.ifdef is not None:
yield '#ifdef %s' % (self.ifdef,)
yield 'typedef %s ctypesplatcheck_t;' % (self.name,)
yield ''
yield 'ctypesplatcheck_t x;'
if self.ifdef is not None:
yield 'dump("defined", 1);'
yield 'dump("size", sizeof(ctypesplatcheck_t));'
if self.ctype_hint in integer_class:
yield 'x = 0; x = ~x;'
yield 'dump("unsigned", x > 0);'
if self.ifdef is not None:
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if self.ifdef is not None and not info['defined']:
return None
size = info['size']
sign = info.get('unsigned', False)
ctype = self.ctype_hint
if (size, sign) != size_and_sign(ctype):
ctype = fixup_ctype(ctype, self.name, (size, sign))
return ctype
class ConstantInteger(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined integer constant.
"""
def __init__(self, name):
self.name = name
def prepare_code(self):
yield 'if ((%s) < 0) {' % (self.name,)
yield ' long long x = (long long)(%s);' % (self.name,)
yield ' printf("value: %lld\\n", x);'
yield '} else {'
yield ' unsigned long long x = (unsigned long long)(%s);' % (
self.name,)
yield ' printf("value: %llu\\n", x);'
yield '}'
def build_result(self, info, config_result):
return info['value']
class DefinedConstantInteger(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined integer constant. If not #defined the value will be None.
"""
def __init__(self, macro):
self.name = self.macro = macro
def prepare_code(self):
yield '#ifdef %s' % self.macro
yield 'dump("defined", 1);'
yield 'if ((%s) < 0) {' % (self.macro,)
yield ' long long x = (long long)(%s);' % (self.macro,)
yield ' printf("value: %lld\\n", x);'
yield '} else {'
yield ' unsigned long long x = (unsigned long long)(%s);' % (
self.macro,)
yield ' printf("value: %llu\\n", x);'
yield '}'
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if info["defined"]:
return info['value']
return None
class DefinedConstantString(CConfigEntry):
"""
"""
def __init__(self, macro):
self.macro = macro
self.name = macro
def prepare_code(self):
yield '#ifdef %s' % self.macro
yield 'int i;'
yield 'char *p = %s;' % self.macro
yield 'dump("defined", 1);'
yield 'for (i = 0; p[i] != 0; i++ ) {'
yield ' printf("value_%d: %d\\n", i, (int)(unsigned char)p[i]);'
yield '}'
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if info["defined"]:
string = ''
d = 0
while info.has_key('value_%d' % d):
string += chr(info['value_%d' % d])
d += 1
return string
return None
class Defined(CConfigEntry):
"""A boolean, corresponding to an #ifdef.
"""
def __init__(self, macro):
self.macro = macro
self.name = macro
def prepare_code(self):
yield '#ifdef %s' % (self.macro,)
yield 'dump("defined", 1);'
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
return bool(info['defined'])
class Library(CConfigEntry):
"""The loaded CTypes library object.
"""
def __init__(self, name):
self.name = name
def prepare_code(self):
# XXX should check that we can link against the lib
return []
def build_result(self, info, config_result):
from pypy.rpython.rctypes.tool import util
path = util.find_library(self.name)
mylib = ctypes.cdll.LoadLibrary(path)
class _FuncPtr(ctypes._CFuncPtr):
_flags_ = ctypes._FUNCFLAG_CDECL
_restype_ = ctypes.c_int # default, can be overridden in instances
includes = tuple(config_result.CConfig._includes_)
libraries = (self.name,)
mylib._FuncPtr = _FuncPtr
return mylib
# ____________________________________________________________
#
# internal helpers
def ctype_alignment(c_type):
if issubclass(c_type, ctypes.Structure):
return max([ctype_alignment(fld_type)
for fld_name, fld_type in c_type._fields_])
return ctypes.alignment(c_type)
def uniquefilepath(LAST=[0]):
i = LAST[0]
LAST[0] += 1
return udir.join('ctypesplatcheck_%d.c' % i)
alignment_types = [
ctypes.c_short,
ctypes.c_int,
ctypes.c_long,
ctypes.c_float,
ctypes.c_double,
ctypes.c_char_p,
ctypes.c_void_p,
ctypes.c_longlong,
ctypes.c_wchar,
ctypes.c_wchar_p,
]
integer_class = [ctypes.c_byte, ctypes.c_ubyte,
ctypes.c_short, ctypes.c_ushort,
ctypes.c_int, ctypes.c_uint,
ctypes.c_long, ctypes.c_ulong,
ctypes.c_longlong, ctypes.c_ulonglong,
]
float_class = [ctypes.c_float, ctypes.c_double]
class Field(object):
def __init__(self, name, ctype):
self.name = name
self.ctype = ctype
def __repr__(self):
return '<field %s: %s>' % (self.name, self.ctype)
def layout_addfield(layout, offset, ctype, prefix):
size = ctypes.sizeof(ctype)
name = prefix
i = 0
while name in layout:
i += 1
name = '%s_%d' % (prefix, i)
field = Field(name, ctype)
for i in range(offset, offset+size):
assert layout[i] is None, "%s overlaps %r" % (fieldname, layout[i])
layout[i] = field
return field
def size_and_sign(ctype):
return (ctypes.sizeof(ctype),
ctype in integer_class and ctype(-1).value > 0)
def fixup_ctype(fieldtype, fieldname, expected_size_and_sign):
for typeclass in [integer_class, float_class]:
if fieldtype in typeclass:
for ctype in typeclass:
if size_and_sign(ctype) == expected_size_and_sign:
return ctype
if (hasattr(fieldtype, '_length_')
and getattr(fieldtype, '_type_', None) == ctypes.c_char):
# for now, assume it is an array of chars; otherwise we'd also
# have to check the exact integer type of the elements of the array
size, sign = expected_size_and_sign
return ctypes.c_char * size
if (hasattr(fieldtype, '_length_')
and getattr(fieldtype, '_type_', None) == ctypes.c_ubyte):
# grumble, fields of type 'c_char array' have automatic cast-to-
# Python-string behavior in ctypes, which may not be what you
# want, so here is the same with c_ubytes instead...
size, sign = expected_size_and_sign
return ctypes.c_ubyte * size
raise TypeError("conflicting field type %r for %r" % (fieldtype,
fieldname))
C_HEADER = """
#include <stdio.h>
#include <stddef.h> /* for offsetof() */
void dump(char* key, int value) {
printf("%s: %d\\n", key, value);
}
"""
def run_example_code(filepath, include_dirs=[]):
executable = build_executable([filepath], include_dirs=include_dirs)
output = py.process.cmdexec(executable)
section = None
for line in output.splitlines():
line = line.strip()
if line.startswith('-+- '): # start of a new section
section = {}
elif line == '---': # section end
assert section is not None
yield section
section = None
elif line:
assert section is not None
key, value = line.split(': ')
section[key] = int(value)
# ____________________________________________________________
def get_python_include_dir():
from distutils import sysconfig
gcv = sysconfig.get_config_vars()
return gcv['INCLUDEPY']
if __name__ == '__main__':
doc = """Example:
ctypes_platform.py -h sys/types.h -h netinet/in.h
'struct sockaddr_in'
sin_port c_int
"""
import sys, getopt
opts, args = getopt.gnu_getopt(sys.argv[1:], 'h:')
if not args:
print >> sys.stderr, doc
else:
assert len(args) % 2 == 1
headers = []
for opt, value in opts:
if opt == '-h':
headers.append('#include <%s>' % (value,))
name = args[0]
fields = []
for i in range(1, len(args), 2):
ctype = getattr(ctypes, args[i+1])
fields.append((args[i], ctype))
S = getstruct(name, '\n'.join(headers), fields)
for key, value in S._fields_:
print key, value
| Python |
#! /usr/bin/env python
"""
Usage: compilemodule.py <module-name>
Compiles the PyPy extension module from pypy/module/<module-name>/
into a regular CPython extension module.
"""
import autopath
import sys
import shutil
import os
from optparse import OptionParser
from pypy.tool.error import debug
def compilemodule(modname, interactive=False, basepath='pypy.module'):
"Compile a PyPy module for CPython."
import pypy.rpython.rctypes.implementation
from pypy.objspace.cpy.objspace import CPyObjSpace
from pypy.objspace.cpy.function import reraise
from pypy.objspace.cpy.ann_policy import CPyAnnotatorPolicy
from pypy.translator.driver import TranslationDriver
from pypy.interpreter.error import OperationError
space = CPyObjSpace()
space.config.translating = True
ModuleClass = __import__(basepath + '.%s' % modname,
None, None, ['Module']).Module
module = ModuleClass(space, space.wrap(modname))
w_moduledict = module.getdict()
def __init__(mod):
print 'in'
w_mod = CPyObjSpace.W_Object(mod)
try:
## space.appexec([w_mod, w_moduledict],
## '''(mod, newdict):
## old = mod.__dict__.copy()
## for key in ['__name__', '__doc__', 'RPythonError']:
## newdict[key] = old[key]
## newdict['__rpython__'] = old
## mod.__dict__.clear()
## mod.__dict__.update(newdict)
## ''')
# the same at interp-level:
w_moddict = space.getattr(w_mod, space.wrap('__dict__'))
w_old = space.call_method(w_moddict, 'copy')
space.call_method(w_moddict, 'clear')
space.setitem(w_moddict, space.wrap('__rpython__'), w_old)
for key in ['__name__', '__doc__', 'RPythonError']:
w_key = space.wrap(key)
try:
w1 = space.getitem(w_old, w_key)
except OperationError:
pass
else:
space.setitem(w_moddict, w_key, w1)
space.call_method(w_moddict, 'update', w_moduledict)
except OperationError, e:
reraise(e)
__init__.allow_someobjects = True
driver = TranslationDriver(extmod_name=modname)
driver.setup(__init__, [object], policy=CPyAnnotatorPolicy(space))
try:
driver.proceed(['compile_c'])
except SystemExit:
raise
except:
if not interactive:
raise
debug(driver)
raise SystemExit(1)
return driver.cbuilder.c_ext_module
def main(argv):
usage = """usage: %prog [options] MODULENAME
Compiles a PyPy extension module
into a regular CPython extension module.
The module is a package with rpython interplevel code,
python applevel code,
and corresponding exports correctly declared."""
parser = OptionParser(usage)
parser.add_option("-p", "--package",
dest="basepath", default="",
metavar="PACKAGE",
help="""package where the module to compile can be found,
default value is pypy/module""")
parser.add_option("-d", "--directory", dest="directory", default="",
help="directory where to copy the resulting module")
(options, argv) = parser.parse_args()
argvCount = len(argv)
if argvCount <> 1:
parser.error('MODULENAME is mandatory.')
if options.directory:
directory = options.directory
if not os.path.exists(directory):
parser.error('Target directory [%s] does not exist.' % directory)
elif not os.path.isdir(directory):
parser.error('Target [%s] is not a directory.' % directory)
if not options.basepath:
c_ext_module = compilemodule(argv[0], interactive=True)
elif options.basepath:
c_ext_module = compilemodule(argv[0], interactive=True, basepath=options.basepath)
print 'Created %r.' % (c_ext_module.__file__,)
if options.directory:
shutil.copy(c_ext_module.__file__, options.directory)
print 'Copied to %r.' % (directory,)
if __name__ == '__main__':
main(sys.argv)
| Python |
#! /usr/bin/env python
import os, py, sys
import ctypes
from pypy.translator.tool.cbuild import build_executable
from pypy.tool.udir import udir
# ____________________________________________________________
#
# Helpers for simple cases
def getstruct(name, c_header_source, interesting_fields):
class CConfig:
_header_ = c_header_source
STRUCT = Struct(name, interesting_fields)
return configure(CConfig)['STRUCT']
def getsimpletype(name, c_header_source, ctype_hint=ctypes.c_int):
class CConfig:
_header_ = c_header_source
TYPE = SimpleType(name, ctype_hint)
return configure(CConfig)['TYPE']
def getconstantinteger(name, c_header_source):
class CConfig:
_header_ = c_header_source
CONST = ConstantInteger(name)
return configure(CConfig)['CONST']
def getdefined(macro, c_header_source):
class CConfig:
_header_ = c_header_source
DEFINED = Defined(macro)
return configure(CConfig)['DEFINED']
# ____________________________________________________________
#
# General interface
class ConfigResult:
def __init__(self, CConfig, info, entries):
self.CConfig = CConfig
self.result = {}
self.info = info
self.entries = entries
def get_entry_result(self, entry):
try:
return self.result[entry]
except KeyError:
pass
name = self.entries[entry]
info = self.info[name]
self.result[entry] = entry.build_result(info, self)
def get_result(self):
return dict([(name, self.result[entry])
for entry, name in self.entries.iteritems()])
def configure(CConfig):
"""Examine the local system by running the C compiler.
The CConfig class contains CConfigEntry attribues that describe
what should be inspected; configure() returns a dict mapping
names to the results.
"""
entries = []
for key in dir(CConfig):
value = getattr(CConfig, key)
if isinstance(value, CConfigEntry):
entries.append((key, value))
filepath = uniquefilepath()
f = filepath.open('w')
print >> f, C_HEADER
print >> f
for path in getattr(CConfig, '_includes_', ()): # optional
print >> f, '#include <%s>' % (path,)
print >> f, getattr(CConfig, '_header_', '') # optional
print >> f
for key, entry in entries:
print >> f, 'void dump_section_%s(void) {' % (key,)
for line in entry.prepare_code():
if line and line[0] != '#':
line = '\t' + line
print >> f, line
print >> f, '}'
print >> f
print >> f, 'int main(void) {'
for key, entry in entries:
print >> f, '\tprintf("-+- %s\\n");' % (key,)
print >> f, '\tdump_section_%s();' % (key,)
print >> f, '\tprintf("---\\n");'
print >> f, '\treturn 0;'
print >> f, '}'
f.close()
include_dirs = getattr(CConfig, '_include_dirs_', [])
infolist = list(run_example_code(filepath, include_dirs))
assert len(infolist) == len(entries)
resultinfo = {}
resultentries = {}
for info, (key, entry) in zip(infolist, entries):
resultinfo[key] = info
resultentries[entry] = key
result = ConfigResult(CConfig, resultinfo, resultentries)
for name, entry in entries:
result.get_entry_result(entry)
return result.get_result()
# ____________________________________________________________
class CConfigEntry(object):
"Abstract base class."
class Struct(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined structure.
"""
def __init__(self, name, interesting_fields, ifdef=None):
self.name = name
self.interesting_fields = interesting_fields
self.ifdef = ifdef
def prepare_code(self):
if self.ifdef is not None:
yield '#ifdef %s' % (self.ifdef,)
yield 'typedef %s ctypesplatcheck_t;' % (self.name,)
yield 'typedef struct {'
yield ' char c;'
yield ' ctypesplatcheck_t s;'
yield '} ctypesplatcheck2_t;'
yield ''
yield 'ctypesplatcheck_t s;'
if self.ifdef is not None:
yield 'dump("defined", 1);'
yield 'dump("align", offsetof(ctypesplatcheck2_t, s));'
yield 'dump("size", sizeof(ctypesplatcheck_t));'
for fieldname, fieldtype in self.interesting_fields:
yield 'dump("fldofs %s", offsetof(ctypesplatcheck_t, %s));'%(
fieldname, fieldname)
yield 'dump("fldsize %s", sizeof(s.%s));' % (
fieldname, fieldname)
if fieldtype in integer_class:
yield 's.%s = 0; s.%s = ~s.%s;' % (fieldname,
fieldname,
fieldname)
yield 'dump("fldunsigned %s", s.%s > 0);' % (fieldname,
fieldname)
if self.ifdef is not None:
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if self.ifdef is not None:
if not info['defined']:
return None
alignment = 1
layout = [None] * info['size']
for fieldname, fieldtype in self.interesting_fields:
if isinstance(fieldtype, Struct):
offset = info['fldofs ' + fieldname]
size = info['fldsize ' + fieldname]
c_fieldtype = config_result.get_entry_result(fieldtype)
layout_addfield(layout, offset, c_fieldtype, fieldname)
alignment = max(alignment, ctype_alignment(c_fieldtype))
else:
offset = info['fldofs ' + fieldname]
size = info['fldsize ' + fieldname]
sign = info.get('fldunsigned ' + fieldname, False)
if (size, sign) != size_and_sign(fieldtype):
fieldtype = fixup_ctype(fieldtype, fieldname, (size, sign))
layout_addfield(layout, offset, fieldtype, fieldname)
alignment = max(alignment, ctype_alignment(fieldtype))
# try to enforce the same alignment as the one of the original
# structure
if alignment < info['align']:
choices = [ctype for ctype in alignment_types
if ctype_alignment(ctype) == info['align']]
assert choices, "unsupported alignment %d" % (info['align'],)
choices = [(ctypes.sizeof(ctype), i, ctype)
for i, ctype in enumerate(choices)]
csize, _, ctype = min(choices)
for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
else:
raise AssertionError("unenforceable alignment %d" % (
info['align'],))
n = 0
for i, cell in enumerate(layout):
if cell is not None:
continue
layout_addfield(layout, i, ctypes.c_char, '_pad%d' % (n,))
n += 1
# build the ctypes Structure
seen = {}
fields = []
for cell in layout:
if cell in seen:
continue
fields.append((cell.name, cell.ctype))
seen[cell] = True
class S(ctypes.Structure):
_fields_ = fields
name = self.name
if name.startswith('struct '):
name = name[7:]
S.__name__ = name
return S
class SimpleType(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined simple numeric type.
"""
def __init__(self, name, ctype_hint=ctypes.c_int, ifdef=None):
self.name = name
self.ctype_hint = ctype_hint
self.ifdef = ifdef
def prepare_code(self):
if self.ifdef is not None:
yield '#ifdef %s' % (self.ifdef,)
yield 'typedef %s ctypesplatcheck_t;' % (self.name,)
yield ''
yield 'ctypesplatcheck_t x;'
if self.ifdef is not None:
yield 'dump("defined", 1);'
yield 'dump("size", sizeof(ctypesplatcheck_t));'
if self.ctype_hint in integer_class:
yield 'x = 0; x = ~x;'
yield 'dump("unsigned", x > 0);'
if self.ifdef is not None:
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if self.ifdef is not None and not info['defined']:
return None
size = info['size']
sign = info.get('unsigned', False)
ctype = self.ctype_hint
if (size, sign) != size_and_sign(ctype):
ctype = fixup_ctype(ctype, self.name, (size, sign))
return ctype
class ConstantInteger(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined integer constant.
"""
def __init__(self, name):
self.name = name
def prepare_code(self):
yield 'if ((%s) < 0) {' % (self.name,)
yield ' long long x = (long long)(%s);' % (self.name,)
yield ' printf("value: %lld\\n", x);'
yield '} else {'
yield ' unsigned long long x = (unsigned long long)(%s);' % (
self.name,)
yield ' printf("value: %llu\\n", x);'
yield '}'
def build_result(self, info, config_result):
return info['value']
class DefinedConstantInteger(CConfigEntry):
"""An entry in a CConfig class that stands for an externally
defined integer constant. If not #defined the value will be None.
"""
def __init__(self, macro):
self.name = self.macro = macro
def prepare_code(self):
yield '#ifdef %s' % self.macro
yield 'dump("defined", 1);'
yield 'if ((%s) < 0) {' % (self.macro,)
yield ' long long x = (long long)(%s);' % (self.macro,)
yield ' printf("value: %lld\\n", x);'
yield '} else {'
yield ' unsigned long long x = (unsigned long long)(%s);' % (
self.macro,)
yield ' printf("value: %llu\\n", x);'
yield '}'
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if info["defined"]:
return info['value']
return None
class DefinedConstantString(CConfigEntry):
"""
"""
def __init__(self, macro):
self.macro = macro
self.name = macro
def prepare_code(self):
yield '#ifdef %s' % self.macro
yield 'int i;'
yield 'char *p = %s;' % self.macro
yield 'dump("defined", 1);'
yield 'for (i = 0; p[i] != 0; i++ ) {'
yield ' printf("value_%d: %d\\n", i, (int)(unsigned char)p[i]);'
yield '}'
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
if info["defined"]:
string = ''
d = 0
while info.has_key('value_%d' % d):
string += chr(info['value_%d' % d])
d += 1
return string
return None
class Defined(CConfigEntry):
"""A boolean, corresponding to an #ifdef.
"""
def __init__(self, macro):
self.macro = macro
self.name = macro
def prepare_code(self):
yield '#ifdef %s' % (self.macro,)
yield 'dump("defined", 1);'
yield '#else'
yield 'dump("defined", 0);'
yield '#endif'
def build_result(self, info, config_result):
return bool(info['defined'])
class Library(CConfigEntry):
"""The loaded CTypes library object.
"""
def __init__(self, name):
self.name = name
def prepare_code(self):
# XXX should check that we can link against the lib
return []
def build_result(self, info, config_result):
from pypy.rpython.rctypes.tool import util
path = util.find_library(self.name)
mylib = ctypes.cdll.LoadLibrary(path)
class _FuncPtr(ctypes._CFuncPtr):
_flags_ = ctypes._FUNCFLAG_CDECL
_restype_ = ctypes.c_int # default, can be overridden in instances
includes = tuple(config_result.CConfig._includes_)
libraries = (self.name,)
mylib._FuncPtr = _FuncPtr
return mylib
# ____________________________________________________________
#
# internal helpers
def ctype_alignment(c_type):
if issubclass(c_type, ctypes.Structure):
return max([ctype_alignment(fld_type)
for fld_name, fld_type in c_type._fields_])
return ctypes.alignment(c_type)
def uniquefilepath(LAST=[0]):
i = LAST[0]
LAST[0] += 1
return udir.join('ctypesplatcheck_%d.c' % i)
alignment_types = [
ctypes.c_short,
ctypes.c_int,
ctypes.c_long,
ctypes.c_float,
ctypes.c_double,
ctypes.c_char_p,
ctypes.c_void_p,
ctypes.c_longlong,
ctypes.c_wchar,
ctypes.c_wchar_p,
]
integer_class = [ctypes.c_byte, ctypes.c_ubyte,
ctypes.c_short, ctypes.c_ushort,
ctypes.c_int, ctypes.c_uint,
ctypes.c_long, ctypes.c_ulong,
ctypes.c_longlong, ctypes.c_ulonglong,
]
float_class = [ctypes.c_float, ctypes.c_double]
class Field(object):
def __init__(self, name, ctype):
self.name = name
self.ctype = ctype
def __repr__(self):
return '<field %s: %s>' % (self.name, self.ctype)
def layout_addfield(layout, offset, ctype, prefix):
size = ctypes.sizeof(ctype)
name = prefix
i = 0
while name in layout:
i += 1
name = '%s_%d' % (prefix, i)
field = Field(name, ctype)
for i in range(offset, offset+size):
assert layout[i] is None, "%s overlaps %r" % (fieldname, layout[i])
layout[i] = field
return field
def size_and_sign(ctype):
return (ctypes.sizeof(ctype),
ctype in integer_class and ctype(-1).value > 0)
def fixup_ctype(fieldtype, fieldname, expected_size_and_sign):
for typeclass in [integer_class, float_class]:
if fieldtype in typeclass:
for ctype in typeclass:
if size_and_sign(ctype) == expected_size_and_sign:
return ctype
if (hasattr(fieldtype, '_length_')
and getattr(fieldtype, '_type_', None) == ctypes.c_char):
# for now, assume it is an array of chars; otherwise we'd also
# have to check the exact integer type of the elements of the array
size, sign = expected_size_and_sign
return ctypes.c_char * size
if (hasattr(fieldtype, '_length_')
and getattr(fieldtype, '_type_', None) == ctypes.c_ubyte):
# grumble, fields of type 'c_char array' have automatic cast-to-
# Python-string behavior in ctypes, which may not be what you
# want, so here is the same with c_ubytes instead...
size, sign = expected_size_and_sign
return ctypes.c_ubyte * size
raise TypeError("conflicting field type %r for %r" % (fieldtype,
fieldname))
C_HEADER = """
#include <stdio.h>
#include <stddef.h> /* for offsetof() */
void dump(char* key, int value) {
printf("%s: %d\\n", key, value);
}
"""
def run_example_code(filepath, include_dirs=[]):
executable = build_executable([filepath], include_dirs=include_dirs)
output = py.process.cmdexec(executable)
section = None
for line in output.splitlines():
line = line.strip()
if line.startswith('-+- '): # start of a new section
section = {}
elif line == '---': # section end
assert section is not None
yield section
section = None
elif line:
assert section is not None
key, value = line.split(': ')
section[key] = int(value)
# ____________________________________________________________
def get_python_include_dir():
from distutils import sysconfig
gcv = sysconfig.get_config_vars()
return gcv['INCLUDEPY']
if __name__ == '__main__':
doc = """Example:
ctypes_platform.py -h sys/types.h -h netinet/in.h
'struct sockaddr_in'
sin_port c_int
"""
import sys, getopt
opts, args = getopt.gnu_getopt(sys.argv[1:], 'h:')
if not args:
print >> sys.stderr, doc
else:
assert len(args) % 2 == 1
headers = []
for opt, value in opts:
if opt == '-h':
headers.append('#include <%s>' % (value,))
name = args[0]
fields = []
for i in range(1, len(args), 2):
ctype = getattr(ctypes, args[i+1])
fields.append((args[i], ctype))
S = getstruct(name, '\n'.join(headers), fields)
for key, value in S._fields_:
print key, value
| Python |
import sys
from ctypes import *
# __________ the standard C library __________
# LoadLibrary is deprecated in ctypes, this should be removed at some point
if "load" in dir(cdll):
cdll_load = cdll.load
else:
cdll_load = cdll.LoadLibrary
if sys.platform == 'win32':
libc = cdll_load('msvcrt.dll')
elif sys.platform in ('linux2', 'freebsd6'):
libc = cdll_load('libc.so.6')
elif sys.platform == 'darwin':
libc = cdll_load('libc.dylib')
else:
raise ImportError("don't know how to load the c lib for %s" % sys.platform)
# ____________________________________________
| Python |
"""
This is the module 'ctypes.util', copied from ctypes 0.9.9.6.
"""
import sys, os
import ctypes
# find_library(name) returns the pathname of a library, or None.
if os.name == "nt":
def find_library(name):
# See MSDN for the REAL search order.
for directory in os.environ['PATH'].split(os.pathsep):
fname = os.path.join(directory, name)
if os.path.exists(fname):
return fname
if fname.lower().endswith(".dll"):
continue
fname = fname + ".dll"
if os.path.exists(fname):
return fname
return None
if os.name == "ce":
# search path according to MSDN:
# - absolute path specified by filename
# - The .exe launch directory
# - the Windows directory
# - ROM dll files (where are they?)
# - OEM specified search path: HKLM\Loader\SystemPath
def find_library(name):
return name
if os.name == "posix" and sys.platform == "darwin":
from ctypes.macholib.dyld import dyld_find as _dyld_find
def find_library(name):
possible = ['lib%s.dylib' % name,
'%s.dylib' % name,
'%s.framework/%s' % (name, name)]
for name in possible:
try:
return _dyld_find(name)
except ValueError:
continue
return None
elif os.name == "posix":
# Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump
import re, tempfile
def _findLib_gcc(name):
expr = '[^\(\)\s]*lib%s\.[^\(\)\s]*' % name
cmd = 'if type gcc &>/dev/null; then CC=gcc; else CC=cc; fi;' \
'$CC -Wl,-t -o /dev/null 2>&1 -l' + name
try:
fdout, outfile = tempfile.mkstemp()
fd = os.popen(cmd)
trace = fd.read()
err = fd.close()
finally:
try:
os.unlink(outfile)
except OSError, e:
if e.errno != errno.ENOENT:
raise
res = re.search(expr, trace)
if not res:
return None
return res.group(0)
def _findLib_ld(name):
expr = '/[^\(\)\s]*lib%s\.[^\(\)\s]*' % name
res = re.search(expr, os.popen('/sbin/ldconfig -p 2>/dev/null').read())
if not res:
# Hm, this works only for libs needed by the python executable.
cmd = 'ldd %s 2>/dev/null' % sys.executable
res = re.search(expr, os.popen(cmd).read())
if not res:
return None
return res.group(0)
def _get_soname(f):
cmd = "objdump -p -j .dynamic 2>/dev/null " + f
res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read())
if not res:
return None
return res.group(1)
def find_library(name):
lib = _findLib_ld(name) or _findLib_gcc(name)
if not lib:
return None
return _get_soname(lib)
if "load" in dir(ctypes.cdll):
load_library = ctypes.cdll.load
else:
load_library = ctypes.cdll.LoadLibrary
################################################################
# test code
def test():
from ctypes import cdll
if os.name == "nt":
print cdll.msvcrt
print cdll.load("msvcrt")
print find_library("msvcrt")
if os.name == "posix":
# find and load_version
print find_library("m")
print find_library("c")
print find_library("bz2")
# getattr
## print cdll.m
## print cdll.bz2
# load
if sys.platform == "darwin":
print cdll.LoadLibrary("libm.dylib")
print cdll.LoadLibrary("libcrypto.dylib")
print cdll.LoadLibrary("libSystem.dylib")
print cdll.LoadLibrary("System.framework/System")
else:
print cdll.LoadLibrary("libm.so")
print cdll.LoadLibrary("libcrypt.so")
print find_library("crypt")
if __name__ == "__main__":
test()
| 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
"""
Usage: compilemodule.py <module-name>
Compiles the PyPy extension module from pypy/module/<module-name>/
into a regular CPython extension module.
"""
import autopath
import sys
import shutil
import os
from optparse import OptionParser
from pypy.tool.error import debug
def compilemodule(modname, interactive=False, basepath='pypy.module'):
"Compile a PyPy module for CPython."
import pypy.rpython.rctypes.implementation
from pypy.objspace.cpy.objspace import CPyObjSpace
from pypy.objspace.cpy.function import reraise
from pypy.objspace.cpy.ann_policy import CPyAnnotatorPolicy
from pypy.translator.driver import TranslationDriver
from pypy.interpreter.error import OperationError
space = CPyObjSpace()
space.config.translating = True
ModuleClass = __import__(basepath + '.%s' % modname,
None, None, ['Module']).Module
module = ModuleClass(space, space.wrap(modname))
w_moduledict = module.getdict()
def __init__(mod):
print 'in'
w_mod = CPyObjSpace.W_Object(mod)
try:
## space.appexec([w_mod, w_moduledict],
## '''(mod, newdict):
## old = mod.__dict__.copy()
## for key in ['__name__', '__doc__', 'RPythonError']:
## newdict[key] = old[key]
## newdict['__rpython__'] = old
## mod.__dict__.clear()
## mod.__dict__.update(newdict)
## ''')
# the same at interp-level:
w_moddict = space.getattr(w_mod, space.wrap('__dict__'))
w_old = space.call_method(w_moddict, 'copy')
space.call_method(w_moddict, 'clear')
space.setitem(w_moddict, space.wrap('__rpython__'), w_old)
for key in ['__name__', '__doc__', 'RPythonError']:
w_key = space.wrap(key)
try:
w1 = space.getitem(w_old, w_key)
except OperationError:
pass
else:
space.setitem(w_moddict, w_key, w1)
space.call_method(w_moddict, 'update', w_moduledict)
except OperationError, e:
reraise(e)
__init__.allow_someobjects = True
driver = TranslationDriver(extmod_name=modname)
driver.setup(__init__, [object], policy=CPyAnnotatorPolicy(space))
try:
driver.proceed(['compile_c'])
except SystemExit:
raise
except:
if not interactive:
raise
debug(driver)
raise SystemExit(1)
return driver.cbuilder.c_ext_module
def main(argv):
usage = """usage: %prog [options] MODULENAME
Compiles a PyPy extension module
into a regular CPython extension module.
The module is a package with rpython interplevel code,
python applevel code,
and corresponding exports correctly declared."""
parser = OptionParser(usage)
parser.add_option("-p", "--package",
dest="basepath", default="",
metavar="PACKAGE",
help="""package where the module to compile can be found,
default value is pypy/module""")
parser.add_option("-d", "--directory", dest="directory", default="",
help="directory where to copy the resulting module")
(options, argv) = parser.parse_args()
argvCount = len(argv)
if argvCount <> 1:
parser.error('MODULENAME is mandatory.')
if options.directory:
directory = options.directory
if not os.path.exists(directory):
parser.error('Target directory [%s] does not exist.' % directory)
elif not os.path.isdir(directory):
parser.error('Target [%s] is not a directory.' % directory)
if not options.basepath:
c_ext_module = compilemodule(argv[0], interactive=True)
elif options.basepath:
c_ext_module = compilemodule(argv[0], interactive=True, basepath=options.basepath)
print 'Created %r.' % (c_ext_module.__file__,)
if options.directory:
shutil.copy(c_ext_module.__file__, options.directory)
print 'Copied to %r.' % (directory,)
if __name__ == '__main__':
main(sys.argv)
| Python |
#empty
| Python |
from pypy.rlib import rarithmetic
from pypy.rpython.lltypesystem import lltype
import ctypes
def c_type_size(c_type):
bits = 0
while c_type(1<<bits).value != 0:
bits += 1
sign = c_type(-1).value < 0
return sign, bits
def setup():
for _name in 'byte short int long longlong'.split():
for name in (_name, 'u' + _name):
c_type = getattr(ctypes, 'c_' + name)
sign, bits = c_type_size(c_type)
inttype = rarithmetic.build_int('rc' + name, sign, bits)
globals()['rc'+name] = inttype
if name[0] == 'u':
llname = 'CU' + name[1:].title()
else:
llname = 'C' + name.title()
globals()[llname] = lltype.build_number(llname, inttype)
setup()
del setup
| Python |
from ctypes import py_object
from pypy.annotation.model import SomeCTypesObject, SomeObject
from pypy.rpython.rctypes.implementation import CTypesCallEntry, CTypesObjEntry
from pypy.rpython.lltypesystem import lltype
from pypy.tool.uid import Hashable
class CallEntry(CTypesCallEntry):
"Annotation and rtyping of calls to py_object."
_about_ = py_object
def specialize_call(self, hop):
from pypy.rpython.robject import pyobj_repr
r_pyobject = hop.r_result
hop.exception_cannot_occur()
v_result = r_pyobject.allocate_instance(hop.llops)
if len(hop.args_s):
[v_input] = hop.inputargs(pyobj_repr)
r_pyobject.setvalue(hop.llops, v_result, v_input)
return v_result
class ObjEntry(CTypesObjEntry):
"Annotation and rtyping of py_object instances."
_type_ = py_object
def get_field_annotation(self, s_pyobject, fieldname):
assert fieldname == "value"
# reading the .value field results in an object of
# completely unknown type. This crashes the annotator if
# it is not in allow_someobjects mode.
return SomeObject()
## def object_seen(self, bookkeeper):
## "Called when the annotator sees this py_object."
## # extension: if the py_object instance has a 'builder' attribute,
## # it must be a pair (callable, args) which is meant to be called
## # at initialization-time when the compiled extension module is
## # first imported. It returns the "real" Python object.
## if hasattr(self.instance, 'builder'):
## # emulate a call so that the callable is properly annotated
## callable, args = self.instance.builder
## s_callable = bookkeeper.immutablevalue(callable)
## args_s = [bookkeeper.immutablevalue(a) for a in args]
## uniquekey = Hashable(self.instance)
## s_res = bookkeeper.emulate_pbc_call(uniquekey, s_callable, args_s)
## assert (issubclass(s_res.knowntype, py_object) or
## isinstance(s_res, SomeImpossibleValue))
def get_repr(self, rtyper, s_pyobject):
from pypy.rpython.rctypes.rpyobject import CTypesPyObjRepr
lowleveltype = lltype.Ptr(lltype.PyObject)
return CTypesPyObjRepr(rtyper, s_pyobject, lowleveltype)
def register_py_object_subclass(subcls):
assert issubclass(subcls, py_object)
CallEntry._register_value(subcls)
ObjEntry._register_type(subcls)
| Python |
from ctypes import ARRAY, c_int, c_char
from pypy.annotation.model import SomeCTypesObject, SomeString
from pypy.rpython.rctypes.implementation import CTypesCallEntry, CTypesObjEntry
from pypy.rpython.lltypesystem import lltype
ArrayType = type(ARRAY(c_int, 10))
class VarSizedArrayType(object):
"""Placeholder for ctypes array types whose size is not an
annotation-time constant.
"""
def __init__(self, itemtype):
self._type_ = itemtype
#self._length_ = unspecified
self.__name__ = itemtype.__name__ + '_Array'
def get_instance_annotation(self, *args_s):
return SomeCTypesObject(self, ownsmemory=True)
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self._type_ == other._type_)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(self._type_)
class CallEntry(CTypesCallEntry):
"Annotation and rtyping of calls to array types."
_type_ = ArrayType
def specialize_call(self, hop):
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import inputconst
r_array = hop.r_result
hop.exception_cannot_occur()
v_result = r_array.allocate_instance(hop.llops)
if hop.nb_args > r_array.length:
raise TyperError("too many arguments for an array of length %d" % (
r_array.length,))
items_v = hop.inputargs(*[r_array.r_item] * hop.nb_args)
r_array.initializeitems(hop.llops, v_result, items_v)
return v_result
class ObjEntry(CTypesObjEntry):
"Annotation and rtyping of array instances."
_metatype_ = ArrayType, VarSizedArrayType
def get_field_annotation(self, s_array, fieldname):
assert fieldname == 'value'
if self.type._type_ != c_char:
raise Exception("only arrays of chars have a .value attribute")
return SomeString() # can_be_None = False
def get_repr(self, rtyper, s_array):
from pypy.rpython.rctypes.rarray import ArrayRepr
return ArrayRepr(rtyper, s_array)
| Python |
from pypy.rpython.rctypes.rmodel import CTypesValueRepr, C_ZERO
from pypy.rpython.rctypes.rstringbuf import StringBufRepr
from pypy.annotation.pairtype import pairtype
from pypy.rpython.rstr import AbstractStringRepr
from pypy.rpython.lltypesystem.rstr import string_repr
from pypy.rpython.rctypes.rchar_p import CCharPRepr
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython.rctypes.rpointer import PointerRepr
from pypy.rpython.rctypes.rarray import ArrayRepr
class CVoidPRepr(CTypesValueRepr):
def convert_const(self, value):
if isinstance(value, self.ctype):
return super(CVoidPRepr, self).convert_const(value)
raise NotImplementedError("XXX constant pointer passed to void* arg")
def rtype_getattr(self, hop):
s_attr = hop.args_s[1]
assert s_attr.is_constant()
assert s_attr.const == 'value'
v_box = hop.inputarg(self, 0)
v_c_adr = self.getvalue(hop.llops, v_box)
hop.exception_cannot_occur()
return hop.genop('cast_adr_to_int', [v_c_adr],
resulttype = lltype.Signed)
class __extend__(pairtype(CCharPRepr, CVoidPRepr),
pairtype(PointerRepr, CVoidPRepr)):
def convert_from_to((r_from, r_to), v, llops):
v_ptr = r_from.getvalue(llops, v)
v_adr = llops.genop('cast_ptr_to_adr', [v_ptr],
resulttype = llmemory.Address)
return r_to.return_value(llops, v_adr)
class __extend__(pairtype(StringBufRepr, CVoidPRepr),
pairtype(ArrayRepr, CVoidPRepr)):
def convert_from_to((r_from, r_to), v, llops):
v_ptr = r_from.get_c_data_of_item(llops, v, C_ZERO)
v_adr = llops.genop('cast_ptr_to_adr', [v_ptr],
resulttype = llmemory.Address)
return r_to.return_value(llops, v_adr)
class __extend__(pairtype(AbstractStringRepr, CVoidPRepr)):
def convert_from_to((r_from, r_to), v, llops):
# warning: no keepalives, only for short-lived conversions like
# in argument passing
# r_from could be char_repr: first convert it to string_repr
v = llops.convertvar(v, r_from, string_repr)
v_adr = llops.gendirectcall(ll_string2addr, v)
return r_to.return_value(llops, v_adr)
def ll_string2addr(s):
if s:
ptr = lltype.direct_arrayitems(s.chars)
return llmemory.cast_ptr_to_adr(ptr)
else:
return llmemory.NULL
| Python |
#empty
| Python |
from pypy.rpython.rtyper import inputconst
from pypy.rpython.rctypes.rmodel import CTypesValueRepr, CTypesRefRepr
from pypy.rpython.rctypes.afunc import CFuncPtrType
from pypy.rpython.error import TyperError
from pypy.rpython.lltypesystem import lltype
from pypy.annotation import model as annmodel
from pypy.annotation.model import SomeCTypesObject
from pypy.objspace.flow.model import Constant
import ctypes
class CFuncPtrRepr(CTypesValueRepr):
def __init__(self, rtyper, s_funcptr):
# For recursive types, getting the args_r and r_result is delayed
# until _setup_repr().
ll_contents = lltype.Ptr(lltype.ForwardReference())
super(CFuncPtrRepr, self).__init__(rtyper, s_funcptr, ll_contents)
self.sample = self.ctype()
self.argtypes = self.sample.argtypes
self.restype = self.sample.restype
if self.argtypes is None:
raise TyperError("cannot handle yet function pointers with "
"unspecified argument types")
def _setup_repr(self):
# Find the repr and low-level type of the arguments and return value
rtyper = self.rtyper
args_r = []
for arg_ctype in self.argtypes:
r = rtyper.getrepr(SomeCTypesObject(arg_ctype,
ownsmemory=False))
args_r.append(r)
if self.restype is not None:
r_result = rtyper.getrepr(SomeCTypesObject(self.restype,
ownsmemory=True))
else:
r_result = None
if isinstance(self.ll_type.TO, lltype.ForwardReference):
FUNCTYPE = get_funcptr_type(args_r, r_result)
self.ll_type.TO.become(FUNCTYPE)
self.args_r = args_r
self.r_result = r_result
def ctypecheck(self, value):
return (isinstance(value.__class__, CFuncPtrType) and
list(value.argtypes) == list(self.argtypes) and
value.restype == self.restype)
def initialize_const(self, p, cfuncptr):
if not cfuncptr: # passed as arg to functions expecting func pointers
return
c, args_r, r_res = get_funcptr_constant(self.rtyper, cfuncptr, None)
p.c_data[0] = c.value
def rtype_simple_call(self, hop):
v_box = hop.inputarg(self, arg=0)
v_funcptr = self.getvalue(hop.llops, v_box)
hop2 = hop.copy()
hop2.r_s_popfirstarg()
return rtype_funcptr_call(hop2, v_funcptr, self.args_r, self.r_result)
# ____________________________________________________________
def get_funcptr_constant(rtyper, cfuncptr, args_s):
"""Get a Constant ll function pointer from a ctypes function object.
"""
fnname = cfuncptr.__name__
args_r, r_res = get_arg_res_repr(rtyper, cfuncptr, args_s)
FUNCTYPE = get_funcptr_type(args_r, r_res)
flags = get_funcptr_flags(cfuncptr)
f = lltype.functionptr(FUNCTYPE, fnname, **flags)
return inputconst(lltype.typeOf(f), f), args_r, r_res
def get_arg_res_repr(rtyper, cfuncptr, args_s):
"""Get the reprs to use for the arguments and the return value of a
ctypes function call. The args_s annotations are used to guess the
argument types if they are not specified by cfuncptr.argtypes.
"""
def repr_for_ctype(ctype):
s = SomeCTypesObject(ctype, ownsmemory=False)
r = rtyper.getrepr(s)
return r
args_r = []
if getattr(cfuncptr, 'argtypes', None) is not None:
for ctype in cfuncptr.argtypes:
args_r.append(repr_for_ctype(ctype))
else:
# unspecified argtypes: use ctypes rules for arguments,
# accepting integers, strings, or None
for s_arg in args_s:
if isinstance(s_arg, SomeCTypesObject):
r_arg = rtyper.getrepr(s_arg)
elif isinstance(s_arg, annmodel.SomeInteger):
r_arg = repr_for_ctype(ctypes.c_long)
elif (isinstance(s_arg, annmodel.SomeString)
or s_arg == annmodel.s_None):
r_arg = repr_for_ctype(ctypes.c_char_p)
else:
raise TyperError("call with no argtypes: don't know "
"how to convert argument %r" % (s_arg,))
args_r.append(r_arg)
if cfuncptr.restype is not None:
s_res = SomeCTypesObject(cfuncptr.restype, ownsmemory=True)
r_res = rtyper.getrepr(s_res)
else:
r_res = None
return args_r, r_res
def get_funcptr_type(args_r, r_res):
"""Get the lltype FUNCTYPE to use for a ctypes function call.
"""
ARGTYPES = []
for r_arg in args_r:
if isinstance(r_arg, CTypesValueRepr):
# ValueRepr case
ARGTYPES.append(r_arg.ll_type)
else:
# RefRepr case -- i.e. the function argument that we pass by
# value is e.g. a complete struct
ARGTYPES.append(r_arg.c_data_type)
if r_res is not None:
RESTYPE = r_res.ll_type
else:
RESTYPE = lltype.Void
return lltype.FuncType(ARGTYPES, RESTYPE)
def get_funcptr_flags(cfuncptr):
"""Get the fnptr flags to use for the given concrete ctypes function.
"""
kwds = {'external': 'C'}
if hasattr(cfuncptr, 'llinterp_friendly_version'):
kwds['_callable'] = cfuncptr.llinterp_friendly_version
suppress_pyerr_occurred = False
if (cfuncptr._flags_ & ctypes._FUNCFLAG_PYTHONAPI) == 0:
suppress_pyerr_occurred = True
if hasattr(cfuncptr, '_rctypes_pyerrchecker_'):
suppress_pyerr_occurred = True
if suppress_pyerr_occurred:
kwds['includes'] = getattr(cfuncptr, 'includes', ())
kwds['libraries'] = getattr(cfuncptr, 'libraries', ())
#else:
# no 'includes': hack to trigger in GenC a PyErr_Occurred() check
return kwds
def rtype_funcptr_call(hop, v_funcptr, args_r, r_res, pyerrchecker=None):
"""Generate a call to the given ll function pointer.
"""
hop.rtyper.call_all_setups()
vlist = hop.inputargs(*args_r)
unwrapped_args_v = []
for r_arg, v in zip(args_r, vlist):
if isinstance(r_arg, CTypesValueRepr):
# ValueRepr case
unwrapped_args_v.append(r_arg.getvalue(hop.llops, v))
elif isinstance(r_arg, CTypesRefRepr):
# RefRepr case -- i.e. the function argument that we pass by
# value is e.g. a complete struct; we pass a pointer to it
# in the low-level graphs and it's up to the back-end to
# generate the correct dereferencing
unwrapped_args_v.append(r_arg.get_c_data(hop.llops, v))
else:
assert 0, "ctypes func call got a non-ctypes arg repr"
FUNCTYPE = v_funcptr.concretetype.TO
hop.exception_cannot_occur()
if isinstance(v_funcptr, Constant):
opname = 'direct_call'
else:
unwrapped_args_v.append(inputconst(lltype.Void, None))
opname = 'indirect_call'
v_result = hop.genop(opname, [v_funcptr]+unwrapped_args_v,
resulttype = FUNCTYPE.RESULT)
if pyerrchecker is not None:
# special extension to support the CPyObjSpace
# XXX hackish: someone else -- like the annotator policy --
# must ensure that this extra function has been annotated
from pypy.translator.translator import graphof
graph = graphof(hop.rtyper.annotator.translator, pyerrchecker)
hop.llops.record_extra_call(graph)
# build the 'direct_call' operation
f = hop.rtyper.getcallable(graph)
c = hop.inputconst(lltype.typeOf(f), f)
hop.genop('direct_call', [c])
if r_res is not None:
v_result = r_res.return_value(hop.llops, v_result)
return v_result
| Python |
# Base classes describing annotation and rtyping
from pypy.annotation.model import SomeCTypesObject
from pypy.rpython import extregistry
from pypy.rpython.extregistry import ExtRegistryEntry
import ctypes
if ctypes.__version__ < '0.9.9.6': # string comparison... good enough?
raise ImportError("requires ctypes >= 0.9.9.6, got %s" % (
ctypes.__version__,))
# rctypes version of ctypes.CFUNCTYPE.
# It's required to work around three limitations of CFUNCTYPE:
#
# * There is no PY_ version to make callbacks for CPython, which
# expects the callback to follow the usual conventions (NULL = error).
#
# * The wrapped callback is not exposed in any special attribute, so
# if rctypes sees a CFunctionType object it can't find the Python callback
#
# * I would expect a return type of py_object to mean that if the
# callback Python function returns a py_object, the C caller sees the
# PyObject* inside. Wrong: it sees the py_object wrapper itself. For
# consistency -- and also because unwrapping the py_object manually is
# not allowed annotation-wise -- we change the semantics here under
# the nose of the annotator.
##_c_callback_functype_cache = {}
##def CALLBACK_FUNCTYPE(restype, *argtypes, **flags):
## if 'callconv' in flags:
## callconv = flags.pop('callconv')
## else:
## callconv = ctypes.CDLL
## assert not flags, "unknown keyword arguments %r" % (flags.keys(),)
## try:
## return _c_callback_functype_cache[(restype, argtypes)]
## except KeyError:
## class CallbackFunctionType(ctypes._CFuncPtr):
## _argtypes_ = argtypes
## _restype_ = restype
## _flags_ = callconv._FuncPtr._flags_
## def __new__(cls, callback):
## assert callable(callback)
## if issubclass(restype, ctypes.py_object):
## def func(*args, **kwds):
## w_res = callback(*args, **kwds)
## assert isinstance(w_res, py_object)
## return w_res.value
## else:
## func = callback
## res = super(CallbackFunctionType, cls).__new__(cls, func)
## res.callback = callback
## return res
## _c_callback_functype_cache[(restype, argtypes)] = CallbackFunctionType
## return CallbackFunctionType
# ____________________________________________________________
class CTypesEntry(ExtRegistryEntry):
pass
## def compute_annotation(self):
## self.ctype_object_discovered()
## return super(CTypesEntry, self).compute_annotation()
## def ctype_object_discovered(self):
## if self.instance is None:
## return
## from pypy.annotation.bookkeeper import getbookkeeper
## bookkeeper = getbookkeeper()
## if bookkeeper is None:
## return
## # follow all dependent ctypes objects in order to discover
## # all callback functions
## memo = {}
## def recfind(o):
## if id(o) in memo:
## return
## memo[id(o)] = o
## if isinstance(o, dict):
## for x in o.itervalues():
## recfind(x)
## elif isinstance(o, (list, tuple)):
## for x in o:
## recfind(x)
## elif extregistry.is_registered(o):
## entry = extregistry.lookup(o)
## if isinstance(entry, CTypesEntry):
## entry.object_seen(bookkeeper)
## recfind(o._objects)
## recfind(o.__dict__) # for extra keepalives
## recfind(self.instance)
## def object_seen(self, bookkeeper):
## """To be overriden for ctypes objects whose mere presence influences
## annotation, e.g. callback functions."""
class CTypesCallEntry(CTypesEntry):
"Annotation and rtyping of ctypes types (mostly their calls)."
def compute_annotation(self):
ctype = self.instance
assert ctype is not None
analyser = self.compute_result_annotation
methodname = ctype.__name__
return SomeCTypesType(analyser, methodname=methodname)
def compute_result_annotation(self, *args_s, **kwds_s):
ctype = self.instance # the ctype is the called object
return SomeCTypesObject(ctype, ownsmemory=True)
class CTypesObjEntry(CTypesEntry):
"Annotation and rtyping of ctypes instances."
def compute_annotation(self):
#self.ctype_object_discovered()
ctype = self.type
return SomeCTypesObject(ctype, ownsmemory=True)
# Importing for side effect of registering types with extregistry
from pypy.rpython.rctypes.atype import SomeCTypesType
import pypy.rpython.rctypes.aprimitive
import pypy.rpython.rctypes.apointer
import pypy.rpython.rctypes.aarray
import pypy.rpython.rctypes.afunc
import pypy.rpython.rctypes.achar_p
import pypy.rpython.rctypes.astruct
import pypy.rpython.rctypes.avoid_p
import pypy.rpython.rctypes.astringbuf
import pypy.rpython.rctypes.apyobject
| Python |
"""
Var-sized arrays, i.e. arrays whose size is not known at annotation-time.
"""
from pypy.annotation.model import SomeCTypesObject
from pypy.annotation.model import SomeBuiltin, SomeInteger, SomeString
from pypy.annotation.pairtype import pair, pairtype
from pypy.rpython.extregistry import ExtRegistryEntry
class SomeCTypesType(SomeBuiltin):
"""A ctypes type behaves like a built-in function, because it can only
be called -- with the exception of 'ctype*int' to build array types.
"""
def rtyper_makerepr(self, rtyper):
from pypy.rpython.rctypes.rtype import TypeRepr
return TypeRepr(self)
def rtyper_makekey(self):
return SomeCTypesType, getattr(self, 'const', None)
class SomeVarSizedCTypesType(SomeBuiltin):
"""A ctypes built at runtime as 'ctype*int'.
Note that at the moment 'ctype*int*int' is not supported.
"""
def __init__(self, ctype_item):
from pypy.rpython.rctypes.aarray import VarSizedArrayType
ctype_array = VarSizedArrayType(ctype_item)
SomeBuiltin.__init__(self, ctype_array.get_instance_annotation)
self.ctype_array = ctype_array
def rtyper_makerepr(self, rtyper):
assert self.s_self is None
from pypy.rpython.rctypes.rtype import VarSizedTypeRepr
return VarSizedTypeRepr()
def rtyper_makekey(self):
return SomeVarSizedCTypesType, self.ctype_array
class __extend__(pairtype(SomeCTypesType, SomeInteger)):
def mul((s_ctt, s_int)):
entry = s_ctt.analyser.im_self # fish fish
ctype_item = entry.instance
return SomeVarSizedCTypesType(ctype_item)
mul.can_only_throw = []
| Python |
import py
class Directory(py.test.collect.Directory):
def run(self):
try:
import ctypes
except ImportError:
py.test.skip("these tests need ctypes installed")
return super(Directory, self).run()
| Python |
from pypy.annotation.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.rpython.lltypesystem.lltype import Signed, Unsigned, Bool, Float
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import IntegerRepr, BoolRepr
from pypy.rpython.robject import PyObjRepr, pyobj_repr
from pypy.rpython.rmodel import log
class __extend__(annmodel.SomeBool):
def rtyper_makerepr(self, rtyper):
return bool_repr
def rtyper_makekey(self):
return self.__class__,
bool_repr = BoolRepr()
class __extend__(BoolRepr):
def convert_const(self, value):
if not isinstance(value, bool):
raise TyperError("not a bool: %r" % (value,))
return value
def rtype_is_true(_, hop):
vlist = hop.inputargs(Bool)
return vlist[0]
def rtype_int(_, hop):
vlist = hop.inputargs(Signed)
return vlist[0]
def rtype_float(_, hop):
vlist = hop.inputargs(Float)
return vlist[0]
#
# _________________________ Conversions _________________________
class __extend__(pairtype(BoolRepr, IntegerRepr)):
def convert_from_to((r_from, r_to), v, llops):
if r_from.lowleveltype == Bool and r_to.lowleveltype == Unsigned:
log.debug('explicit cast_bool_to_uint')
return llops.genop('cast_bool_to_uint', [v], resulttype=Unsigned)
if r_from.lowleveltype == Bool and r_to.lowleveltype == Signed:
return llops.genop('cast_bool_to_int', [v], resulttype=Signed)
if r_from.lowleveltype == Bool:
from pypy.rpython.rint import signed_repr
v_int = llops.genop('cast_bool_to_int', [v], resulttype=Signed)
return llops.convertvar(v_int, signed_repr, r_to)
return NotImplemented
class __extend__(pairtype(IntegerRepr, BoolRepr)):
def convert_from_to((r_from, r_to), v, llops):
if r_from.lowleveltype == Unsigned and r_to.lowleveltype == Bool:
log.debug('explicit cast_uint_to_bool')
return llops.genop('uint_is_true', [v], resulttype=Bool)
if r_from.lowleveltype == Signed and r_to.lowleveltype == Bool:
log.debug('explicit cast_int_to_bool')
return llops.genop('int_is_true', [v], resulttype=Bool)
return NotImplemented
class __extend__(pairtype(PyObjRepr, BoolRepr)):
def convert_from_to((r_from, r_to), v, llops):
if r_to.lowleveltype == Bool:
# xxx put in table
return llops.gencapicall('PyObject_IsTrue', [v], resulttype=Bool,
_callable=lambda pyo: bool(pyo._obj.value))
return NotImplemented
class __extend__(pairtype(BoolRepr, PyObjRepr)):
def convert_from_to((r_from, r_to), v, llops):
if r_from.lowleveltype == Bool:
return llops.gencapicall('PyBool_FromLong', [v],
resulttype = pyobj_repr)
return NotImplemented
| Python |
from pypy.annotation.pairtype import pairtype, extendabletype, pair
from pypy.annotation import model as annmodel
from pypy.annotation import description
from pypy.objspace.flow.model import Constant
from pypy.rpython.lltypesystem.lltype import \
Void, Bool, Float, Signed, Char, UniChar, \
typeOf, LowLevelType, Ptr, PyObject, isCompatibleType
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.error import TyperError, MissingRTypeOperation
# initialization states for Repr instances
class setupstate:
NOTINITIALIZED = 0
INPROGRESS = 1
BROKEN = 2
FINISHED = 3
DELAYED = 4
class Repr:
""" An instance of Repr is associated with each instance of SomeXxx.
It defines the chosen representation for the SomeXxx. The Repr subclasses
generally follows the SomeXxx subclass hierarchy, but there are numerous
exceptions. For example, the annotator uses SomeIter for any iterator, but
we need different representations according to the type of container we are
iterating over.
"""
__metaclass__ = extendabletype
_initialized = setupstate.NOTINITIALIZED
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.lowleveltype)
def compact_repr(self):
return '%s %s' % (self.__class__.__name__.replace('Repr','R'), self.lowleveltype._short_name())
def setup(self):
""" call _setup_repr() and keep track of the initializiation
status to e.g. detect recursive _setup_repr invocations.
the '_initialized' attr has four states:
"""
if self._initialized == setupstate.FINISHED:
return
elif self._initialized == setupstate.BROKEN:
raise BrokenReprTyperError(
"cannot setup already failed Repr: %r" %(self,))
elif self._initialized == setupstate.INPROGRESS:
raise AssertionError(
"recursive invocation of Repr setup(): %r" %(self,))
elif self._initialized == setupstate.DELAYED:
raise AssertionError(
"Repr setup() is delayed and cannot be called yet: %r" %(self,))
assert self._initialized == setupstate.NOTINITIALIZED
self._initialized = setupstate.INPROGRESS
try:
self._setup_repr()
except TyperError, e:
self._initialized = setupstate.BROKEN
raise
else:
self._initialized = setupstate.FINISHED
def _setup_repr(self):
"For recursive data structure, which must be initialized in two steps."
def setup_final(self):
"""Same as setup(), called a bit later, for effects that are only
needed after the typer finished (as opposed to needed for other parts
of the typer itself)."""
if self._initialized == setupstate.BROKEN:
raise BrokenReprTyperError("cannot perform setup_final_touch "
"on failed Repr: %r" %(self,))
assert self._initialized == setupstate.FINISHED, (
"setup_final() on repr with state %s: %r" %
(self._initialized, self))
self._setup_repr_final()
def _setup_repr_final(self):
pass
def is_setup_delayed(self):
return self._initialized == setupstate.DELAYED
def set_setup_delayed(self, flag):
assert self._initialized in (setupstate.NOTINITIALIZED,
setupstate.DELAYED)
if flag:
self._initialized = setupstate.DELAYED
else:
self._initialized = setupstate.NOTINITIALIZED
def set_setup_maybe_delayed(self):
if self._initialized == setupstate.NOTINITIALIZED:
self._initialized = setupstate.DELAYED
return self._initialized == setupstate.DELAYED
def __getattr__(self, name):
# Assume that when an attribute is missing, it's because setup() needs
# to be called
if not (name[:2] == '__' == name[-2:]):
if self._initialized == setupstate.NOTINITIALIZED:
self.setup()
try:
return self.__dict__[name]
except KeyError:
pass
raise AttributeError("%s instance has no attribute %s" % (
self.__class__.__name__, name))
def _freeze_(self):
return True
def convert_desc_or_const(self, desc_or_const):
if isinstance(desc_or_const, description.Desc):
return self.convert_desc(desc_or_const)
elif isinstance(desc_or_const, Constant):
return self.convert_const(desc_or_const.value)
else:
raise TyperError("convert_desc_or_const expects a Desc"
"or Constant: %r" % desc_or_const)
def convert_const(self, value):
"Convert the given constant value to the low-level repr of 'self'."
if self.lowleveltype is not Void:
try:
realtype = typeOf(value)
except (AssertionError, AttributeError, TypeError):
realtype = '???'
if realtype != self.lowleveltype:
raise TyperError("convert_const(self = %r, value = %r)" % (
self, value))
return value
def get_ll_eq_function(self):
"""Return an eq(x,y) function to use to compare two low-level
values of this Repr.
This can return None to mean that simply using '==' is fine.
"""
raise TyperError, 'no equality function for %r' % self
def get_ll_hash_function(self):
"""Return a hash(x) function for low-level values of this Repr.
"""
raise TyperError, 'no hashing function for %r' % self
def get_ll_fasthash_function(self):
"""Return a 'fast' hash(x) function for low-level values of this
Repr. The function can assume that 'x' is already stored as a
key in a dict. get_ll_fasthash_function() should return None if
the hash should rather be cached in the dict entry.
"""
return None
def can_ll_be_null(self, s_value):
"""Check if the low-level repr can take the value 0/NULL.
The annotation s_value is provided as a hint because it may
contain more information than the Repr.
"""
return True # conservative
def get_ll_dummyval_obj(self, rtyper, s_value):
"""A dummy value is a special low-level value, not otherwise
used. It should not be the NULL value even if it is special.
This returns either None, or a hashable object that has a
(possibly lazy) attribute 'll_dummy_value'.
The annotation s_value is provided as a hint because it may
contain more information than the Repr.
"""
T = self.lowleveltype
if (isinstance(T, lltype.Ptr) and
isinstance(T.TO, (lltype.Struct,
lltype.Array,
lltype.ForwardReference)) and
T.TO._gckind != 'cpy'):
return DummyValueBuilder(rtyper, T.TO)
else:
return None
def rtype_bltn_list(self, hop):
raise TyperError, 'no list() support for %r' % self
def rtype_unichr(self, hop):
raise TyperError, 'no unichr() support for %r' % self
# default implementation of some operations
def rtype_getattr(self, hop):
s_attr = hop.args_s[1]
if s_attr.is_constant() and isinstance(s_attr.const, str):
attr = s_attr.const
s_obj = hop.args_s[0]
if s_obj.find_method(attr) is None:
raise TyperError("no method %s on %r" % (attr, s_obj))
else:
# implement methods (of a known name) as just their 'self'
return hop.inputarg(self, arg=0)
else:
raise TyperError("getattr() with a non-constant attribute name")
def rtype_str(self, hop):
[v_self] = hop.inputargs(self)
return hop.gendirectcall(self.ll_str, v_self)
def rtype_nonzero(self, hop):
return self.rtype_is_true(hop) # can call a subclass' rtype_is_true()
def rtype_is_true(self, hop):
try:
vlen = self.rtype_len(hop)
except MissingRTypeOperation:
if not hop.s_result.is_constant():
raise TyperError("rtype_is_true(%r) not implemented" % (self,))
return hop.inputconst(Bool, hop.s_result.const)
else:
return hop.genop('int_is_true', [vlen], resulttype=Bool)
def rtype_id(self, hop):
if not isinstance(self.lowleveltype, Ptr):
raise TyperError('id() of an instance of the non-pointer %r' % (
self,))
vobj, = hop.inputargs(self)
# XXX why did this go through weakadr??
#v_waddr = hop.genop('cast_ptr_to_weakadr', [vobj],
# resulttype=llmemory.WeakGcAddress)
#return hop.genop('cast_weakadr_to_int', [v_waddr], resulttype=Signed)
return hop.genop('cast_ptr_to_int', [vobj], resulttype=Signed)
def rtype_hash(self, hop):
ll_hash = self.get_ll_hash_function()
v, = hop.inputargs(self)
return hop.gendirectcall(ll_hash, v)
def rtype_iter(self, hop):
r_iter = self.make_iterator_repr()
return r_iter.newiter(hop)
def make_iterator_repr(self, *variant):
raise TyperError("%s is not iterable" % (self,))
def rtype_hint(self, hop):
return hop.inputarg(hop.r_result, arg=0)
# hlinvoke helpers
def get_r_implfunc(self):
raise TyperError("%s has no corresponding implementation function representation" % (self,))
def get_s_callable(self):
raise TyperError("%s is not callable or cannot reconstruct a pbc annotation for itself" % (self,))
def ll_hash_void(v):
return 0
class CanBeNull(object):
"""A mix-in base class for subclasses of Repr that represent None as
'null' and true values as non-'null'.
"""
def rtype_is_true(self, hop):
if hop.s_result.is_constant():
return hop.inputconst(Bool, hop.s_result.const)
else:
return hop.rtyper.type_system.check_null(self, hop)
class IteratorRepr(Repr):
"""Base class of Reprs of any kind of iterator."""
def rtype_iter(self, hop): # iter(iter(x)) <==> iter(x)
v_iter, = hop.inputargs(self)
return v_iter
def rtype_method_next(self, hop):
return self.rtype_next(hop)
class __extend__(annmodel.SomeIterator):
# NOTE: SomeIterator is for iterators over any container, not just list
def rtyper_makerepr(self, rtyper):
r_container = rtyper.getrepr(self.s_container)
return r_container.make_iterator_repr(*self.variant)
def rtyper_makekey_ex(self, rtyper):
return self.__class__, rtyper.makekey(self.s_container), self.variant
class __extend__(annmodel.SomeImpossibleValue):
def rtyper_makerepr(self, rtyper):
return impossible_repr
def rtyper_makekey(self):
return self.__class__,
# ____ generic binary operations _____________________________
class __extend__(pairtype(Repr, Repr)):
def rtype_is_((robj1, robj2), hop):
if hop.s_result.is_constant():
return inputconst(Bool, hop.s_result.const)
return hop.rtyper.type_system.generic_is(robj1, robj2, hop)
# default implementation for checked getitems
def rtype_getitem_idx_key((r_c1, r_o1), hop):
return pair(r_c1, r_o1).rtype_getitem(hop)
rtype_getitem_idx = rtype_getitem_idx_key
rtype_getitem_key = rtype_getitem_idx_key
# ____________________________________________________________
def make_missing_op(rcls, opname):
attr = 'rtype_' + opname
if not hasattr(rcls, attr):
def missing_rtype_operation(self, hop):
raise MissingRTypeOperation("unimplemented operation: "
"'%s' on %r" % (opname, self))
setattr(rcls, attr, missing_rtype_operation)
for opname in annmodel.UNARY_OPERATIONS:
make_missing_op(Repr, opname)
for opname in annmodel.BINARY_OPERATIONS:
make_missing_op(pairtype(Repr, Repr), opname)
# not in BINARY_OPERATIONS
make_missing_op(pairtype(Repr, Repr), 'contains')
class __extend__(pairtype(Repr, Repr)):
def convert_from_to((r_from, r_to), v, llops):
return NotImplemented
# ____________________________________________________________
# Primitive Repr classes, in the same hierarchical order as
# the corresponding SomeObjects
class FloatRepr(Repr):
lowleveltype = Float
class IntegerRepr(FloatRepr):
def __init__(self, lowleveltype, opprefix):
self.lowleveltype = lowleveltype
self._opprefix = opprefix
self.as_int = self
def _get_opprefix(self):
if self._opprefix is None:
raise TyperError("arithmetic not supported on %r" %
self.lowleveltype)
return self._opprefix
opprefix =property(_get_opprefix)
class BoolRepr(IntegerRepr):
lowleveltype = Bool
# NB. no 'opprefix' here. Use 'as_int' systematically.
def __init__(self):
from pypy.rpython.rint import signed_repr
self.as_int = signed_repr
class VoidRepr(Repr):
lowleveltype = Void
def get_ll_eq_function(self): return None
def get_ll_hash_function(self): return ll_hash_void
get_ll_fasthash_function = get_ll_hash_function
def ll_str(self, nothing): raise AssertionError("unreachable code")
impossible_repr = VoidRepr()
class SimplePointerRepr(Repr):
"Convenience Repr for simple ll pointer types with no operation on them."
def __init__(self, lowleveltype):
self.lowleveltype = lowleveltype
def convert_const(self, value):
if value is not None:
raise TyperError("%r only supports None as prebuilt constant, "
"got %r" % (self, value))
return lltype.nullptr(self.lowleveltype.TO)
# ____________________________________________________________
def inputdesc(reqtype, desc):
"""Return a Constant for the given desc, of the requested type,
which can only be a Repr.
"""
assert isinstance(reqtype, Repr)
value = reqtype.convert_desc(desc)
lltype = reqtype.lowleveltype
c = Constant(value)
c.concretetype = lltype
return c
def inputconst(reqtype, value):
"""Return a Constant with the given value, of the requested type,
which can be a Repr instance or a low-level type.
"""
if isinstance(reqtype, Repr):
value = reqtype.convert_const(value)
lltype = reqtype.lowleveltype
elif isinstance(reqtype, LowLevelType):
lltype = reqtype
else:
raise TypeError(repr(reqtype))
# Void Constants can hold any value;
# non-Void Constants must hold a correctly ll-typed value
if lltype is not Void:
try:
realtype = typeOf(value)
except (AssertionError, AttributeError):
realtype = '???'
if not isCompatibleType(realtype, lltype):
raise TyperError("inputconst(reqtype = %s, value = %s):\n"
"expected a %r,\n"
" got a %r" % (reqtype, value,
lltype, realtype))
c = Constant(value)
c.concretetype = lltype
return c
class BrokenReprTyperError(TyperError):
""" raised when trying to setup a Repr whose setup
has failed already.
"""
def mangle(prefix, name):
"""Make a unique identifier from the prefix and the name. The name
is allowed to start with $."""
if name.startswith('$'):
return '%sinternal_%s' % (prefix, name[1:])
else:
return '%s_%s' % (prefix, name)
class HalfConcreteWrapper:
# see rtyper.gendirectcall()
def __init__(self, callback):
self.concretize = callback # should produce a concrete const
def _freeze_(self):
return True
# __________ utilities __________
PyObjPtr = Ptr(PyObject)
def getgcflavor(classdef):
for parentdef in classdef.getmro():
if hasattr(parentdef, '_cpy_exported_type_'):
return 'cpy'
classdesc = classdef.classdesc
alloc_flavor = classdesc.read_attribute('_alloc_flavor_',
Constant('gc')).value
return alloc_flavor
def externalvsinternal(rtyper, item_repr): # -> external_item_repr, (internal_)item_repr
from pypy.rpython import rclass
if (isinstance(item_repr, rclass.AbstractInstanceRepr) and
getattr(item_repr, 'gcflavor', 'gc') == 'gc'):
return item_repr, rclass.getinstancerepr(rtyper, None)
else:
return item_repr, item_repr
class DummyValueBuilder(object):
def __init__(self, rtyper, TYPE):
self.rtyper = rtyper
self.TYPE = TYPE
def _freeze_(self):
return True
def __hash__(self):
return hash(self.TYPE)
def __eq__(self, other):
return (isinstance(other, DummyValueBuilder) and
self.rtyper is other.rtyper and
self.TYPE == other.TYPE)
def __ne__(self, other):
return not (self == other)
def build_ll_dummy_value(self):
TYPE = self.TYPE
try:
return self.rtyper.cache_dummy_values[TYPE]
except KeyError:
# generate a dummy ptr to an immortal placeholder struct/array
if TYPE._is_varsize():
p = lltype.malloc(TYPE, 0, immortal=True)
else:
p = lltype.malloc(TYPE, immortal=True)
self.rtyper.cache_dummy_values[TYPE] = p
return p
ll_dummy_value = property(build_ll_dummy_value)
# logging/warning
import py
from pypy.tool.ansi_print import ansi_log
log = py.log.Producer("rtyper")
py.log.setconsumer("rtyper", ansi_log)
py.log.setconsumer("rtyper translating", None)
py.log.setconsumer("rtyper debug", None)
def warning(msg):
log.WARNING(msg)
| Python |
"""
The code needed to flow and annotate low-level helpers -- the ll_*() functions
"""
import types
from pypy.tool.sourcetools import valid_identifier
from pypy.annotation import model as annmodel
from pypy.annotation.policy import AnnotatorPolicy, Sig
from pypy.rpython.lltypesystem import lltype
from pypy.rpython import extfunctable, extregistry
from pypy.objspace.flow.model import Constant
class KeyComp(object):
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.__class__ == other.__class__ and self.val == other.val
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(self.val)
def __str__(self):
val = self.val
if isinstance(val, lltype.LowLevelType):
return val._short_name() + 'LlT'
s = getattr(val, '__name__', None)
if s is None:
compact = getattr(val, 'compact_repr', None)
if compact is None:
s = repr(val)
else:
s = compact()
return s + 'Const'
class LowLevelAnnotatorPolicy(AnnotatorPolicy):
allow_someobjects = False
def __init__(pol, rtyper=None):
pol.rtyper = rtyper
def default_specialize(funcdesc, args_s):
key = []
new_args_s = []
for s_obj in args_s:
if isinstance(s_obj, annmodel.SomePBC):
assert s_obj.is_constant(), "ambiguous low-level helper specialization"
key.append(KeyComp(s_obj.const))
new_args_s.append(s_obj)
else:
new_args_s.append(annmodel.not_const(s_obj))
try:
key.append(annmodel.annotation_to_lltype(s_obj))
except ValueError:
# passing non-low-level types to a ll_* function is allowed
# for module/ll_*
key.append(s_obj.__class__)
flowgraph = funcdesc.cachedgraph(tuple(key))
args_s[:] = new_args_s
return flowgraph
default_specialize = staticmethod(default_specialize)
def override__init_opaque_object(pol, s_opaqueptr, s_value):
assert isinstance(s_opaqueptr, annmodel.SomePtr)
assert isinstance(s_opaqueptr.ll_ptrtype.TO, lltype.OpaqueType)
assert isinstance(s_value, annmodel.SomeExternalObject)
exttypeinfo = extfunctable.typetable[s_value.knowntype]
assert s_opaqueptr.ll_ptrtype.TO._exttypeinfo == exttypeinfo
return annmodel.SomeExternalObject(exttypeinfo.typ)
def override__from_opaque_object(pol, s_opaqueptr):
assert isinstance(s_opaqueptr, annmodel.SomePtr)
assert isinstance(s_opaqueptr.ll_ptrtype.TO, lltype.OpaqueType)
exttypeinfo = s_opaqueptr.ll_ptrtype.TO._exttypeinfo
return annmodel.SomeExternalObject(exttypeinfo.typ)
def override__to_opaque_object(pol, s_value):
assert isinstance(s_value, annmodel.SomeExternalObject)
exttypeinfo = extfunctable.typetable[s_value.knowntype]
return annmodel.SomePtr(lltype.Ptr(exttypeinfo.get_lltype()))
def specialize__ts(pol, funcdesc, args_s, ref):
ts = pol.rtyper.type_system
ref = ref.split('.')
x = ts
for part in ref:
x = getattr(x, part)
bk = pol.rtyper.annotator.bookkeeper
funcdesc2 = bk.getdesc(x)
return pol.default_specialize(funcdesc2, args_s)
def specialize__semierased(funcdesc, args_s):
a2l = annmodel.annotation_to_lltype
l2a = annmodel.lltype_to_annotation
args_s[:] = [l2a(a2l(s)) for s in args_s]
return LowLevelAnnotatorPolicy.default_specialize(funcdesc, args_s)
specialize__semierased = staticmethod(specialize__semierased)
specialize__ll = default_specialize
def annotate_lowlevel_helper(annotator, ll_function, args_s, policy=None):
if policy is None:
policy= LowLevelAnnotatorPolicy()
return annotator.annotate_helper(ll_function, args_s, policy)
# ___________________________________________________________________
# Mix-level helpers: combining RPython and ll-level
class MixLevelAnnotatorPolicy(LowLevelAnnotatorPolicy):
def __init__(pol, annhelper):
pol.annhelper = annhelper
pol.rtyper = annhelper.rtyper
def default_specialize(pol, funcdesc, args_s):
name = funcdesc.name
if name.startswith('ll_') or name.startswith('_ll_'): # xxx can we do better?
return super(MixLevelAnnotatorPolicy, pol).default_specialize(
funcdesc, args_s)
else:
return AnnotatorPolicy.default_specialize(funcdesc, args_s)
def specialize__arglltype(pol, funcdesc, args_s, i):
key = pol.rtyper.getrepr(args_s[i]).lowleveltype
alt_name = funcdesc.name+"__for_%sLlT" % key._short_name()
return funcdesc.cachedgraph(key, alt_name=valid_identifier(alt_name))
def specialize__genconst(pol, funcdesc, args_s, i):
# XXX this is specific to the JIT
TYPE = annmodel.annotation_to_lltype(args_s[i], 'genconst')
args_s[i] = annmodel.lltype_to_annotation(TYPE)
alt_name = funcdesc.name + "__%s" % (TYPE._short_name(),)
return funcdesc.cachedgraph(TYPE, alt_name=valid_identifier(alt_name))
class MixLevelHelperAnnotator:
def __init__(self, rtyper):
self.rtyper = rtyper
self.policy = MixLevelAnnotatorPolicy(self)
self.pending = [] # list of (ll_function, graph, args_s, s_result)
self.delayedreprs = {}
self.delayedconsts = []
self.delayedfuncs = []
self.original_graph_count = len(rtyper.annotator.translator.graphs)
def getgraph(self, ll_function, args_s, s_result):
# get the graph of the mix-level helper ll_function and prepare it for
# being annotated. Annotation and RTyping should be done in a single shot
# at the end with finish().
graph, args_s = self.rtyper.annotator.get_call_parameters(
ll_function, args_s, policy = self.policy)
for v_arg, s_arg in zip(graph.getargs(), args_s):
self.rtyper.annotator.setbinding(v_arg, s_arg)
self.rtyper.annotator.setbinding(graph.getreturnvar(), s_result)
#self.rtyper.annotator.annotated[graph.returnblock] = graph
self.pending.append((ll_function, graph, args_s, s_result))
return graph
def delayedfunction(self, ll_function, args_s, s_result, needtype=False):
# get a delayed pointer to the low-level function, annotated as
# specified. The pointer is only valid after finish() was called.
graph = self.getgraph(ll_function, args_s, s_result)
if needtype:
ARGS = [self.getdelayedrepr(s_arg, False).lowleveltype
for s_arg in args_s]
RESULT = self.getdelayedrepr(s_result, False).lowleveltype
FUNCTYPE = lltype.FuncType(ARGS, RESULT)
else:
FUNCTYPE = None
return self.graph2delayed(graph, FUNCTYPE)
def constfunc(self, ll_function, args_s, s_result):
p = self.delayedfunction(ll_function, args_s, s_result)
return Constant(p, lltype.typeOf(p))
def graph2delayed(self, graph, FUNCTYPE=None):
if FUNCTYPE is None:
FUNCTYPE = lltype.ForwardReference()
# obscure hack: embed the name of the function in the string, so
# that the genc database can get it even before the delayedptr
# is really computed
name = "delayed!%s" % (graph.name,)
delayedptr = lltype._ptr(lltype.Ptr(FUNCTYPE), name, solid=True)
self.delayedfuncs.append((delayedptr, graph))
return delayedptr
def graph2const(self, graph):
p = self.graph2delayed(graph)
return Constant(p, lltype.typeOf(p))
def getdelayedrepr(self, s_value, check_never_seen=True):
"""Like rtyper.getrepr(), but the resulting repr will not be setup() at
all before finish() is called.
"""
r = self.rtyper.getrepr(s_value)
if check_never_seen:
r.set_setup_delayed(True)
delayed = True
else:
delayed = r.set_setup_maybe_delayed()
if delayed:
self.delayedreprs[r] = True
return r
def s_r_instanceof(self, cls, can_be_None=True, check_never_seen=True):
classdesc = self.rtyper.annotator.bookkeeper.getdesc(cls)
classdef = classdesc.getuniqueclassdef()
s_instance = annmodel.SomeInstance(classdef, can_be_None)
r_instance = self.getdelayedrepr(s_instance, check_never_seen)
return s_instance, r_instance
def delayedconst(self, repr, obj):
if repr.is_setup_delayed():
# record the existence of this 'obj' for the bookkeeper - e.g.
# if 'obj' is an instance, this will populate the classdef with
# the prebuilt attribute values of the instance
bk = self.rtyper.annotator.bookkeeper
bk.immutablevalue(obj)
delayedptr = lltype._ptr(repr.lowleveltype, "delayed!")
self.delayedconsts.append((delayedptr, repr, obj))
return delayedptr
else:
return repr.convert_const(obj)
def finish(self):
self.finish_annotate()
self.finish_rtype()
def finish_annotate(self):
# push all the graphs into the annotator's pending blocks dict at once
rtyper = self.rtyper
ann = rtyper.annotator
bk = ann.bookkeeper
for ll_function, graph, args_s, s_result in self.pending:
# mark the return block as already annotated, because the return var
# annotation was forced in getgraph() above. This prevents temporary
# less general values reaching the return block from crashing the
# annotator (on the assert-that-new-binding-is-not-less-general).
ann.annotated[graph.returnblock] = graph
s_function = bk.immutablevalue(ll_function)
bk.emulate_pbc_call(graph, s_function, args_s)
ann.complete_helpers(self.policy)
for ll_function, graph, args_s, s_result in self.pending:
s_real_result = ann.binding(graph.getreturnvar())
if s_real_result != s_result:
raise Exception("wrong annotation for the result of %r:\n"
"originally specified: %r\n"
" found by annotating: %r" %
(graph, s_result, s_real_result))
del self.pending[:]
def finish_rtype(self):
rtyper = self.rtyper
rtyper.type_system.perform_normalizations(rtyper)
for r in self.delayedreprs:
r.set_setup_delayed(False)
rtyper.call_all_setups()
for p, repr, obj in self.delayedconsts:
p._become(repr.convert_const(obj))
rtyper.call_all_setups()
for p, graph in self.delayedfuncs:
real_p = rtyper.getcallable(graph)
REAL = lltype.typeOf(real_p).TO
FUNCTYPE = lltype.typeOf(p).TO
if isinstance(FUNCTYPE, lltype.ForwardReference):
FUNCTYPE.become(REAL)
assert FUNCTYPE == REAL
p._become(real_p)
rtyper.specialize_more_blocks()
self.delayedreprs.clear()
del self.delayedconsts[:]
del self.delayedfuncs[:]
def backend_optimize(self, **flags):
# only optimize the newly created graphs
from pypy.translator.backendopt.all import backend_optimizations
translator = self.rtyper.annotator.translator
newgraphs = translator.graphs[self.original_graph_count:]
self.original_graph_count = len(translator.graphs)
backend_optimizations(translator, newgraphs, secondary=True, **flags)
# ____________________________________________________________
class PseudoHighLevelCallable(object):
"""A gateway to a low-level function pointer. To high-level RPython
code it looks like a normal function, taking high-level arguments
and returning a high-level result.
"""
def __init__(self, llfnptr, args_s, s_result):
self.llfnptr = llfnptr
self.args_s = args_s
self.s_result = s_result
def __call__(self, *args):
raise Exception("PseudoHighLevelCallable objects are not really "
"callable directly")
class PseudoHighLevelCallableEntry(extregistry.ExtRegistryEntry):
_type_ = PseudoHighLevelCallable
def compute_result_annotation(self, *args_s):
return self.instance.s_result
def specialize_call(self, hop):
args_r = [hop.rtyper.getrepr(s) for s in self.instance.args_s]
r_res = hop.rtyper.getrepr(self.instance.s_result)
vlist = hop.inputargs(*args_r)
p = self.instance.llfnptr
TYPE = lltype.typeOf(p)
c_func = Constant(p, TYPE)
for r_arg, ARGTYPE in zip(args_r, TYPE.TO.ARGS):
assert r_arg.lowleveltype == ARGTYPE
assert r_res.lowleveltype == TYPE.TO.RESULT
hop.exception_is_here()
return hop.genop('direct_call', [c_func] + vlist, resulttype = r_res)
# ____________________________________________________________
def llhelper(F, f):
# implementation for the purpose of direct running only
# XXX need more cleverness to support translation of prebuilt llhelper ptr
return lltype.functionptr(F.TO, f.func_name, _callable=f)
class LLHelperEntry(extregistry.ExtRegistryEntry):
_about_ = llhelper
def compute_result_annotation(self, s_F, s_callable):
assert s_F.is_constant()
assert s_callable.is_constant()
F = s_F.const
args_s = [annmodel.lltype_to_annotation(T) for T in F.TO.ARGS]
key = (llhelper, s_callable.const)
s_res = self.bookkeeper.emulate_pbc_call(key, s_callable, args_s)
assert annmodel.lltype_to_annotation(F.TO.RESULT).contains(s_res)
return annmodel.SomePtr(F)
def specialize_call(self, hop):
hop.exception_cannot_occur()
return hop.args_r[1].get_unique_llfn()
# ____________________________________________________________
def hlstr(ll_s):
if hasattr(ll_s, 'items'):
return ''.join(items)
else:
return ll_s._str
class HLStrEntry(extregistry.ExtRegistryEntry):
_about_ = hlstr
def compute_result_annotation(self, s_ll_str):
return annmodel.SomeString()
def specialize_call(self, hop):
hop.exception_cannot_occur()
assert hop.args_r[0].lowleveltype == hop.r_result.lowleveltype
v_ll_str, = hop.inputargs(*hop.args_r)
return hop.genop('same_as', [v_ll_str],
resulttype = hop.r_result.lowleveltype)
# ____________________________________________________________
def cast_object_to_ptr(PTR, object):
raise NotImplementedError("cast_object_to_ptr")
def cast_instance_to_base_ptr(instance):
return cast_object_to_ptr(base_ptr_lltype(), instance)
cast_instance_to_base_ptr._annspecialcase_ = 'specialize:argtype(0)'
def base_ptr_lltype():
from pypy.rpython.lltypesystem.rclass import OBJECTPTR
return OBJECTPTR
class CastObjectToPtrEntry(extregistry.ExtRegistryEntry):
_about_ = cast_object_to_ptr
def compute_result_annotation(self, s_PTR, s_object):
assert s_PTR.is_constant()
assert isinstance(s_PTR.const, lltype.Ptr)
return annmodel.SomePtr(s_PTR.const)
def specialize_call(self, hop):
from pypy.rpython import rpbc
PTR = hop.r_result.lowleveltype
if isinstance(hop.args_r[1], rpbc.NoneFrozenPBCRepr):
return hop.inputconst(PTR, lltype.nullptr(PTR.TO))
v_arg = hop.inputarg(hop.args_r[1], arg=1)
assert isinstance(v_arg.concretetype, lltype.Ptr)
hop.exception_cannot_occur()
return hop.genop('cast_pointer', [v_arg],
resulttype = PTR)
# ____________________________________________________________
def cast_base_ptr_to_instance(Class, ptr):
raise NotImplementedError("cast_base_ptr_to_instance")
class CastBasePtrToInstanceEntry(extregistry.ExtRegistryEntry):
_about_ = cast_base_ptr_to_instance
def compute_result_annotation(self, s_Class, s_ptr):
assert s_Class.is_constant()
classdef = self.bookkeeper.getuniqueclassdef(s_Class.const)
return annmodel.SomeInstance(classdef, can_be_None=True)
def specialize_call(self, hop):
v_arg = hop.inputarg(hop.args_r[1], arg=1)
assert isinstance(v_arg.concretetype, lltype.Ptr)
hop.exception_cannot_occur()
return hop.genop('cast_pointer', [v_arg],
resulttype = hop.r_result.lowleveltype)
# ____________________________________________________________
## XXX finish me
##def cast_instance_to_ptr(Class, instance):
## raise NotImplementedError("cast_instance_to_ptr")
##class CastInstanceToPtrEntry(extregistry.ExtRegistryEntry):
## _about_ = cast_instance_to_ptr
## def compute_result_annotation(self, s_Class, s_instance):
## assert s_Class.is_constant()
## pol = self.bookkeeper.annotator.policy
## s_Instance, r_Instance = pol.annhelper.s_r_instanceof(s_Class.const)
## return annmodel.SomePtr(r_Instance.lowleveltype)
## ...
# ____________________________________________________________
def placeholder_sigarg(s):
if s == "self":
def expand(s_self, *args_s):
assert isinstance(s_self, annmodel.SomePtr)
return s_self
elif s == "SELF":
raise NotImplementedError
else:
assert s.islower()
def expand(s_self, *args_s):
assert isinstance(s_self, annmodel.SomePtr)
return getattr(s_self.ll_ptrtype.TO, s.upper())
return expand
def typemeth_placeholder_sigarg(s):
if s == "SELF":
def expand(s_TYPE, *args_s):
assert isinstance(s_TYPE, annmodel.SomePBC)
assert s_TYPE.is_constant()
return s_TYPE
elif s == "self":
def expand(s_TYPE, *args_s):
assert isinstance(s_TYPE, annmodel.SomePBC)
assert s_TYPE.is_constant()
return lltype.Ptr(s_TYPE.const)
else:
assert s.islower()
def expand(s_TYPE, *args_s):
assert isinstance(s_TYPE, annmodel.SomePBC)
assert s_TYPE.is_constant()
return getattr(s_TYPE.const, s.upper())
return expand
class ADTInterface(object):
def __init__(self, base, sigtemplates):
self.sigtemplates = sigtemplates
self.base = base
sigs = {}
if base is not None:
sigs.update(base.sigs)
for name, template in sigtemplates.items():
args, result = template
if args[0] == "self":
make_expand = placeholder_sigarg
elif args[0] == "SELF":
make_expand = typemeth_placeholder_sigarg
else:
assert False, ("ADTInterface signature should start with"
" 'SELF' or 'self'")
sigargs = []
for arg in args:
if isinstance(arg, str):
arg = make_expand(arg)
sigargs.append(arg)
sigs[name] = Sig(*sigargs)
self.sigs = sigs
def __call__(self, adtmeths):
for name, sig in self.sigs.items():
meth = adtmeths[name]
prevsig = getattr(meth, '_annenforceargs_', None)
if prevsig:
assert prevsig is sig
else:
meth._annenforceargs_ = sig
return adtmeths
# ____________________________________________________________
class cachedtype(type):
"""Metaclass for classes that should only have one instance per
tuple of arguments given to the constructor."""
def __init__(selfcls, name, bases, dict):
super(cachedtype, selfcls).__init__(name, bases, dict)
selfcls._instancecache = {}
def __call__(selfcls, *args):
d = selfcls._instancecache
try:
return d[args]
except KeyError:
instance = d[args] = selfcls.__new__(selfcls, *args)
try:
instance.__init__(*args)
except:
# If __init__ fails, remove the 'instance' from d.
# That's a "best effort" attempt, it's not really enough
# in theory because some other place might have grabbed
# a reference to the same broken 'instance' in the meantime
del d[args]
raise
return instance
| Python |
"""
RTyper: converts high-level operations into low-level operations in flow graphs.
The main class, with code to walk blocks and dispatch individual operations
to the care of the rtype_*() methods implemented in the other r* modules.
For each high-level operation 'hop', the rtype_*() methods produce low-level
operations that are collected in the 'llops' list defined here. When necessary,
conversions are inserted.
This logic borrows a bit from pypy.annotation.annrpython, without the fixpoint
computation part.
"""
from __future__ import generators
import os
import py
from pypy.annotation.pairtype import pair
from pypy.annotation import model as annmodel
from pypy.objspace.flow.model import Variable, Constant
from pypy.objspace.flow.model import SpaceOperation, c_last_exception
from pypy.rpython.lltypesystem.lltype import \
Signed, Unsigned, Float, Char, Bool, Void, \
LowLevelType, Ptr, ContainerType, \
FuncType, functionptr, typeOf, RuntimeTypeInfo, \
attachRuntimeTypeInfo, Primitive, Number
from pypy.rpython.ootypesystem import ootype
from pypy.translator.unsimplify import insert_empty_block
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import Repr, inputconst, BrokenReprTyperError
from pypy.rpython.rmodel import warning, HalfConcreteWrapper
from pypy.rpython.annlowlevel import annotate_lowlevel_helper, LowLevelAnnotatorPolicy
from pypy.rpython.typesystem import LowLevelTypeSystem,\
ObjectOrientedTypeSystem
class RPythonTyper(object):
from pypy.rpython.rmodel import log
def __init__(self, annotator, type_system="lltype"):
self.annotator = annotator
self.lowlevel_ann_policy = LowLevelAnnotatorPolicy(self)
if isinstance(type_system, str):
if type_system == "lltype":
self.type_system = LowLevelTypeSystem.instance
elif type_system == "ootype":
self.type_system = ObjectOrientedTypeSystem.instance
else:
raise TyperError("Unknown type system %r!" % type_system)
else:
self.type_system = type_system
self.type_system_deref = self.type_system.deref
self.reprs = {}
self._reprs_must_call_setup = []
self._seen_reprs_must_call_setup = {}
self._dict_traits = {}
self.class_reprs = {}
self.instance_reprs = {}
self.pbc_reprs = {}
self.classes_with_wrapper = {}
self.wrapper_context = None # or add an extra arg to convertvar?
self.classdef_to_pytypeobject = {}
self.concrete_calltables = {}
self.class_pbc_attributes = {}
self.oo_meth_impls = {}
self.cache_dummy_values = {}
self.typererrors = []
self.typererror_count = 0
# make the primitive_to_repr constant mapping
self.primitive_to_repr = {}
if self.type_system.offers_exceptiondata:
self.exceptiondata = self.type_system.exceptiondata.ExceptionData(self)
else:
self.exceptiondata = None
try:
self.seed = int(os.getenv('RTYPERSEED'))
s = 'Using %d as seed for block shuffling' % self.seed
self.log.info(s)
except:
self.seed = 0
self.order = None
# the following code would invoke translator.goal.order, which is
# not up-to-date any more:
## RTYPERORDER = os.getenv('RTYPERORDER')
## if RTYPERORDER:
## order_module = RTYPERORDER.split(',')[0]
## self.order = __import__(order_module, {}, {}, ['*']).order
## s = 'Using %s.%s for order' % (self.order.__module__, self.order.__name__)
## self.log.info(s)
self.crash_on_first_typeerror = True
def getconfig(self):
return self.annotator.translator.config
def getprimitiverepr(self, lltype):
try:
return self.primitive_to_repr[lltype]
except KeyError:
pass
if isinstance(lltype, Primitive):
repr = self.primitive_to_repr[lltype] = self.getrepr(annmodel.lltype_to_annotation(lltype))
return repr
raise TyperError('There is no primitive repr for %r'%(lltype,))
def add_wrapper(self, clsdef):
# record that this class has a wrapper, and what the __init__ is
cls = clsdef.classdesc.pyobj
init = getattr(cls.__init__, 'im_func', None)
self.classes_with_wrapper[cls] = init
def set_wrapper_context(self, obj):
# not nice, but we sometimes need to know which function we are wrapping
self.wrapper_context = obj
def add_pendingsetup(self, repr):
assert isinstance(repr, Repr)
if repr in self._seen_reprs_must_call_setup:
#warning("ignoring already seen repr for setup: %r" %(repr,))
return
self._reprs_must_call_setup.append(repr)
self._seen_reprs_must_call_setup[repr] = True
def getexceptiondata(self):
return self.exceptiondata # built at the end of specialize()
def lltype_to_classdef_mapping(self):
result = {}
for (classdef, _), repr in self.instance_reprs.iteritems():
result[repr.lowleveltype] = classdef
return result
def makekey(self, s_obj):
return pair(self.type_system, s_obj).rtyper_makekey(self)
def makerepr(self, s_obj):
return pair(self.type_system, s_obj).rtyper_makerepr(self)
def getrepr(self, s_obj):
# s_objs are not hashable... try hard to find a unique key anyway
key = self.makekey(s_obj)
assert key[0] == s_obj.__class__
try:
result = self.reprs[key]
except KeyError:
self.reprs[key] = None
result = self.makerepr(s_obj)
assert not isinstance(result.lowleveltype, ContainerType), (
"missing a Ptr in the type specification "
"of %s:\n%r" % (s_obj, result.lowleveltype))
self.reprs[key] = result
self.add_pendingsetup(result)
assert result is not None # recursive getrepr()!
return result
def binding(self, var, default=annmodel.SomeObject()):
s_obj = self.annotator.binding(var, default)
return s_obj
def bindingrepr(self, var):
return self.getrepr(self.binding(var))
def specialize(self, dont_simplify_again=False, crash_on_first_typeerror = True):
"""Main entry point: specialize all annotated blocks of the program."""
self.crash_on_first_typeerror = crash_on_first_typeerror
# specialize depends on annotator simplifications
assert dont_simplify_again in (False, True) # safety check
if not dont_simplify_again:
self.annotator.simplify()
# first make sure that all functions called in a group have exactly
# the same signature, by hacking their flow graphs if needed
self.type_system.perform_normalizations(self)
self.exceptiondata.finish(self)
# new blocks can be created as a result of specialize_block(), so
# we need to be careful about the loop here.
self.already_seen = {}
self.specialize_more_blocks()
if self.exceptiondata is not None:
self.exceptiondata.make_helpers(self)
self.specialize_more_blocks() # for the helpers just made
#
from pypy.annotation import listdef
ldef = listdef.ListDef(None, annmodel.SomeString())
self.list_of_str_repr = self.getrepr(annmodel.SomeList(ldef))
def getannmixlevel(self):
if self.annmixlevel is not None:
return self.annmixlevel
from pypy.rpython.annlowlevel import MixLevelHelperAnnotator
self.annmixlevel = MixLevelHelperAnnotator(self)
return self.annmixlevel
def specialize_more_blocks(self):
if self.already_seen:
newtext = ' more'
else:
newtext = ''
blockcount = 0
self.annmixlevel = None
while True:
# look for blocks not specialized yet
pending = [block for block in self.annotator.annotated
if block not in self.already_seen]
if not pending:
break
# shuffle blocks a bit
if self.seed:
import random
r = random.Random(self.seed)
r.shuffle(pending)
if self.order:
tracking = self.order(self.annotator, pending)
else:
tracking = lambda block: None
previous_percentage = 0
# specialize all blocks in the 'pending' list
for block in pending:
tracking(block)
blockcount += 1
self.specialize_block(block)
self.already_seen[block] = True
# progress bar
n = len(self.already_seen)
if n % 100 == 0:
total = len(self.annotator.annotated)
percentage = 100 * n // total
if percentage >= previous_percentage + 5:
previous_percentage = percentage
if self.typererror_count:
error_report = " but %d errors" % self.typererror_count
else:
error_report = ''
self.log.event('specializing: %d / %d blocks (%d%%)%s' %
(n, total, percentage, error_report))
# make sure all reprs so far have had their setup() called
self.call_all_setups()
if self.typererrors:
self.dump_typererrors(to_log=True)
raise TyperError("there were %d error" % len(self.typererrors))
self.log.event('-=- specialized %d%s blocks -=-' % (
blockcount, newtext))
annmixlevel = self.annmixlevel
del self.annmixlevel
if annmixlevel is not None:
annmixlevel.finish()
def dump_typererrors(self, num=None, minimize=True, to_log=False):
c = 0
bc = 0
for err in self.typererrors[:num]:
c += 1
if minimize and isinstance(err, BrokenReprTyperError):
bc += 1
continue
block, position = err.where
graph = self.annotator.annotated.get(block, None)
errmsg = ("TyperError-%d: %s\n" % (c, graph) +
str(err) +
"\n")
if to_log:
self.log.ERROR(errmsg)
else:
print errmsg
if bc:
minmsg = "(minimized %d errors away for this dump)" % (bc,)
if to_log:
self.log.ERROR(minmsg)
else:
print minmsg
def call_all_setups(self):
# make sure all reprs so far have had their setup() called
must_setup_more = []
delayed = []
while self._reprs_must_call_setup:
r = self._reprs_must_call_setup.pop()
if r.is_setup_delayed():
delayed.append(r)
else:
r.setup()
must_setup_more.append(r)
for r in must_setup_more:
r.setup_final()
self._reprs_must_call_setup.extend(delayed)
def setconcretetype(self, v):
assert isinstance(v, Variable)
v.concretetype = self.bindingrepr(v).lowleveltype
def setup_block_entry(self, block):
if block.operations == () and len(block.inputargs) == 2:
# special case for exception blocks: force them to return an
# exception type and value in a standardized format
v1, v2 = block.inputargs
v1.concretetype = self.exceptiondata.lltype_of_exception_type
v2.concretetype = self.exceptiondata.lltype_of_exception_value
return [self.exceptiondata.r_exception_type,
self.exceptiondata.r_exception_value]
else:
# normal path
result = []
for a in block.inputargs:
r = self.bindingrepr(a)
a.concretetype = r.lowleveltype
result.append(r)
return result
def make_new_lloplist(self, block):
return LowLevelOpList(self, block)
def specialize_block(self, block):
graph = self.annotator.annotated[block]
if graph not in self.annotator.fixed_graphs:
self.annotator.fixed_graphs[graph] = True
# make sure that the return variables of all graphs
# are concretetype'd
self.setconcretetype(graph.getreturnvar())
# give the best possible types to the input args
try:
self.setup_block_entry(block)
except TyperError, e:
self.gottypererror(e, block, "block-entry", None)
return # cannot continue this block
# specialize all the operations, as far as possible
if block.operations == (): # return or except block
return
newops = self.make_new_lloplist(block)
varmapping = {}
for v in block.getvariables():
varmapping[v] = v # records existing Variables
for hop in self.highlevelops(block, newops):
try:
hop.setup() # this is called from here to catch TyperErrors...
self.translate_hl_to_ll(hop, varmapping)
except TyperError, e:
self.gottypererror(e, block, hop.spaceop, newops)
return # cannot continue this block: no op.result.concretetype
block.operations[:] = newops
block.renamevariables(varmapping)
extrablock = None
pos = newops.llop_raising_exceptions
if (pos is not None and pos != len(newops)-1):
# this is for the case where the llop that raises the exceptions
# is not the last one in the list.
assert block.exitswitch == c_last_exception
noexclink = block.exits[0]
assert noexclink.exitcase is None
if pos == "removed":
# the exception cannot actually occur at all.
# See for example rspecialcase.rtype_call_specialcase().
# We just remove all exception links.
block.exitswitch = None
block.exits = block.exits[:1]
else:
# We have to split the block in two, with the exception-catching
# exitswitch after the llop at 'pos', and the extra operations
# in the new part of the block, corresponding to the
# no-exception case. See for example test_rlist.test_indexerror
# or test_rpbc.test_multiple_ll_one_hl_op.
assert 0 <= pos < len(newops) - 1
extraops = block.operations[pos+1:]
del block.operations[pos+1:]
extrablock = insert_empty_block(self.annotator,
noexclink,
newops = extraops)
if extrablock is None:
self.insert_link_conversions(block)
else:
# skip the extrablock as a link target, its link doesn't need conversions
# by construction, OTOH some of involved vars have no annotation
# so proceeding with it would kill information
self.insert_link_conversions(block, skip=1)
# consider it as a link source instead
self.insert_link_conversions(extrablock)
def _convert_link(self, block, link):
if link.exitcase is not None and link.exitcase != 'default':
if isinstance(block.exitswitch, Variable):
r_case = self.bindingrepr(block.exitswitch)
else:
assert block.exitswitch == c_last_exception
r_case = rclass.get_type_repr(self)
link.llexitcase = r_case.convert_const(link.exitcase)
else:
link.llexitcase = None
a = link.last_exception
if isinstance(a, Variable):
a.concretetype = self.exceptiondata.lltype_of_exception_type
elif isinstance(a, Constant):
link.last_exception = inputconst(
self.exceptiondata.r_exception_type, a.value)
a = link.last_exc_value
if isinstance(a, Variable):
a.concretetype = self.exceptiondata.lltype_of_exception_value
elif isinstance(a, Constant):
link.last_exc_value = inputconst(
self.exceptiondata.r_exception_value, a.value)
def insert_link_conversions(self, block, skip=0):
# insert the needed conversions on the links
can_insert_here = block.exitswitch is None and len(block.exits) == 1
for link in block.exits[skip:]:
self._convert_link(block, link)
inputargs_reprs = self.setup_block_entry(link.target)
newops = self.make_new_lloplist(block)
newlinkargs = {}
for i in range(len(link.args)):
a1 = link.args[i]
r_a2 = inputargs_reprs[i]
if isinstance(a1, Constant):
link.args[i] = inputconst(r_a2, a1.value)
continue # the Constant was typed, done
if a1 is link.last_exception:
r_a1 = self.exceptiondata.r_exception_type
elif a1 is link.last_exc_value:
r_a1 = self.exceptiondata.r_exception_value
else:
r_a1 = self.bindingrepr(a1)
if r_a1 == r_a2:
continue # no conversion needed
try:
new_a1 = newops.convertvar(a1, r_a1, r_a2)
except TyperError, e:
self.gottypererror(e, block, link, newops)
continue # try other args
if new_a1 != a1:
newlinkargs[i] = new_a1
if newops:
if can_insert_here:
block.operations.extend(newops)
else:
# cannot insert conversion operations around a single
# link, unless it is the only exit of this block.
# create a new block along the link...
newblock = insert_empty_block(self.annotator,
link,
# ...and store the conversions there.
newops=newops)
link = newblock.exits[0]
for i, new_a1 in newlinkargs.items():
link.args[i] = new_a1
def highlevelops(self, block, llops):
# enumerate the HighLevelOps in a block.
if block.operations:
for op in block.operations[:-1]:
yield HighLevelOp(self, op, [], llops)
# look for exception links for the last operation
if block.exitswitch == c_last_exception:
exclinks = block.exits[1:]
else:
exclinks = []
yield HighLevelOp(self, block.operations[-1], exclinks, llops)
def translate_hl_to_ll(self, hop, varmapping):
#self.log.translating(hop.spaceop.opname, hop.args_s)
resultvar = hop.dispatch()
if hop.exceptionlinks and hop.llops.llop_raising_exceptions is None:
raise TyperError("the graph catches %s, but the rtyper did not "
"take exceptions into account "
"(exception_is_here() not called)" % (
[link.exitcase.__name__ for link in hop.exceptionlinks],))
if resultvar is None:
# no return value
self.translate_no_return_value(hop)
else:
assert isinstance(resultvar, (Variable, Constant))
op = hop.spaceop
# for simplicity of the translate_meth, resultvar is usually not
# op.result here. We have to replace resultvar with op.result
# in all generated operations.
if hop.s_result.is_constant():
if isinstance(resultvar, Constant) and \
isinstance(hop.r_result.lowleveltype, Primitive) and \
hop.r_result.lowleveltype is not Void:
assert resultvar.value == hop.s_result.const
resulttype = resultvar.concretetype
op.result.concretetype = hop.r_result.lowleveltype
if op.result.concretetype != resulttype:
raise TyperError("inconsistent type for the result of '%s':\n"
"annotator says %s,\n"
"whose repr is %r\n"
"but rtype_%s returned %r" % (
op.opname, hop.s_result,
hop.r_result, op.opname, resulttype))
# figure out if the resultvar is a completely fresh Variable or not
if (isinstance(resultvar, Variable) and
resultvar not in self.annotator.bindings and
resultvar not in varmapping):
# fresh Variable: rename it to the previously existing op.result
varmapping[resultvar] = op.result
elif resultvar is op.result:
# special case: we got the previous op.result Variable again
assert varmapping[resultvar] is resultvar
else:
# renaming unsafe. Insert a 'same_as' operation...
hop.llops.append(SpaceOperation('same_as', [resultvar],
op.result))
def translate_no_return_value(self, hop):
op = hop.spaceop
if hop.s_result != annmodel.s_ImpossibleValue:
raise TyperError("the annotator doesn't agree that '%s' "
"has no return value" % op.opname)
op.result.concretetype = Void
def gottypererror(self, e, block, position, llops):
"""Record a TyperError without crashing immediately.
Put a 'TyperError' operation in the graph instead.
"""
e.where = (block, position)
self.typererror_count += 1
if self.crash_on_first_typeerror:
raise
self.typererrors.append(e)
if llops:
c1 = inputconst(Void, Exception.__str__(e))
llops.genop('TYPER ERROR', [c1], resulttype=Void)
# __________ regular operations __________
def _registeroperations(cls, model):
d = {}
# All unary operations
for opname in model.UNARY_OPERATIONS:
fnname = 'translate_op_' + opname
exec py.code.compile("""
def translate_op_%s(self, hop):
r_arg1 = hop.args_r[0]
return r_arg1.rtype_%s(hop)
""" % (opname, opname)) in globals(), d
setattr(cls, fnname, d[fnname])
# All binary operations
for opname in model.BINARY_OPERATIONS:
fnname = 'translate_op_' + opname
exec py.code.compile("""
def translate_op_%s(self, hop):
r_arg1 = hop.args_r[0]
r_arg2 = hop.args_r[1]
return pair(r_arg1, r_arg2).rtype_%s(hop)
""" % (opname, opname)) in globals(), d
setattr(cls, fnname, d[fnname])
_registeroperations = classmethod(_registeroperations)
# this one is not in BINARY_OPERATIONS
def translate_op_contains(self, hop):
r_arg1 = hop.args_r[0]
r_arg2 = hop.args_r[1]
return pair(r_arg1, r_arg2).rtype_contains(hop)
# __________ irregular operations __________
def translate_op_newlist(self, hop):
return rlist.rtype_newlist(hop)
def translate_op_newdict(self, hop):
return self.type_system.rdict.rtype_newdict(hop)
def translate_op_alloc_and_set(self, hop):
return rlist.rtype_alloc_and_set(hop)
def translate_op_extend_with_str_slice(self, hop):
r_arg1 = hop.args_r[0]
r_arg2 = hop.args_r[1]
return pair(r_arg1, r_arg2).rtype_extend_with_str_slice(hop)
def translate_op_extend_with_char_count(self, hop):
r_arg1 = hop.args_r[0]
r_arg2 = hop.args_r[1]
return pair(r_arg1, r_arg2).rtype_extend_with_char_count(hop)
def translate_op_newtuple(self, hop):
return self.type_system.rtuple.rtype_newtuple(hop)
def translate_op_newslice(self, hop):
return rslice.rtype_newslice(hop)
def translate_op_instantiate1(self, hop):
from pypy.rpython.lltypesystem import rclass
if not isinstance(hop.s_result, annmodel.SomeInstance):
raise TyperError("instantiate1 got s_result=%r" % (hop.s_result,))
classdef = hop.s_result.classdef
return rclass.rtype_new_instance(self, classdef, hop.llops)
generic_translate_operation = None
def default_translate_operation(self, hop):
raise TyperError("unimplemented operation: '%s'" % hop.spaceop.opname)
# __________ utilities __________
def needs_hash_support(self, clsdef):
return clsdef in self.annotator.bookkeeper.needs_hash_support
def needs_wrapper(self, cls):
return cls in self.classes_with_wrapper
def get_wrapping_hint(self, clsdef):
cls = clsdef.classdesc.pyobj
return self.classes_with_wrapper[cls], self.wrapper_context
def getcallable(self, graph):
def getconcretetype(v):
return self.bindingrepr(v).lowleveltype
return self.type_system.getcallable(graph, getconcretetype)
def annotate_helper(self, ll_function, argtypes):
"""Annotate the given low-level helper function and return its graph
"""
args_s = []
for s in argtypes:
# assume 's' is a low-level type, unless it is already an annotation
if not isinstance(s, annmodel.SomeObject):
s = annmodel.lltype_to_annotation(s)
args_s.append(s)
# hack for bound methods
if hasattr(ll_function, 'im_func'):
bk = self.annotator.bookkeeper
args_s.insert(0, bk.immutablevalue(ll_function.im_self))
ll_function = ll_function.im_func
helper_graph = annotate_lowlevel_helper(self.annotator,
ll_function, args_s,
policy=self.lowlevel_ann_policy)
return helper_graph
def annotate_helper_fn(self, ll_function, argtypes):
"""Annotate the given low-level helper function
and return it as a function pointer
"""
graph = self.annotate_helper(ll_function, argtypes)
return self.getcallable(graph)
def attachRuntimeTypeInfoFunc(self, GCSTRUCT, func, ARG_GCSTRUCT=None,
destrptr=None):
self.call_all_setups() # compute ForwardReferences now
if ARG_GCSTRUCT is None:
ARG_GCSTRUCT = GCSTRUCT
args_s = [annmodel.SomePtr(Ptr(ARG_GCSTRUCT))]
graph = self.annotate_helper(func, args_s)
s = self.annotator.binding(graph.getreturnvar())
if (not isinstance(s, annmodel.SomePtr) or
s.ll_ptrtype != Ptr(RuntimeTypeInfo)):
raise TyperError("runtime type info function %r returns %r, "
"excepted Ptr(RuntimeTypeInfo)" % (func, s))
funcptr = self.getcallable(graph)
attachRuntimeTypeInfo(GCSTRUCT, funcptr, destrptr)
# register operations from annotation model
RPythonTyper._registeroperations(annmodel)
# ____________________________________________________________
class HighLevelOp(object):
forced_opname = None
def __init__(self, rtyper, spaceop, exceptionlinks, llops):
self.rtyper = rtyper
self.spaceop = spaceop
self.exceptionlinks = exceptionlinks
self.llops = llops
def setup(self):
rtyper = self.rtyper
spaceop = self.spaceop
self.nb_args = len(spaceop.args)
self.args_v = list(spaceop.args)
self.args_s = [rtyper.binding(a) for a in spaceop.args]
self.s_result = rtyper.binding(spaceop.result)
self.args_r = [rtyper.getrepr(s_a) for s_a in self.args_s]
self.r_result = rtyper.getrepr(self.s_result)
rtyper.call_all_setups() # compute ForwardReferences now
def copy(self):
result = HighLevelOp(self.rtyper, self.spaceop,
self.exceptionlinks, self.llops)
for key, value in self.__dict__.items():
if type(value) is list: # grunt
value = value[:]
setattr(result, key, value)
result.forced_opname = self.forced_opname
return result
def dispatch(self):
rtyper = self.rtyper
generic = rtyper.generic_translate_operation
if generic is not None:
res = generic(self)
if res is not None:
return res
opname = self.forced_opname or self.spaceop.opname
translate_meth = getattr(rtyper, 'translate_op_'+opname,
rtyper.default_translate_operation)
return translate_meth(self)
def inputarg(self, converted_to, arg):
"""Returns the arg'th input argument of the current operation,
as a Variable or Constant converted to the requested type.
'converted_to' should be a Repr instance or a Primitive low-level
type.
"""
if not isinstance(converted_to, Repr):
converted_to = self.rtyper.getprimitiverepr(converted_to)
v = self.args_v[arg]
if isinstance(v, Constant):
return inputconst(converted_to, v.value)
assert hasattr(v, 'concretetype')
s_binding = self.args_s[arg]
if s_binding.is_constant():
return inputconst(converted_to, s_binding.const)
r_binding = self.args_r[arg]
return self.llops.convertvar(v, r_binding, converted_to)
inputconst = staticmethod(inputconst) # export via the HighLevelOp class
def inputargs(self, *converted_to):
if len(converted_to) != self.nb_args:
raise TyperError("operation argument count mismatch:\n"
"'%s' has %d arguments, rtyper wants %d" % (
self.spaceop.opname, self.nb_args, len(converted_to)))
vars = []
for i in range(len(converted_to)):
vars.append(self.inputarg(converted_to[i], i))
return vars
def genop(self, opname, args_v, resulttype=None):
return self.llops.genop(opname, args_v, resulttype)
def gendirectcall(self, ll_function, *args_v):
return self.llops.gendirectcall(ll_function, *args_v)
def r_s_pop(self, index=-1):
"Return and discard the argument with index position."
self.nb_args -= 1
self.args_v.pop(index)
return self.args_r.pop(index), self.args_s.pop(index)
def r_s_popfirstarg(self):
"Return and discard the first argument."
return self.r_s_pop(0)
def v_s_insertfirstarg(self, v_newfirstarg, s_newfirstarg):
r_newfirstarg = self.rtyper.getrepr(s_newfirstarg)
self.args_v.insert(0, v_newfirstarg)
self.args_r.insert(0, r_newfirstarg)
self.args_s.insert(0, s_newfirstarg)
self.nb_args += 1
def swap_fst_snd_args(self):
self.args_v[0], self.args_v[1] = self.args_v[1], self.args_v[0]
self.args_s[0], self.args_s[1] = self.args_s[1], self.args_s[0]
self.args_r[0], self.args_r[1] = self.args_r[1], self.args_r[0]
def has_implicit_exception(self, exc_cls):
if self.llops.llop_raising_exceptions is not None:
raise TyperError("already generated the llop that raises the "
"exception")
if not self.exceptionlinks:
return False # don't record has_implicit_exception checks on
# high-level ops before the last one in the block
if self.llops.implicit_exceptions_checked is None:
self.llops.implicit_exceptions_checked = []
result = False
for link in self.exceptionlinks:
if issubclass(exc_cls, link.exitcase):
self.llops.implicit_exceptions_checked.append(link.exitcase)
result = True
# go on looping to add possibly more exceptions to the list
# (e.g. Exception itself - see test_rlist.test_valueerror)
return result
def exception_is_here(self):
if self.llops.llop_raising_exceptions is not None:
raise TyperError("cannot catch an exception at more than one llop")
if not self.exceptionlinks:
return # ignored for high-level ops before the last one in the block
if self.llops.implicit_exceptions_checked is not None:
# sanity check: complain if an has_implicit_exception() check is
# missing in the rtyper.
for link in self.exceptionlinks:
if link.exitcase not in self.llops.implicit_exceptions_checked:
raise TyperError("the graph catches %s, but the rtyper "
"did not explicitely handle it" % (
link.exitcase.__name__,))
self.llops.llop_raising_exceptions = len(self.llops)
def exception_cannot_occur(self):
if self.llops.llop_raising_exceptions is not None:
raise TyperError("cannot catch an exception at more than one llop")
if not self.exceptionlinks:
return # ignored for high-level ops before the last one in the block
self.llops.llop_raising_exceptions = "removed"
# ____________________________________________________________
class LowLevelOpList(list):
"""A list with gen*() methods to build and append low-level
operations to it.
"""
# NB. the following two attributes are here instead of on HighLevelOp
# because we want them to be shared between a HighLevelOp and its
# copy()es.
llop_raising_exceptions = None
implicit_exceptions_checked = None
def __init__(self, rtyper=None, originalblock=None):
self.rtyper = rtyper
self.originalblock = originalblock
def getparentgraph(self):
return self.rtyper.annotator.annotated[self.originalblock]
def hasparentgraph(self):
return self.originalblock is not None
def record_extra_call(self, graph):
if self.hasparentgraph():
self.rtyper.annotator.translator.update_call_graph(
caller_graph = self.getparentgraph(),
callee_graph = graph,
position_tag = object())
def convertvar(self, v, r_from, r_to):
assert isinstance(v, (Variable, Constant))
if r_from != r_to:
v = pair(r_from, r_to).convert_from_to(v, self)
if v is NotImplemented:
raise TyperError("don't know how to convert from %r to %r" %
(r_from, r_to))
if v.concretetype != r_to.lowleveltype:
raise TyperError("bug in conversion from %r to %r: "
"returned a %r" % (r_from, r_to,
v.concretetype))
return v
def genop(self, opname, args_v, resulttype=None):
try:
for v in args_v:
v.concretetype
except AttributeError:
raise AssertionError("wrong level! you must call hop.inputargs()"
" and pass its result to genop(),"
" never hop.args_v directly.")
vresult = Variable()
self.append(SpaceOperation(opname, args_v, vresult))
if resulttype is None:
vresult.concretetype = Void
return None
else:
if isinstance(resulttype, Repr):
resulttype = resulttype.lowleveltype
assert isinstance(resulttype, LowLevelType)
vresult.concretetype = resulttype
return vresult
def gendirectcall(self, ll_function, *args_v):
rtyper = self.rtyper
args_s = []
newargs_v = []
for v in args_v:
if v.concretetype is Void:
s_value = rtyper.binding(v, default=annmodel.s_None)
if not s_value.is_constant():
raise TyperError("non-constant variable of type Void")
if not isinstance(s_value, annmodel.SomePBC):
raise TyperError("non-PBC Void argument: %r", (s_value,))
if isinstance(s_value.const, HalfConcreteWrapper):
# Modify args_v so that 'v' gets the concrete value
# returned by the wrapper
wrapper = s_value.const
v = wrapper.concretize()
s_value = annmodel.lltype_to_annotation(v.concretetype)
args_s.append(s_value)
else:
args_s.append(annmodel.lltype_to_annotation(v.concretetype))
newargs_v.append(v)
self.rtyper.call_all_setups() # compute ForwardReferences now
# hack for bound methods
if hasattr(ll_function, 'im_func'):
bk = rtyper.annotator.bookkeeper
args_s.insert(0, bk.immutablevalue(ll_function.im_self))
newargs_v.insert(0, inputconst(Void, ll_function.im_self))
ll_function = ll_function.im_func
graph = annotate_lowlevel_helper(rtyper.annotator, ll_function, args_s,
rtyper.lowlevel_ann_policy)
self.record_extra_call(graph)
# build the 'direct_call' operation
f = self.rtyper.getcallable(graph)
c = inputconst(typeOf(f), f)
fobj = self.rtyper.type_system_deref(f)
return self.genop('direct_call', [c]+newargs_v,
resulttype = typeOf(fobj).RESULT)
def genexternalcall(self, fnname, args_v, resulttype=None, **flags):
if isinstance(resulttype, Repr):
resulttype = resulttype.lowleveltype
argtypes = [v.concretetype for v in args_v]
FUNCTYPE = FuncType(argtypes, resulttype or Void)
f = functionptr(FUNCTYPE, fnname, **flags)
cf = inputconst(typeOf(f), f)
return self.genop('direct_call', [cf]+list(args_v), resulttype)
def gencapicall(self, cfnname, args_v, resulttype=None, **flags):
return self.genexternalcall(cfnname, args_v, resulttype=resulttype, external="C", **flags)
def genconst(self, ll_value):
return inputconst(typeOf(ll_value), ll_value)
def genvoidconst(self, placeholder):
return inputconst(Void, placeholder)
def constTYPE(self, T):
return T
# _______________________________________________________________________
# this has the side-effect of registering the unary and binary operations
# and the rtyper_chooserepr() methods
from pypy.rpython import robject
from pypy.rpython import rint, rbool, rfloat
from pypy.rpython import rslice, rrange
from pypy.rpython import rstr, rdict, rlist
from pypy.rpython import rclass, rbuiltin, rpbc, rspecialcase
from pypy.rpython import rexternalobj
from pypy.rpython import rptr
from pypy.rpython import rgeneric
from pypy.rpython import raddress # memory addresses
from pypy.rpython.ootypesystem import rootype
| Python |
from pypy.annotation.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.rpython.lltypesystem.lltype import \
PyObject, Ptr, Void, pyobjectptr, nullptr, Bool
from pypy.rpython.rmodel import Repr, VoidRepr, inputconst
from pypy.rpython import rclass
from pypy.tool.sourcetools import func_with_new_name
class __extend__(annmodel.SomeObject):
def rtyper_makerepr(self, rtyper):
kind = getkind(self)
if kind == "type":
return rclass.get_type_repr(rtyper)
elif kind == "const":
return constpyobj_repr
else:
return pyobj_repr
def rtyper_makekey(self):
return self.__class__, getkind(self)
def getkind(s_obj):
if s_obj.is_constant():
if getattr(s_obj.const, '__module__', None) == '__builtin__':
return "const"
if s_obj.knowntype is type:
return "type"
if s_obj.is_constant():
return "const"
return "pyobj"
class PyObjRepr(Repr):
def convert_const(self, value):
return pyobjectptr(value)
def make_iterator_repr(self):
return pyobj_repr
pyobj_repr = PyObjRepr()
pyobj_repr.lowleveltype = Ptr(PyObject)
constpyobj_repr = PyObjRepr()
constpyobj_repr.lowleveltype = Void
class __extend__(pairtype(VoidRepr, PyObjRepr)):
# conversion used to return a PyObject* when a function can really only
# raise an exception, in which case the return value is a VoidRepr
def convert_from_to(_, v, llops):
return inputconst(Ptr(PyObject), nullptr(PyObject))
# ____________________________________________________________
#
# All operations involving a PyObjRepr are "replaced" by themselves,
# after converting all other arguments to PyObjRepr as well. This
# basically defers the operations to the care of the code generator.
def make_operation(opname, cls=PyObjRepr):
def rtype_op(_, hop):
vlist = hop.inputargs(*([pyobj_repr]*hop.nb_args))
hop.exception_is_here()
v = hop.genop(opname, vlist, resulttype=pyobj_repr)
if not isinstance(hop.r_result, VoidRepr):
return hop.llops.convertvar(v, pyobj_repr, hop.r_result)
funcname = 'rtype_' + opname
func = func_with_new_name(rtype_op, funcname)
assert funcname not in cls.__dict__ # can be in Repr; overridden then.
setattr(cls, funcname, func)
for opname in annmodel.UNARY_OPERATIONS:
make_operation(opname)
for opname in annmodel.BINARY_OPERATIONS:
make_operation(opname, pairtype(PyObjRepr, Repr))
make_operation(opname, pairtype(Repr, PyObjRepr))
class __extend__(pairtype(PyObjRepr, PyObjRepr)):
def rtype_contains((r_seq, r_item), hop):
v_seq, v_item = hop.inputargs(r_seq, r_item)
return hop.llops.gencapicall('PySequence_Contains_with_exc',
[v_seq, v_item], resulttype=Bool)
| Python |
import types
from pypy.annotation import model as annmodel
#from pypy.annotation.classdef import isclassdef
from pypy.annotation import description
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import Repr, getgcflavor
def getclassrepr(rtyper, classdef):
try:
result = rtyper.class_reprs[classdef]
except KeyError:
result = rtyper.type_system.rclass.ClassRepr(rtyper, classdef)
rtyper.class_reprs[classdef] = result
rtyper.add_pendingsetup(result)
return result
def getinstancerepr(rtyper, classdef, default_flavor='gc'):
if classdef is None:
flavor = default_flavor
else:
flavor = getgcflavor(classdef)
try:
result = rtyper.instance_reprs[classdef, flavor]
except KeyError:
result = rtyper.type_system.rclass.buildinstancerepr(
rtyper, classdef, gcflavor=flavor)
rtyper.instance_reprs[classdef, flavor] = result
rtyper.add_pendingsetup(result)
return result
class MissingRTypeAttribute(TyperError):
pass
class AbstractClassRepr(Repr):
def __init__(self, rtyper, classdef):
self.rtyper = rtyper
self.classdef = classdef
def _setup_repr(self):
pass
def __repr__(self):
if self.classdef is None:
clsname = 'object'
else:
clsname = self.classdef.name
return '<ClassRepr for %s>' % (clsname,)
def compact_repr(self):
if self.classdef is None:
clsname = 'object'
else:
clsname = self.classdef.name
return 'ClassR %s' % (clsname,)
def convert_desc(self, desc):
subclassdef = desc.getuniqueclassdef()
if self.classdef is not None:
if self.classdef.commonbase(subclassdef) != self.classdef:
raise TyperError("not a subclass of %r: %r" % (
self.classdef.name, desc))
return getclassrepr(self.rtyper, subclassdef).getruntime()
def convert_const(self, value):
if not isinstance(value, (type, types.ClassType)):
raise TyperError("not a class: %r" % (value,))
bk = self.rtyper.annotator.bookkeeper
return self.convert_desc(bk.getdesc(value))
def prepare_method(self, s_value):
# special-casing for methods:
# if s_value is SomePBC([MethodDescs...])
# return a PBC representing the underlying functions
if isinstance(s_value, annmodel.SomePBC):
if not s_value.isNone() and s_value.getKind() == description.MethodDesc:
s_value = self.classdef.lookup_filter(s_value)
funcdescs = [mdesc.funcdesc for mdesc in s_value.descriptions]
return annmodel.SomePBC(funcdescs)
return None # not a method
def get_ll_eq_function(self):
return None
def get_type_repr(rtyper):
return getclassrepr(rtyper, None)
# ____________________________________________________________
class __extend__(annmodel.SomeInstance):
def rtyper_makerepr(self, rtyper):
return getinstancerepr(rtyper, self.classdef)
def rtyper_makekey(self):
return self.__class__, self.classdef
class AbstractInstanceRepr(Repr):
def __init__(self, rtyper, classdef):
self.rtyper = rtyper
self.classdef = classdef
def _setup_repr(self):
pass
def __repr__(self):
if self.classdef is None:
clsname = 'object'
else:
clsname = self.classdef.name
return '<InstanceRepr for %s>' % (clsname,)
def compact_repr(self):
if self.classdef is None:
clsname = 'object'
else:
clsname = self.classdef.name
return 'InstanceR %s' % (clsname,)
def _setup_repr_final(self):
pass
def new_instance(self, llops, classcallhop=None):
raise NotImplementedError
def convert_const(self, value):
if value is None:
return self.null_instance()
if isinstance(value, types.MethodType):
value = value.im_self # bound method -> instance
bk = self.rtyper.annotator.bookkeeper
try:
classdef = bk.getuniqueclassdef(value.__class__)
except KeyError:
raise TyperError("no classdef: %r" % (value.__class__,))
if classdef != self.classdef:
# if the class does not match exactly, check that 'value' is an
# instance of a subclass and delegate to that InstanceRepr
if classdef.commonbase(self.classdef) != self.classdef:
raise TyperError("not an instance of %r: %r" % (
self.classdef.name, value))
rinstance = getinstancerepr(self.rtyper, classdef)
result = rinstance.convert_const(value)
return self.upcast(result)
# common case
return self.convert_const_exact(value)
def convert_const_exact(self, value):
try:
return self.prebuiltinstances[id(value)][1]
except KeyError:
self.setup()
result = self.create_instance()
self.prebuiltinstances[id(value)] = value, result
self.initialize_prebuilt_instance(value, self.classdef, result)
return result
def get_reusable_prebuilt_instance(self):
"Get a dummy prebuilt instance. Multiple calls reuse the same one."
try:
return self._reusable_prebuilt_instance
except AttributeError:
self.setup()
result = self.create_instance()
self._reusable_prebuilt_instance = result
self.initialize_prebuilt_instance(Ellipsis, self.classdef, result)
return result
def rtype_type(self, hop):
raise NotImplementedError
def rtype_getattr(self, hop):
raise NotImplementedError
def rtype_setattr(self, hop):
raise NotImplementedError
def rtype_is_true(self, hop):
raise NotImplementedError
def ll_str(self, i):
raise NotImplementedError
def get_ll_eq_function(self):
return None # defaults to compare by identity ('==' on pointers)
def can_ll_be_null(self, s_value):
return s_value.can_be_none()
# ____________________________________________________________
def rtype_new_instance(rtyper, classdef, llops, classcallhop=None):
rinstance = getinstancerepr(rtyper, classdef)
return rinstance.new_instance(llops, classcallhop)
| Python |
import weakref
import UserDict
from pypy.tool.uid import Hashable
class AutoRegisteringType(type):
def __init__(selfcls, name, bases, dict):
super(AutoRegisteringType, selfcls).__init__(selfcls,
name, bases, dict)
if '_about_' in dict:
selfcls._register_value(dict['_about_'])
del selfcls._about_ # avoid keeping a ref
if '_type_' in dict:
selfcls._register_type(dict['_type_'])
del selfcls._type_
if '_metatype_' in dict:
selfcls._register_metatype(dict['_metatype_'])
del selfcls._metatype_
def _register(selfcls, dict, key):
if isinstance(key, tuple):
for k in key:
selfcls._register(dict, k)
else:
for basecls in selfcls.__mro__:
if '_condition_' in basecls.__dict__:
cond = basecls.__dict__['_condition_']
break
else:
cond = None
try:
family = dict[key]
except KeyError:
family = dict[key] = ClassFamily()
family.add(selfcls, cond)
def _register_value(selfcls, key):
selfcls._register(EXT_REGISTRY_BY_VALUE, key)
def _register_type(selfcls, key):
selfcls._register(EXT_REGISTRY_BY_TYPE, key)
def _register_metatype(selfcls, key):
selfcls._register(EXT_REGISTRY_BY_METATYPE, key)
class ClassFamily(object):
def __init__(self):
self.default = None
self.conditionals = []
def add(self, cls, cond=None):
if cond is None:
assert self.default is None, (
"duplicate extregistry entry %r" % (cls,))
self.default = cls
else:
self.conditionals.append((cls, cond))
def match(self, config):
if config is not None:
matches = [cls for cls, cond in self.conditionals
if cond(config)]
if matches:
assert len(matches) == 1, (
"multiple extregistry matches: %r" % (matches,))
return matches[0]
if self.default:
return self.default
raise KeyError("no default extregistry entry")
class ExtRegistryEntry(object):
__metaclass__ = AutoRegisteringType
def __init__(self, type, instance=None):
self.type = type
self.instance = instance
# structural equality, and trying hard to be hashable: Entry instances
# are used as keys to map annotations to Reprs in the rtyper.
# Warning, it's based on only 'type' and 'instance'.
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.type == other.type and
self.instance == other.instance)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash((self.__class__, self.type, Hashable(self.instance)))
def compute_annotation_bk(self, bk):
self.bookkeeper = bk
return self.compute_annotation()
def compute_annotation(self):
# callers should always use compute_annotation_bk()!
# default implementation useful for built-in functions,
# can be overriden.
func = self.instance
assert func is not None
from pypy.annotation import model as annmodel
analyser = self.compute_result_annotation
methodname = getattr(func, '__name__', None)
return annmodel.SomeBuiltin(analyser, methodname=methodname)
def compute_result_annotation(self, *args_s, **kwds_s):
# default implementation for built-in functions with a constant
# result annotation, can be overriden
return self.s_result_annotation
# ____________________________________________________________
class FlexibleWeakDict(UserDict.DictMixin):
"""A WeakKeyDictionary that accepts more or less anything as keys:
weakly referenceable objects or not, hashable objects or not.
"""
def __init__(self):
self._regdict = {}
self._weakdict = weakref.WeakKeyDictionary()
self._iddict = {}
def ref(self, key):
try:
hash(key)
except TypeError:
return self._iddict, Hashable(key) # key is not hashable
try:
weakref.ref(key)
except TypeError:
return self._regdict, key # key cannot be weakly ref'ed
else:
return self._weakdict, key # normal case
def __getitem__(self, key):
d, key = self.ref(key)
return d[key]
def __setitem__(self, key, value):
d, key = self.ref(key)
d[key] = value
def __delitem__(self, key):
d, key = self.ref(key)
del d[key]
def keys(self):
return (self._regdict.keys() +
self._weakdict.keys() +
[hashable.value for hashable in self._iddict])
EXT_REGISTRY_BY_VALUE = FlexibleWeakDict()
EXT_REGISTRY_BY_TYPE = weakref.WeakKeyDictionary()
EXT_REGISTRY_BY_METATYPE = weakref.WeakKeyDictionary()
# ____________________________________________________________
# Public interface to access the registry
def _lookup_type_cls(tp, config):
try:
return EXT_REGISTRY_BY_TYPE[tp].match(config)
except (KeyError, TypeError):
return EXT_REGISTRY_BY_METATYPE[type(tp)].match(config)
def lookup_type(tp, config=None):
Entry = _lookup_type_cls(tp, config)
return Entry(tp)
def is_registered_type(tp, config=None):
try:
_lookup_type_cls(tp, config)
except KeyError:
return False
return True
def _lookup_cls(instance, config):
try:
return EXT_REGISTRY_BY_VALUE[instance].match(config)
except (KeyError, TypeError):
return _lookup_type_cls(type(instance), config)
def lookup(instance, config=None):
Entry = _lookup_cls(instance, config)
return Entry(type(instance), instance)
def is_registered(instance, config=None):
try:
_lookup_cls(instance, config)
except KeyError:
return False
return True
| Python |
from pypy.annotation.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.objspace.flow.model import Constant
from pypy.rpython.lltypesystem import lltype, rclass, llmemory
from pypy.rpython import rint, raddress
from pypy.rlib import rarithmetic, rstack, objectmodel
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import Repr, IntegerRepr, inputconst
from pypy.rpython.rrange import rtype_builtin_range, rtype_builtin_xrange
from pypy.rpython import rstr
from pypy.rpython import rptr
from pypy.rpython.robject import pyobj_repr
from pypy.tool import sourcetools
from pypy.rpython import extregistry
class __extend__(annmodel.SomeBuiltin):
def rtyper_makerepr(self, rtyper):
if self.s_self is None:
# built-in function case
if not self.is_constant():
raise TyperError("non-constant built-in function!")
return BuiltinFunctionRepr(self.const)
else:
# built-in method case
assert self.methodname is not None
result = BuiltinMethodRepr(rtyper, self.s_self, self.methodname)
if result.self_repr == pyobj_repr:
return pyobj_repr # special case: methods of 'PyObject*'
else:
return result
def rtyper_makekey(self):
if self.s_self is None:
# built-in function case
const = getattr(self, 'const', None)
if extregistry.is_registered(const):
const = extregistry.lookup(const)
return self.__class__, const
else:
# built-in method case
# NOTE: we hash by id of self.s_self here. This appears to be
# necessary because it ends up in hop.args_s[0] in the method call,
# and there is no telling what information the called
# rtype_method_xxx() will read from that hop.args_s[0].
# See test_method_join in test_rbuiltin.
# There is no problem with self.s_self being garbage-collected and
# its id reused, because the BuiltinMethodRepr keeps a reference
# to it.
return (self.__class__, self.methodname, id(self.s_self))
def call_args_expand(hop, takes_kwds = True):
hop = hop.copy()
from pypy.interpreter.argument import Arguments
arguments = Arguments.fromshape(None, hop.args_s[1].const, # shape
range(hop.nb_args-2))
if arguments.w_starstararg is not None:
raise TyperError("**kwds call not implemented")
if arguments.w_stararg is not None:
# expand the *arg in-place -- it must be a tuple
from pypy.rpython.rtuple import AbstractTupleRepr
if arguments.w_stararg != hop.nb_args - 3:
raise TyperError("call pattern too complex")
hop.nb_args -= 1
v_tuple = hop.args_v.pop()
s_tuple = hop.args_s.pop()
r_tuple = hop.args_r.pop()
if not isinstance(r_tuple, AbstractTupleRepr):
raise TyperError("*arg must be a tuple")
for i in range(len(r_tuple.items_r)):
v_item = r_tuple.getitem_internal(hop.llops, v_tuple, i)
hop.nb_args += 1
hop.args_v.append(v_item)
hop.args_s.append(s_tuple.items[i])
hop.args_r.append(r_tuple.items_r[i])
kwds = arguments.kwds_w or {}
if not takes_kwds and kwds:
raise TyperError("kwds args not supported")
# prefix keyword arguments with 'i_'
kwds_i = {}
for key, index in kwds.items():
kwds_i['i_'+key] = index
return hop, kwds_i
class BuiltinFunctionRepr(Repr):
lowleveltype = lltype.Void
def __init__(self, builtinfunc):
self.builtinfunc = builtinfunc
def findbltintyper(self, rtyper):
"Find the function to use to specialize calls to this built-in func."
try:
return BUILTIN_TYPER[self.builtinfunc]
except (KeyError, TypeError):
pass
try:
return rtyper.type_system.rbuiltin.BUILTIN_TYPER[self.builtinfunc]
except (KeyError, TypeError):
pass
if extregistry.is_registered(self.builtinfunc):
entry = extregistry.lookup(self.builtinfunc)
return entry.specialize_call
raise TyperError("don't know about built-in function %r" % (
self.builtinfunc,))
def rtype_simple_call(self, hop):
bltintyper = self.findbltintyper(hop.rtyper)
hop2 = hop.copy()
hop2.r_s_popfirstarg()
return bltintyper(hop2)
def rtype_call_args(self, hop):
# calling a built-in function with keyword arguments:
# mostly for rpython.objectmodel.hint() and for constructing
# rctypes structures
hop, kwds_i = call_args_expand(hop)
bltintyper = self.findbltintyper(hop.rtyper)
hop2 = hop.copy()
hop2.r_s_popfirstarg()
hop2.r_s_popfirstarg()
# the RPython-level keyword args are passed with an 'i_' prefix and
# the corresponding value is an *index* in the hop2 arguments,
# to be used with hop.inputarg(arg=..)
return bltintyper(hop2, **kwds_i)
class BuiltinMethodRepr(Repr):
def __init__(self, rtyper, s_self, methodname):
self.s_self = s_self
self.self_repr = rtyper.getrepr(s_self)
self.methodname = methodname
# methods of a known name are implemented as just their 'self'
self.lowleveltype = self.self_repr.lowleveltype
def convert_const(self, obj):
return self.self_repr.convert_const(get_builtin_method_self(obj))
def rtype_simple_call(self, hop):
# methods: look up the rtype_method_xxx()
name = 'rtype_method_' + self.methodname
try:
bltintyper = getattr(self.self_repr, name)
except AttributeError:
raise TyperError("missing %s.%s" % (
self.self_repr.__class__.__name__, name))
# hack based on the fact that 'lowleveltype == self_repr.lowleveltype'
hop2 = hop.copy()
assert hop2.args_r[0] is self
if isinstance(hop2.args_v[0], Constant):
c = hop2.args_v[0].value # get object from bound method
c = get_builtin_method_self(c)
hop2.args_v[0] = Constant(c)
hop2.args_s[0] = self.s_self
hop2.args_r[0] = self.self_repr
return bltintyper(hop2)
class __extend__(pairtype(BuiltinMethodRepr, BuiltinMethodRepr)):
def convert_from_to((r_from, r_to), v, llops):
# convert between two MethodReprs only if they are about the same
# methodname. (Useful for the case r_from.s_self == r_to.s_self but
# r_from is not r_to.) See test_rbuiltin.test_method_repr.
if r_from.methodname != r_to.methodname:
return NotImplemented
return llops.convertvar(v, r_from.self_repr, r_to.self_repr)
def parse_kwds(hop, *argspec_i_r):
lst = [i for (i, r) in argspec_i_r if i is not None]
lst.sort()
if lst != range(hop.nb_args - len(lst), hop.nb_args):
raise TyperError("keyword args are expected to be at the end of "
"the 'hop' arg list")
result = []
for i, r in argspec_i_r:
if i is not None:
if r is None:
r = hop.args_r[i]
result.append(hop.inputarg(r, arg=i))
else:
result.append(None)
hop.nb_args -= len(lst)
return result
def get_builtin_method_self(x):
try:
return x.__self__ # on top of CPython
except AttributeError:
return x.im_self # on top of PyPy
# ____________________________________________________________
def rtype_builtin_bool(hop):
assert hop.nb_args == 1
return hop.args_r[0].rtype_is_true(hop)
def rtype_builtin_int(hop):
if isinstance(hop.args_s[0], annmodel.SomeString):
assert 1 <= hop.nb_args <= 2
return hop.args_r[0].rtype_int(hop)
assert hop.nb_args == 1
return hop.args_r[0].rtype_int(hop)
def rtype_builtin_float(hop):
assert hop.nb_args == 1
return hop.args_r[0].rtype_float(hop)
def rtype_builtin_chr(hop):
assert hop.nb_args == 1
return hop.args_r[0].rtype_chr(hop)
def rtype_builtin_unichr(hop):
assert hop.nb_args == 1
return hop.args_r[0].rtype_unichr(hop)
def rtype_builtin_list(hop):
return hop.args_r[0].rtype_bltn_list(hop)
#def rtype_builtin_range(hop): see rrange.py
#def rtype_builtin_xrange(hop): see rrange.py
#def rtype_r_dict(hop): see rdict.py
def rtype_intmask(hop):
hop.exception_cannot_occur()
vlist = hop.inputargs(lltype.Signed)
return vlist[0]
def rtype_builtin_min(hop):
v1, v2 = hop.inputargs(hop.r_result, hop.r_result)
return hop.gendirectcall(ll_min, v1, v2)
def ll_min(i1, i2):
if i1 < i2:
return i1
return i2
def rtype_builtin_max(hop):
v1, v2 = hop.inputargs(hop.r_result, hop.r_result)
return hop.gendirectcall(ll_max, v1, v2)
def ll_max(i1, i2):
if i1 > i2:
return i1
return i2
def rtype_Exception__init__(hop):
pass
def rtype_object__init__(hop):
pass
def rtype_OSError__init__(hop):
if hop.nb_args == 2:
raise TyperError("OSError() should not be called with "
"a single argument")
if hop.nb_args >= 3:
v_self = hop.args_v[0]
r_self = hop.args_r[0]
v_errno = hop.inputarg(lltype.Signed, arg=1)
r_self.setfield(v_self, 'errno', v_errno, hop.llops)
def rtype_we_are_translated(hop):
hop.exception_cannot_occur()
return hop.inputconst(lltype.Bool, True)
def rtype_yield_current_frame_to_caller(hop):
return hop.genop('yield_current_frame_to_caller', [],
resulttype=hop.r_result)
def rtype_hlinvoke(hop):
_, s_repr = hop.r_s_popfirstarg()
r_callable = s_repr.const
r_func, nimplicitarg = r_callable.get_r_implfunc()
s_callable = r_callable.get_s_callable()
nbargs = len(hop.args_s) - 1 + nimplicitarg
s_sigs = r_func.get_s_signatures((nbargs, (), False, False))
if len(s_sigs) != 1:
raise TyperError("cannot hlinvoke callable %r with not uniform"
"annotations: %r" % (r_callable,
s_sigs))
args_s, s_ret = s_sigs[0]
rinputs = [hop.rtyper.getrepr(s_obj) for s_obj in args_s]
rresult = hop.rtyper.getrepr(s_ret)
args_s = args_s[nimplicitarg:]
rinputs = rinputs[nimplicitarg:]
new_args_r = [r_callable] + rinputs
for i in range(len(new_args_r)):
assert hop.args_r[i].lowleveltype == new_args_r[i].lowleveltype
hop.args_r = new_args_r
hop.args_s = [s_callable] + args_s
hop.s_result = s_ret
assert hop.r_result.lowleveltype == rresult.lowleveltype
hop.r_result = rresult
return hop.dispatch()
# collect all functions
import __builtin__, exceptions
BUILTIN_TYPER = {}
for name, value in globals().items():
if name.startswith('rtype_builtin_'):
original = getattr(__builtin__, name[14:])
BUILTIN_TYPER[original] = value
BUILTIN_TYPER[getattr(OSError.__init__, 'im_func', OSError.__init__)] = (
rtype_OSError__init__)
BUILTIN_TYPER[object.__init__] = rtype_object__init__
# annotation of low-level types
def rtype_malloc(hop, i_flavor=None, i_extra_args=None, i_zero=None):
assert hop.args_s[0].is_constant()
vlist = [hop.inputarg(lltype.Void, arg=0)]
opname = 'malloc'
v_flavor, v_extra_args, v_zero = parse_kwds(hop, (i_flavor, lltype.Void),
(i_extra_args, None),
(i_zero, None))
if v_flavor is not None:
vlist.insert(0, v_flavor)
opname = 'flavored_' + opname
if i_zero is not None:
assert i_extra_args is i_flavor is None
opname = 'zero_' + opname
if hop.nb_args == 2:
vlist.append(hop.inputarg(lltype.Signed, arg=1))
opname += '_varsize'
if v_extra_args is not None:
# items of the v_extra_args tuple become additional args to the op
from pypy.rpython.rtuple import AbstractTupleRepr
r_tup = hop.args_r[i_extra_args]
assert isinstance(r_tup, AbstractTupleRepr)
for n, r in enumerate(r_tup.items_r):
v = r_tup.getitem(hop.llops, v_extra_args, n)
vlist.append(v)
return hop.genop(opname, vlist, resulttype = hop.r_result.lowleveltype)
def rtype_free(hop, i_flavor):
assert i_flavor == 1
hop.exception_cannot_occur()
vlist = hop.inputargs(hop.args_r[0], lltype.Void)
vlist.reverse() # just for confusion
hop.genop('flavored_free', vlist)
def rtype_const_result(hop):
return hop.inputconst(hop.r_result.lowleveltype, hop.s_result.const)
def rtype_cast_pointer(hop):
assert hop.args_s[0].is_constant()
assert isinstance(hop.args_r[1], rptr.PtrRepr)
v_type, v_input = hop.inputargs(lltype.Void, hop.args_r[1])
hop.exception_cannot_occur()
return hop.genop('cast_pointer', [v_input], # v_type implicit in r_result
resulttype = hop.r_result.lowleveltype)
def rtype_cast_opaque_ptr(hop):
assert hop.args_s[0].is_constant()
assert isinstance(hop.args_r[1], rptr.PtrRepr)
v_type, v_input = hop.inputargs(lltype.Void, hop.args_r[1])
hop.exception_cannot_occur()
return hop.genop('cast_opaque_ptr', [v_input], # v_type implicit in r_result
resulttype = hop.r_result.lowleveltype)
def rtype_direct_fieldptr(hop):
assert isinstance(hop.args_r[0], rptr.PtrRepr)
assert hop.args_s[1].is_constant()
vlist = hop.inputargs(hop.args_r[0], lltype.Void)
hop.exception_cannot_occur()
return hop.genop('direct_fieldptr', vlist,
resulttype=hop.r_result.lowleveltype)
def rtype_direct_arrayitems(hop):
assert isinstance(hop.args_r[0], rptr.PtrRepr)
vlist = hop.inputargs(hop.args_r[0])
hop.exception_cannot_occur()
return hop.genop('direct_arrayitems', vlist,
resulttype=hop.r_result.lowleveltype)
def rtype_direct_ptradd(hop):
assert isinstance(hop.args_r[0], rptr.PtrRepr)
vlist = hop.inputargs(hop.args_r[0], lltype.Signed)
hop.exception_cannot_occur()
return hop.genop('direct_ptradd', vlist,
resulttype=hop.r_result.lowleveltype)
def rtype_cast_primitive(hop):
assert hop.args_s[0].is_constant()
TGT = hop.args_s[0].const
v_type, v_value = hop.inputargs(lltype.Void, hop.args_r[1])
return gen_cast(hop.llops, TGT, v_value)
_cast_to_Signed = {
lltype.Signed: None,
lltype.Bool: 'cast_bool_to_int',
lltype.Char: 'cast_char_to_int',
lltype.UniChar: 'cast_unichar_to_int',
lltype.Float: 'cast_float_to_int',
lltype.Unsigned: 'cast_uint_to_int',
}
_cast_from_Signed = {
lltype.Signed: None,
lltype.Bool: 'int_is_true',
lltype.Char: 'cast_int_to_char',
lltype.UniChar: 'cast_int_to_unichar',
lltype.Float: 'cast_int_to_float',
lltype.Unsigned: 'cast_int_to_uint',
}
def gen_cast(llops, TGT, v_value):
ORIG = v_value.concretetype
if ORIG == TGT:
return v_value
if (isinstance(TGT, lltype.Primitive) and
isinstance(ORIG, lltype.Primitive)):
if ORIG in _cast_to_Signed and TGT in _cast_from_Signed:
op = _cast_to_Signed[ORIG]
if op:
v_value = llops.genop(op, [v_value], resulttype=lltype.Signed)
op = _cast_from_Signed[TGT]
if op:
v_value = llops.genop(op, [v_value], resulttype=TGT)
return v_value
else:
# use the generic operation if there is no alternative
return llops.genop('cast_primitive', [v_value], resulttype=TGT)
elif isinstance(TGT, lltype.Ptr):
if isinstance(ORIG, lltype.Ptr):
if (isinstance(TGT.TO, lltype.OpaqueType) or
isinstance(ORIG.TO, lltype.OpaqueType)):
return llops.genop('cast_opaque_ptr', [v_value],
resulttype = TGT)
else:
return llops.genop('cast_pointer', [v_value], resulttype = TGT)
elif ORIG == llmemory.Address:
return llops.genop('cast_adr_to_ptr', [v_value], resulttype = TGT)
elif TGT == llmemory.Address and isinstance(ORIG, lltype.Ptr):
return llops.genop('cast_ptr_to_adr', [v_value], resulttype = TGT)
raise TypeError("don't know how to cast from %r to %r" % (ORIG, TGT))
def rtype_cast_ptr_to_int(hop):
assert isinstance(hop.args_r[0], rptr.PtrRepr)
vlist = hop.inputargs(hop.args_r[0])
hop.exception_cannot_occur()
return hop.genop('cast_ptr_to_int', vlist,
resulttype = lltype.Signed)
def rtype_cast_int_to_ptr(hop):
assert hop.args_s[0].is_constant()
v_type, v_input = hop.inputargs(lltype.Void, lltype.Signed)
hop.exception_cannot_occur()
return hop.genop('cast_int_to_ptr', [v_input],
resulttype = hop.r_result.lowleveltype)
def rtype_runtime_type_info(hop):
assert isinstance(hop.args_r[0], rptr.PtrRepr)
vlist = hop.inputargs(hop.args_r[0])
return hop.genop('runtime_type_info', vlist,
resulttype = hop.r_result.lowleveltype)
BUILTIN_TYPER[lltype.malloc] = rtype_malloc
BUILTIN_TYPER[lltype.free] = rtype_free
BUILTIN_TYPER[lltype.cast_primitive] = rtype_cast_primitive
BUILTIN_TYPER[lltype.cast_pointer] = rtype_cast_pointer
BUILTIN_TYPER[lltype.cast_opaque_ptr] = rtype_cast_opaque_ptr
BUILTIN_TYPER[lltype.direct_fieldptr] = rtype_direct_fieldptr
BUILTIN_TYPER[lltype.direct_arrayitems] = rtype_direct_arrayitems
BUILTIN_TYPER[lltype.direct_ptradd] = rtype_direct_ptradd
BUILTIN_TYPER[lltype.cast_ptr_to_int] = rtype_cast_ptr_to_int
BUILTIN_TYPER[lltype.cast_int_to_ptr] = rtype_cast_int_to_ptr
BUILTIN_TYPER[lltype.typeOf] = rtype_const_result
BUILTIN_TYPER[lltype.nullptr] = rtype_const_result
BUILTIN_TYPER[lltype.getRuntimeTypeInfo] = rtype_const_result
BUILTIN_TYPER[lltype.Ptr] = rtype_const_result
BUILTIN_TYPER[lltype.runtime_type_info] = rtype_runtime_type_info
BUILTIN_TYPER[rarithmetic.intmask] = rtype_intmask
BUILTIN_TYPER[objectmodel.we_are_translated] = rtype_we_are_translated
BUILTIN_TYPER[rstack.yield_current_frame_to_caller] = (
rtype_yield_current_frame_to_caller)
BUILTIN_TYPER[objectmodel.hlinvoke] = rtype_hlinvoke
from pypy.rpython import extfunctable
def rnormalize(rtyper, r):
# this replaces char_repr with string_repr, because so far we have
# no external function expecting a char, but only external functions
# that happily crash if passed a char instead of a string
if r == rtyper.type_system.rstr.char_repr:
r = rtyper.type_system.rstr.string_repr
return r
def make_rtype_extfunc(extfuncinfo):
if extfuncinfo.ll_annotable:
def rtype_extfunc(hop):
ll_function = extfuncinfo.get_ll_function(hop.rtyper.type_system)
vars = hop.inputargs(*[rnormalize(hop.rtyper, r)
for r in hop.args_r])
hop.exception_is_here()
return hop.gendirectcall(ll_function, *vars)
else:
def rtype_extfunc(hop):
ll_function = extfuncinfo.get_ll_function(hop.rtyper.type_system)
resulttype = hop.r_result
vars = hop.inputargs(*[rnormalize(hop.rtyper, r)
for r in hop.args_r])
hop.exception_is_here()
return hop.llops.genexternalcall(ll_function.__name__, vars, resulttype=resulttype,
_callable = ll_function)
if extfuncinfo.func is not None:
rtype_extfunc = sourcetools.func_with_new_name(rtype_extfunc,
"rtype_extfunc_%s" % extfuncinfo.func.__name__)
return rtype_extfunc
def update_exttable():
"""import rtyping information for external functions
from the extfunctable.table into our own specific table
"""
for func, extfuncinfo in extfunctable.table.iteritems():
if func not in BUILTIN_TYPER:
BUILTIN_TYPER[func] = make_rtype_extfunc(extfuncinfo)
# Note: calls to declare() may occur after rbuiltin.py is first imported.
# We must track future changes to the extfunctable.
extfunctable.table_callbacks.append(update_exttable)
update_exttable()
# _________________________________________________________________
# memory addresses
from pypy.rpython.memory import lladdress
from pypy.rpython.lltypesystem import llmemory
def rtype_raw_malloc(hop):
v_size, = hop.inputargs(lltype.Signed)
return hop.genop('raw_malloc', [v_size], resulttype=llmemory.Address)
def rtype_raw_malloc_usage(hop):
v_size, = hop.inputargs(lltype.Signed)
hop.exception_cannot_occur()
return hop.genop('raw_malloc_usage', [v_size], resulttype=lltype.Signed)
def rtype_raw_free(hop):
v_addr, = hop.inputargs(llmemory.Address)
hop.exception_cannot_occur()
return hop.genop('raw_free', [v_addr])
def rtype_raw_memcopy(hop):
v_list = hop.inputargs(llmemory.Address, llmemory.Address, lltype.Signed)
return hop.genop('raw_memcopy', v_list)
def rtype_raw_memclear(hop):
v_list = hop.inputargs(llmemory.Address, lltype.Signed)
return hop.genop('raw_memclear', v_list)
BUILTIN_TYPER[lladdress.raw_malloc] = rtype_raw_malloc
BUILTIN_TYPER[lladdress.raw_malloc_usage] = rtype_raw_malloc_usage
BUILTIN_TYPER[lladdress.raw_free] = rtype_raw_free
BUILTIN_TYPER[lladdress.raw_memclear] = rtype_raw_memclear
BUILTIN_TYPER[lladdress.raw_memcopy] = rtype_raw_memcopy
BUILTIN_TYPER[llmemory.raw_malloc] = rtype_raw_malloc
BUILTIN_TYPER[llmemory.raw_malloc_usage] = rtype_raw_malloc_usage
BUILTIN_TYPER[llmemory.raw_free] = rtype_raw_free
BUILTIN_TYPER[llmemory.raw_memclear] = rtype_raw_memclear
BUILTIN_TYPER[llmemory.raw_memcopy] = rtype_raw_memcopy
def rtype_offsetof(hop):
TYPE, field = hop.inputargs(lltype.Void, lltype.Void)
return hop.inputconst(lltype.Signed,
llmemory.offsetof(TYPE.value, field.value))
BUILTIN_TYPER[llmemory.offsetof] = rtype_offsetof
# _________________________________________________________________
# non-gc objects
def rtype_free_non_gc_object(hop):
vinst, = hop.inputargs(hop.args_r[0])
flavor = hop.args_r[0].gcflavor
assert not flavor.startswith('gc')
cflavor = hop.inputconst(lltype.Void, flavor)
return hop.genop('flavored_free', [cflavor, vinst])
BUILTIN_TYPER[objectmodel.free_non_gc_object] = rtype_free_non_gc_object
# keepalive_until_here
def rtype_keepalive_until_here(hop):
for v in hop.args_v:
hop.genop('keepalive', [v], resulttype=lltype.Void)
return hop.inputconst(lltype.Void, None)
BUILTIN_TYPER[objectmodel.keepalive_until_here] = rtype_keepalive_until_here
def rtype_cast_ptr_to_adr(hop):
vlist = hop.inputargs(hop.args_r[0])
assert isinstance(vlist[0].concretetype, lltype.Ptr)
hop.exception_cannot_occur()
return hop.genop('cast_ptr_to_adr', vlist,
resulttype = llmemory.Address)
def rtype_cast_adr_to_ptr(hop):
assert isinstance(hop.args_r[0], raddress.AddressRepr)
adr, TYPE = hop.inputargs(hop.args_r[0], lltype.Void)
hop.exception_cannot_occur()
return hop.genop('cast_adr_to_ptr', [adr],
resulttype = TYPE.value)
def rtype_cast_adr_to_int(hop):
assert isinstance(hop.args_r[0], raddress.AddressRepr)
adr, = hop.inputargs(hop.args_r[0])
hop.exception_cannot_occur()
return hop.genop('cast_adr_to_int', [adr],
resulttype = lltype.Signed)
def rtype_cast_int_to_adr(hop):
v_input, = hop.inputargs(lltype.Signed)
hop.exception_cannot_occur()
return hop.genop('cast_int_to_adr', [v_input],
resulttype = llmemory.Address)
def rtype_cast_ptr_to_weakadr(hop):
vlist = hop.inputargs(hop.args_r[0])
assert isinstance(vlist[0].concretetype, lltype.Ptr)
hop.exception_cannot_occur()
return hop.genop('cast_ptr_to_weakadr', vlist,
resulttype = llmemory.WeakGcAddress)
def rtype_cast_weakadr_to_ptr(hop):
assert isinstance(hop.args_r[0], raddress.WeakGcAddressRepr)
adr, TYPE = hop.inputargs(hop.args_r[0], lltype.Void)
hop.exception_cannot_occur()
return hop.genop('cast_weakadr_to_ptr', [adr],
resulttype = TYPE.value)
BUILTIN_TYPER[llmemory.cast_ptr_to_adr] = rtype_cast_ptr_to_adr
BUILTIN_TYPER[llmemory.cast_adr_to_ptr] = rtype_cast_adr_to_ptr
BUILTIN_TYPER[llmemory.cast_adr_to_int] = rtype_cast_adr_to_int
BUILTIN_TYPER[llmemory.cast_int_to_adr] = rtype_cast_int_to_adr
BUILTIN_TYPER[llmemory.cast_ptr_to_weakadr] = rtype_cast_ptr_to_weakadr
BUILTIN_TYPER[llmemory.cast_weakadr_to_ptr] = rtype_cast_weakadr_to_ptr
| Python |
from pypy.annotation.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.objspace.flow.model import Constant
from pypy.rpython.lltypesystem import lltype
from pypy.rlib.rarithmetic import r_uint
from pypy.rlib.objectmodel import hlinvoke
from pypy.rpython import robject
from pypy.rlib import objectmodel
from pypy.rpython import rmodel
def dum_keys(): pass
def dum_values(): pass
def dum_items():pass
dum_variant = {"keys": dum_keys,
"values": dum_values,
"items": dum_items}
class __extend__(annmodel.SomeDict):
def rtyper_makerepr(self, rtyper):
dictkey = self.dictdef.dictkey
dictvalue = self.dictdef.dictvalue
s_key = dictkey .s_value
s_value = dictvalue.s_value
if (s_key.__class__ is annmodel.SomeObject and s_key.knowntype == object and
s_value.__class__ is annmodel.SomeObject and s_value.knowntype == object):
return robject.pyobj_repr
else:
if dictkey.custom_eq_hash:
custom_eq_hash = lambda: (rtyper.getrepr(dictkey.s_rdict_eqfn),
rtyper.getrepr(dictkey.s_rdict_hashfn))
else:
custom_eq_hash = None
return rtyper.type_system.rdict.DictRepr(rtyper,
lambda: rtyper.getrepr(s_key),
lambda: rtyper.getrepr(s_value),
dictkey,
dictvalue,
custom_eq_hash)
def rtyper_makekey(self):
self.dictdef.dictkey .dont_change_any_more = True
self.dictdef.dictvalue.dont_change_any_more = True
return (self.__class__, self.dictdef.dictkey, self.dictdef.dictvalue)
class AbstractDictRepr(rmodel.Repr):
def pickrepr(self, item_repr):
if self.custom_eq_hash:
return item_repr, item_repr
else:
return self._externalvsinternal(self.rtyper, item_repr)
def pickkeyrepr(self, key_repr):
external, internal = self.pickrepr(key_repr)
if external != internal:
internal = external
while not self.rtyper.needs_hash_support(internal.classdef):
internal = internal.rbase
return external, internal
def compact_repr(self):
return 'DictR %s %s' % (self.key_repr.compact_repr(), self.value_repr.compact_repr())
def recast_value(self, llops, v):
return llops.convertvar(v, self.value_repr, self.external_value_repr)
def recast_key(self, llops, v):
return llops.convertvar(v, self.key_repr, self.external_key_repr)
def rtype_newdict(hop):
hop.inputargs() # no arguments expected
r_dict = hop.r_result
if r_dict == robject.pyobj_repr: # special case: SomeObject: SomeObject dicts!
cdict = hop.inputconst(robject.pyobj_repr, dict)
return hop.genop('simple_call', [cdict], resulttype = robject.pyobj_repr)
cDICT = hop.inputconst(lltype.Void, r_dict.DICT)
v_result = hop.gendirectcall(hop.rtyper.type_system.rdict.ll_newdict, cDICT)
return v_result
class AbstractDictIteratorRepr(rmodel.IteratorRepr):
def newiter(self, hop):
v_dict, = hop.inputargs(self.r_dict)
citerptr = hop.inputconst(lltype.Void, self.lowleveltype)
return hop.gendirectcall(self.ll_dictiter, citerptr, v_dict)
def _next_implicit_exceptions(self, hop):
hop.has_implicit_exception(StopIteration)
def rtype_next(self, hop):
variant = self.variant
v_iter, = hop.inputargs(self)
v_func = hop.inputconst(lltype.Void, dum_variant[self.variant])
if variant in ('keys', 'values'):
c1 = hop.inputconst(lltype.Void, None)
else:
c1 = hop.inputconst(lltype.Void, hop.r_result.lowleveltype)
self._next_implicit_exceptions(hop) # record that we know about it
hop.exception_is_here()
v = hop.gendirectcall(self.ll_dictnext, v_iter, v_func, c1)
if variant == 'keys':
return self.r_dict.recast_key(hop.llops, v)
elif variant == 'values':
return self.r_dict.recast_value(hop.llops, v)
else:
return v
| Python |
#!/usr/bin/env python
import ctypes
import py
def primitive_pointer_repr(tp_s):
return 'lltype.Ptr(lltype.FixedSizeArray(%s, 1))' % tp_s
# XXX any automatic stuff here?
SIMPLE_TYPE_MAPPING = {
ctypes.c_ubyte : 'rffi.UCHAR',
ctypes.c_byte : 'rffi.CHAR',
ctypes.c_char : 'rffi.CHAR',
ctypes.c_int8 : 'rffi.CHAR',
ctypes.c_ushort : 'rffi.USHORT',
ctypes.c_short : 'rffi.SHORT',
ctypes.c_uint16 : 'rffi.USHORT',
ctypes.c_int16 : 'rffi.SHORT',
ctypes.c_int : 'rffi.INT',
ctypes.c_uint : 'rffi.UINT',
ctypes.c_int32 : 'rffi.INT',
ctypes.c_uint32 : 'rffi.UINT',
#ctypes.c_long : 'rffi.LONG', # same as c_int..
#ctypes.c_ulong : 'rffi.ULONG',
ctypes.c_longlong : 'rffi.LONGLONG',
ctypes.c_ulonglong : 'rffi.ULONGLONG',
ctypes.c_int64 : 'rffi.LONGLONG',
ctypes.c_uint64 : 'rffi.ULONGLONG',
ctypes.c_voidp : 'rffi.VOIDP',
None : 'rffi.lltype.Void', # XXX make a type in rffi
ctypes.c_char_p : 'rffi.CCHARP',
ctypes.c_double : 'rffi.lltype.Float', # XXX make a type in rffi
}
class RffiSource(object):
def __init__(self, structs=None, source=None, includes=[], libraries=[],
include_dirs=[]):
# set of ctypes structs
if structs is None:
self.structs = set()
else:
self.structs = structs
if source is None:
self.source = py.code.Source()
else:
self.source = source
includes = includes and "includes=%s, " % repr(tuple(includes)) or ''
libraries = libraries and "libraries=%s, " % repr(tuple(libraries)) or ''
include_dirs = include_dirs and \
"include_dirs=%s, " % repr(tuple(include_dirs)) or ''
self.extra_args = includes+libraries+include_dirs
def __str__(self):
return str(self.source)
def __add__(self, other):
structs = self.structs.copy()
structs.update(other.structs)
source = py.code.Source(self.source, other.source)
return RffiSource(structs, source)
def __iadd__(self, other):
self.structs.update(other.structs)
self.source = py.code.Source(self.source, other.source)
return self
def proc_struct(self, tp):
name = tp.__name__
if tp not in self.structs:
fields = ["('%s', %s), " % (name_, self.proc_tp(field_tp))
for name_, field_tp in tp._fields_]
fields_repr = ''.join(fields)
self.structs.add(tp)
src = py.code.Source(
"%s = lltype.Struct('%s', %s hints={'external':'C'})"%(
name, name, fields_repr))
self.source = py.code.Source(self.source, src)
return name
def proc_tp(self, tp):
try:
return SIMPLE_TYPE_MAPPING[tp]
except KeyError:
pass
if issubclass(tp, ctypes._Pointer):
if issubclass(tp._type_, ctypes._SimpleCData):
return "lltype.Ptr(lltype.Array(%s, hints={'nolength': True}))"\
% self.proc_tp(tp._type_)
return "lltype.Ptr(%s)" % self.proc_tp(tp._type_)
elif issubclass(tp, ctypes.Structure):
return self.proc_struct(tp)
raise NotImplementedError("Not implemented mapping for %s" % tp)
def proc_func(self, func):
print "proc_func", func
name = func.__name__
src = py.code.Source("""
%s = rffi.llexternal('%s', [%s], %s, %s)
"""%(name, name, ", ".join([self.proc_tp(arg) for arg in func.argtypes]),
self.proc_tp(func.restype), self.extra_args))
self.source = py.code.Source(self.source, src)
def proc_namespace(self, ns):
exempt = set(id(value) for value in ctypes.__dict__.values())
for key, value in ns.items():
if id(value) in exempt:
continue
if isinstance(value, ctypes._CFuncPtr):
print "func", key, value
try:
self.proc_func(value)
except NotImplementedError:
print "skipped:", value
#print value, value.__class__.__name__
| Python |
#!/usr/bin/env python
import ctypes
import py
def primitive_pointer_repr(tp_s):
return 'lltype.Ptr(lltype.FixedSizeArray(%s, 1))' % tp_s
# XXX any automatic stuff here?
SIMPLE_TYPE_MAPPING = {
ctypes.c_ubyte : 'rffi.UCHAR',
ctypes.c_byte : 'rffi.CHAR',
ctypes.c_char : 'rffi.CHAR',
ctypes.c_int8 : 'rffi.CHAR',
ctypes.c_ushort : 'rffi.USHORT',
ctypes.c_short : 'rffi.SHORT',
ctypes.c_uint16 : 'rffi.USHORT',
ctypes.c_int16 : 'rffi.SHORT',
ctypes.c_int : 'rffi.INT',
ctypes.c_uint : 'rffi.UINT',
ctypes.c_int32 : 'rffi.INT',
ctypes.c_uint32 : 'rffi.UINT',
#ctypes.c_long : 'rffi.LONG', # same as c_int..
#ctypes.c_ulong : 'rffi.ULONG',
ctypes.c_longlong : 'rffi.LONGLONG',
ctypes.c_ulonglong : 'rffi.ULONGLONG',
ctypes.c_int64 : 'rffi.LONGLONG',
ctypes.c_uint64 : 'rffi.ULONGLONG',
ctypes.c_voidp : 'rffi.VOIDP',
None : 'rffi.lltype.Void', # XXX make a type in rffi
ctypes.c_char_p : 'rffi.CCHARP',
ctypes.c_double : 'rffi.lltype.Float', # XXX make a type in rffi
}
class RffiSource(object):
def __init__(self, structs=None, source=None, includes=[], libraries=[],
include_dirs=[]):
# set of ctypes structs
if structs is None:
self.structs = set()
else:
self.structs = structs
if source is None:
self.source = py.code.Source()
else:
self.source = source
includes = includes and "includes=%s, " % repr(tuple(includes)) or ''
libraries = libraries and "libraries=%s, " % repr(tuple(libraries)) or ''
include_dirs = include_dirs and \
"include_dirs=%s, " % repr(tuple(include_dirs)) or ''
self.extra_args = includes+libraries+include_dirs
def __str__(self):
return str(self.source)
def __add__(self, other):
structs = self.structs.copy()
structs.update(other.structs)
source = py.code.Source(self.source, other.source)
return RffiSource(structs, source)
def __iadd__(self, other):
self.structs.update(other.structs)
self.source = py.code.Source(self.source, other.source)
return self
def proc_struct(self, tp):
name = tp.__name__
if tp not in self.structs:
fields = ["('%s', %s), " % (name_, self.proc_tp(field_tp))
for name_, field_tp in tp._fields_]
fields_repr = ''.join(fields)
self.structs.add(tp)
src = py.code.Source(
"%s = lltype.Struct('%s', %s hints={'external':'C'})"%(
name, name, fields_repr))
self.source = py.code.Source(self.source, src)
return name
def proc_tp(self, tp):
try:
return SIMPLE_TYPE_MAPPING[tp]
except KeyError:
pass
if issubclass(tp, ctypes._Pointer):
if issubclass(tp._type_, ctypes._SimpleCData):
return "lltype.Ptr(lltype.Array(%s, hints={'nolength': True}))"\
% self.proc_tp(tp._type_)
return "lltype.Ptr(%s)" % self.proc_tp(tp._type_)
elif issubclass(tp, ctypes.Structure):
return self.proc_struct(tp)
raise NotImplementedError("Not implemented mapping for %s" % tp)
def proc_func(self, func):
print "proc_func", func
name = func.__name__
src = py.code.Source("""
%s = rffi.llexternal('%s', [%s], %s, %s)
"""%(name, name, ", ".join([self.proc_tp(arg) for arg in func.argtypes]),
self.proc_tp(func.restype), self.extra_args))
self.source = py.code.Source(self.source, src)
def proc_namespace(self, ns):
exempt = set(id(value) for value in ctypes.__dict__.values())
for key, value in ns.items():
if id(value) in exempt:
continue
if isinstance(value, ctypes._CFuncPtr):
print "func", key, value
try:
self.proc_func(value)
except NotImplementedError:
print "skipped:", value
#print value, value.__class__.__name__
| Python |
from pypy.rpython.rmodel import Repr, inputconst
from pypy.rpython.rrange import AbstractRangeRepr
from pypy.rpython.rint import IntegerRepr
from pypy.rpython.rlist import AbstractBaseListRepr
from pypy.rpython.error import TyperError
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython.lltypesystem.lltype import \
GcArray, GcStruct, Signed, Ptr, Unsigned, malloc, Void
from pypy.annotation.model import SomeInteger
from pypy.rpython.numpy.aarray import SomeArray
from pypy.annotation.pairtype import pairtype
class ArrayRepr(Repr):
def __init__(self, rtyper, s_array):
self.s_value = s_array.get_item_type()
self.item_repr = rtyper.getrepr(self.s_value)
ITEM = self.item_repr.lowleveltype
ITEMARRAY = GcArray(ITEM)
self.ARRAY = Ptr(
GcStruct( "array",
# ("length", Signed),
("data", Ptr(ITEMARRAY))))
self.lowleveltype = self.ARRAY
def allocate_instance(self, llops, v_array):
c1 = inputconst(lltype.Void, self.lowleveltype.TO)
return llops.gendirectcall(ll_allocate, c1, v_array)
class __extend__(SomeArray):
def rtyper_makerepr(self, rtyper):
return ArrayRepr( rtyper, self )
def rtyper_makekey(self):
return self.__class__, self.knowntype
class __extend__(pairtype(ArrayRepr,ArrayRepr)):
def rtype_add((r_arr1,r_arr2), hop):
v_arr1, v_arr2 = hop.inputargs(r_arr1, r_arr2)
cARRAY = hop.inputconst(Void, hop.r_result.ARRAY.TO)
return hop.gendirectcall(ll_add, cARRAY, v_arr1, v_arr2)
class __extend__(pairtype(ArrayRepr,IntegerRepr)):
def rtype_setitem((r_arr,r_int), hop):
v_array, v_index, v_item = hop.inputargs(r_arr, Signed, r_arr.item_repr)
return hop.gendirectcall(ll_setitem, v_array, v_index, v_item)
def rtype_getitem((r_arr,r_int), hop):
v_array, v_index = hop.inputargs(r_arr, Signed)
return hop.gendirectcall(ll_getitem, v_array, v_index)
class __extend__(pairtype(AbstractBaseListRepr, ArrayRepr)):
def convert_from_to((r_lst, r_arr), v, llops):
if r_lst.listitem is None:
return NotImplemented
if r_lst.item_repr != r_arr.item_repr:
return NotImplemented
c1 = inputconst(lltype.Void, r_arr.lowleveltype.TO)
return llops.gendirectcall(ll_build_array, c1, v)
class __extend__(pairtype(AbstractRangeRepr, ArrayRepr)):
def convert_from_to((r_rng, r_arr), v, llops):
c1 = inputconst(lltype.Void, r_arr.lowleveltype.TO)
return llops.gendirectcall(ll_build_array, c1, v)
def ll_build_array(ARRAY, lst):
size = lst.ll_length()
array = malloc(ARRAY)
data = array.data = malloc(ARRAY.data.TO, size)
i = 0
while i < size:
data[i] = lst.ll_getitem_fast(i)
i += 1
return array
def ll_allocate(ARRAY, array):
new_array = malloc(ARRAY)
new_array.data = array.data
return new_array
def ll_setitem(l, index, item):
l.data[index] = item
def ll_getitem(l, index):
return l.data[index]
def ll_add(ARRAY, a1, a2):
size = len(a1.data)
if size != len(a2.data):
raise ValueError
array = malloc(ARRAY)
array.data = malloc(ARRAY.data.TO, size)
i = 0
while i < size:
array.data[i] = a1.data[i] + a2.data[i]
i += 1
return array
| Python |
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.annotation.pairtype import pairtype
from pypy.annotation.model import SomeExternalObject, SomeList, SomeImpossibleValue
from pypy.annotation.model import SomeInteger, SomeFloat, SomeString, SomeChar
from pypy.annotation.listdef import ListDef
from pypy.rpython.rctypes import rcarithmetic
from pypy.tool.error import AnnotatorError
import numpy
class SomeArray(SomeExternalObject):
"""Stands for an object from the numpy module."""
from pypy.rpython.rctypes import rcarithmetic
typecode_to_item = {
'b' : SomeInteger(knowntype=rcarithmetic.rcbyte),
'h' : SomeInteger(knowntype=rcarithmetic.rcshort),
'i' : SomeInteger(knowntype=rcarithmetic.rcint),
'l' : SomeInteger(knowntype=rcarithmetic.rclong),
'q' : SomeInteger(knowntype=rcarithmetic.rclonglong),
'B' : SomeInteger(knowntype=rcarithmetic.rcubyte),
'H' : SomeInteger(knowntype=rcarithmetic.rcushort),
'I' : SomeInteger(knowntype=rcarithmetic.rcuint),
'L' : SomeInteger(knowntype=rcarithmetic.rculong),
'Q' : SomeInteger(knowntype=rcarithmetic.rculonglong),
'f' : SomeFloat(), # XX single precision float XX
'd' : SomeFloat(),
}
def __init__(self, knowntype, typecode):
self.knowntype = knowntype
self.typecode = typecode
self.rank = 1
def can_be_none(self):
return True
def return_annotation(self):
"""Returns either 'self' or the annotation of the unwrapped version
of this ctype, following the logic used when ctypes operations
return a value.
"""
from pypy.rpython import extregistry
assert extregistry.is_registered_type(self.knowntype)
entry = extregistry.lookup_type(self.knowntype)
# special case for returning primitives or c_char_p
return getattr(entry, 's_return_trick', self)
def get_item_type(self):
return self.typecode_to_item[self.typecode]
class __extend__(pairtype(SomeArray, SomeArray)):
def add((s_arr1,s_arr2)):
# TODO: coerce the array types
return SomeArray(s_arr1.knowntype, s_arr1.typecode)
class __extend__(pairtype(SomeArray, SomeInteger)):
def setitem((s_cto, s_index), s_value):
pass
def getitem((s_cto, s_index)):
# TODO: higher ranked arrays have getitem returns SomeArray
return s_cto.get_item_type()
numpy_typedict = {
(SomeInteger, rcarithmetic.rcbyte) : 'b',
(SomeInteger, rcarithmetic.rcshort) : 'h',
(SomeInteger, rcarithmetic.rcint) : 'i',
(SomeInteger, rcarithmetic.rclong) : 'l',
(SomeInteger, int) : 'l',
(SomeInteger, rcarithmetic.rclonglong) : 'q',
(SomeInteger, rcarithmetic.rcubyte) : 'B',
(SomeInteger, rcarithmetic.rcushort) : 'H',
(SomeInteger, rcarithmetic.rcuint) : 'I',
(SomeInteger, rcarithmetic.rculong) : 'L',
(SomeInteger, rcarithmetic.rculonglong) : 'Q',
(SomeFloat, float) : 'f',
(SomeFloat, float) : 'd',
}
valid_typecodes='bhilqBHILQfd'
class CallEntry(ExtRegistryEntry):
"Annotation and rtyping of calls to numpy.array."
_about_ = numpy.array
def compute_result_annotation(self, arg_list, *args_s, **kwds_s):
if not isinstance(arg_list, SomeList):
raise AnnotatorError("numpy.array expects SomeList")
# First guess type from input list
listitem = arg_list.listdef.listitem
key = type(listitem.s_value), listitem.s_value.knowntype
typecode = numpy_typedict.get( key, None )
# now see if the dtype arg over-rides the typecode
dtype = None
if len(args_s)>0:
dtype = args_s[0]
if "dtype" in kwds_s:
dtype = kwds_s["dtype"]
if isinstance(dtype,SomeChar) and dtype.is_constant():
typecode = dtype.const
dtype = None
if dtype is not None:
raise AnnotatorError("dtype is not a valid type specification")
if typecode is None or typecode not in valid_typecodes:
raise AnnotatorError("List item type not supported")
knowntype = numpy.ndarray
return SomeArray(knowntype, typecode)
def specialize_call(self, hop):
r_array = hop.r_result
[v_lst] = hop.inputargs(r_array)
v_result = r_array.allocate_instance(hop.llops, v_lst)
return v_result
class NumpyObjEntry(ExtRegistryEntry):
"Annotation and rtyping of numpy array instances."
_type_ = numpy.ndarray
def get_repr(self, rtyper, s_array):
from pypy.rpython.numpy.rarray import ArrayRepr
return ArrayRepr(rtyper, s_array)
# Importing for side effect of registering types with extregistry
import pypy.rpython.numpy.aarray
| Python |
#empty
| Python |
# Base classes describing annotation and rtyping
from pypy.annotation.model import SomeCTypesObject
from pypy.rpython import extregistry
from pypy.rpython.extregistry import ExtRegistryEntry
# Importing for side effect of registering types with extregistry
import pypy.rpython.numpy.aarray
| Python |
import py
class Directory(py.test.collect.Directory):
def run(self):
try:
import numpy
except ImportError:
py.test.skip("these tests need numpy installed")
return super(Directory, self).run()
| Python |
from pypy.objspace.flow.model import FunctionGraph, Constant, Variable, c_last_exception
from pypy.rlib.rarithmetic import intmask, r_uint, ovfcheck, r_longlong
from pypy.rlib.rarithmetic import r_ulonglong, ovfcheck_lshift
from pypy.rpython.lltypesystem import lltype, llmemory, lloperation, llheap
from pypy.rpython.lltypesystem import rclass
from pypy.rpython.ootypesystem import ootype
from pypy.rlib.objectmodel import ComputedIntSymbolic, CDefinedIntSymbolic
import sys, os
import math
import py
import traceback, cStringIO
log = py.log.Producer('llinterp')
class LLException(Exception):
def __str__(self):
etype = self.args[0]
#evalue = self.args[1]
if len(self.args) > 2:
f = cStringIO.StringIO()
original_type, original_value, original_tb = self.args[2]
traceback.print_exception(original_type, original_value, original_tb,
file=f)
extra = '\n' + f.getvalue().rstrip('\n')
extra = extra.replace('\n', '\n | ') + '\n `------'
else:
extra = ''
return '<LLException %r%s>' % (type_name(etype), extra)
class LLFatalError(Exception):
def __str__(self):
return ': '.join([str(x) for x in self.args])
def type_name(etype):
if isinstance(lltype.typeOf(etype), lltype.Ptr):
return ''.join(etype.name).rstrip('\x00')
else:
# ootype!
return etype.class_._INSTANCE._name.split(".")[-1]
class LLInterpreter(object):
""" low level interpreter working with concrete values. """
def __init__(self, typer, heap=llheap, tracing=True, exc_data_ptr=None):
self.bindings = {}
self.typer = typer
self.heap = heap #module that provides malloc, etc for lltypes
self.exc_data_ptr = exc_data_ptr
self.active_frame = None
# XXX hack: set gc to None because
# prepare_graphs_and_create_gc might already use the llinterpreter!
self.gc = None
self.tracer = None
self.frame_class = LLFrame
if hasattr(heap, "prepare_graphs_and_create_gc"):
flowgraphs = typer.annotator.translator.graphs
self.gc = heap.prepare_graphs_and_create_gc(self, flowgraphs)
if tracing:
self.tracer = Tracer()
def eval_graph(self, graph, args=()):
llframe = self.frame_class(graph, args, self)
if self.tracer:
self.tracer.start()
retval = None
try:
try:
retval = llframe.eval()
except LLException, e:
log.error("LLEXCEPTION: %s" % (e, ))
self.print_traceback()
if self.tracer:
self.tracer.dump('LLException: %s\n' % (e,))
raise
except Exception, e:
log.error("AN ERROR OCCURED: %s" % (e, ))
self.print_traceback()
if self.tracer:
line = str(e)
if line:
line = ': ' + line
line = '* %s' % (e.__class__.__name__,) + line
self.tracer.dump(line + '\n')
raise
finally:
if self.tracer:
if retval is not None:
self.tracer.dump(' ---> %r\n' % (retval,))
self.tracer.stop()
return retval
def print_traceback(self):
frame = self.active_frame
frames = []
while frame is not None:
frames.append(frame)
frame = frame.f_back
frames.reverse()
lines = []
for frame in frames:
logline = frame.graph.name
if frame.curr_block is None:
logline += " <not running yet>"
lines.append(logline)
continue
try:
logline += " " + self.typer.annotator.annotated[frame.curr_block].__module__
except (KeyError, AttributeError):
# if the graph is from the GC it was not produced by the same
# translator :-(
logline += " <unknown module>"
lines.append(logline)
for i, operation in enumerate(frame.curr_block.operations):
if i == frame.curr_operation_index:
logline = "E %s"
else:
logline = " %s"
lines.append(logline % (operation, ))
if self.tracer:
self.tracer.dump('Traceback\n', bold=True)
for line in lines:
self.tracer.dump(line + '\n')
for line in lines:
log.traceback(line)
def find_roots(self):
#log.findroots("starting")
frame = self.active_frame
roots = []
while frame is not None:
#log.findroots("graph", frame.graph.name)
frame.find_roots(roots)
frame = frame.f_back
return roots
def find_exception(self, exc):
assert isinstance(exc, LLException)
klass, inst = exc.args[0], exc.args[1]
exdata = self.typer.getexceptiondata()
frame = self.frame_class(None, [], self)
old_active_frame = self.active_frame
try:
for cls in enumerate_exceptions_top_down():
evalue = frame.op_direct_call(exdata.fn_pyexcclass2exc,
lltype.pyobjectptr(cls))
etype = frame.op_direct_call(exdata.fn_type_of_exc_inst, evalue)
if etype == klass:
return cls
finally:
self.active_frame = old_active_frame
raise ValueError, "couldn't match exception"
def get_transformed_exc_data(self, graph):
if hasattr(graph, 'exceptiontransformed'):
return graph.exceptiontransformed
if getattr(graph, 'rgenop', False):
return self.exc_data_ptr
return None
def checkptr(ptr):
assert isinstance(lltype.typeOf(ptr), lltype.Ptr)
def checkadr(addr):
assert lltype.typeOf(addr) is llmemory.Address
def is_inst(inst):
return isinstance(lltype.typeOf(inst), (ootype.Instance, ootype.BuiltinType, ootype.StaticMethod))
def checkinst(inst):
assert is_inst(inst)
class LLFrame(object):
def __init__(self, graph, args, llinterpreter, f_back=None):
assert not graph or isinstance(graph, FunctionGraph)
self.graph = graph
self.args = args
self.llinterpreter = llinterpreter
self.heap = llinterpreter.heap
self.bindings = {}
self.f_back = f_back
self.curr_block = None
self.curr_operation_index = 0
self.alloca_objects = []
# _______________________________________________________
# variable setters/getters helpers
def clear(self):
self.bindings.clear()
def fillvars(self, block, values):
vars = block.inputargs
assert len(vars) == len(values), (
"block %s received %d args, expected %d" % (
block, len(values), len(vars)))
for var, val in zip(vars, values):
self.setvar(var, val)
def setvar(self, var, val):
if var.concretetype is not lltype.Void:
try:
val = lltype.enforce(var.concretetype, val)
except TypeError:
assert False, "type error: input value of type:\n\n\t%r\n\n===> variable of type:\n\n\t%r\n" % (lltype.typeOf(val), var.concretetype)
assert isinstance(var, Variable)
self.bindings[var] = val
def setifvar(self, var, val):
if isinstance(var, Variable):
self.setvar(var, val)
def getval(self, varorconst):
try:
val = varorconst.value
except AttributeError:
val = self.bindings[varorconst]
if isinstance(val, ComputedIntSymbolic):
val = val.compute_fn()
if varorconst.concretetype is not lltype.Void:
try:
val = lltype.enforce(varorconst.concretetype, val)
except TypeError:
assert False, "type error: %r val from %r var/const" % (lltype.typeOf(val), varorconst.concretetype)
return val
def getval_or_subop(self, varorsubop):
from pypy.translator.oosupport.treebuilder import SubOperation
if isinstance(varorsubop, SubOperation):
self.eval_operation(varorsubop.op)
resultval = self.getval(varorsubop.op.result)
del self.bindings[varorsubop.op.result] # XXX hack
return resultval
else:
return self.getval(varorsubop)
# _______________________________________________________
# other helpers
def getoperationhandler(self, opname):
ophandler = getattr(self, 'op_' + opname, None)
if ophandler is None:
# try to import the operation from opimpl.py
ophandler = lloperation.LL_OPERATIONS[opname].fold
setattr(self.__class__, 'op_' + opname, staticmethod(ophandler))
return ophandler
# _______________________________________________________
# evaling functions
def eval(self):
self.llinterpreter.active_frame = self
graph = self.graph
tracer = self.llinterpreter.tracer
if tracer:
tracer.enter(graph)
try:
nextblock = graph.startblock
args = self.args
while 1:
self.clear()
self.fillvars(nextblock, args)
nextblock, args = self.eval_block(nextblock)
if nextblock is None:
self.llinterpreter.active_frame = self.f_back
for obj in self.alloca_objects:
#XXX slighly unclean
obj._setobj(None)
return args
finally:
if tracer:
tracer.leave()
def eval_block(self, block):
""" return (nextblock, values) tuple. If nextblock
is None, values is the concrete return value.
"""
self.curr_block = block
catch_exception = block.exitswitch == c_last_exception
e = None
try:
for i, op in enumerate(block.operations):
self.curr_operation_index = i
self.eval_operation(op)
except LLException, e:
if not (catch_exception and op is block.operations[-1]):
raise
# determine nextblock and/or return value
if len(block.exits) == 0:
# return block
tracer = self.llinterpreter.tracer
if len(block.inputargs) == 2:
# exception
if tracer:
tracer.dump('raise')
etypevar, evaluevar = block.getvariables()
etype = self.getval(etypevar)
evalue = self.getval(evaluevar)
# watch out, these are _ptr's
raise LLException(etype, evalue)
resultvar, = block.getvariables()
result = self.getval(resultvar)
exc_data = self.llinterpreter.get_transformed_exc_data(self.graph)
if exc_data:
# re-raise the exception set by this graph, if any
etype = exc_data.exc_type
if etype:
evalue = exc_data.exc_value
if tracer:
tracer.dump('raise')
exc_data.exc_type = lltype.typeOf(etype )._defl()
exc_data.exc_value = lltype.typeOf(evalue)._defl()
from pypy.translator.c import exceptiontransform
T = resultvar.concretetype
errvalue = exceptiontransform.error_value(T)
# check that the exc-transformed graph returns the error
# value when it returns with an exception set
assert result == errvalue
raise LLException(etype, evalue)
if tracer:
tracer.dump('return')
return None, result
elif block.exitswitch is None:
# single-exit block
assert len(block.exits) == 1
link = block.exits[0]
elif catch_exception:
link = block.exits[0]
if e:
exdata = self.llinterpreter.typer.getexceptiondata()
cls = e.args[0]
inst = e.args[1]
for link in block.exits[1:]:
assert issubclass(link.exitcase, py.builtin.BaseException)
if self.op_direct_call(exdata.fn_exception_match,
cls, link.llexitcase):
self.setifvar(link.last_exception, cls)
self.setifvar(link.last_exc_value, inst)
break
else:
# no handler found, pass on
raise e
else:
llexitvalue = self.getval(block.exitswitch)
if block.exits[-1].exitcase == "default":
defaultexit = block.exits[-1]
nondefaultexits = block.exits[:-1]
assert defaultexit.llexitcase is None
else:
defaultexit = None
nondefaultexits = block.exits
for link in nondefaultexits:
if link.llexitcase == llexitvalue:
break # found -- the result is in 'link'
else:
if defaultexit is None:
raise ValueError("exit case %r not found in the exit links "
"of %r" % (llexitvalue, block))
else:
link = defaultexit
return link.target, [self.getval(x) for x in link.args]
def eval_operation(self, operation):
tracer = self.llinterpreter.tracer
if tracer:
tracer.dump(str(operation))
ophandler = self.getoperationhandler(operation.opname)
# XXX slighly unnice but an important safety check
if operation.opname == 'direct_call':
assert isinstance(operation.args[0], Constant)
elif operation.opname == 'indirect_call':
assert isinstance(operation.args[0], Variable)
if getattr(ophandler, 'specialform', False):
retval = ophandler(*operation.args)
else:
vals = [self.getval_or_subop(x) for x in operation.args]
if getattr(ophandler, 'need_result_type', False):
vals.insert(0, operation.result.concretetype)
try:
retval = ophandler(*vals)
except LLException, e:
# safety check check that the operation is allowed to raise that
# exception
if operation.opname in lloperation.LL_OPERATIONS:
canraise = lloperation.LL_OPERATIONS[operation.opname].canraise
if Exception not in canraise:
exc = self.llinterpreter.find_exception(e)
for canraiseexc in canraise:
if issubclass(exc, canraiseexc):
break
else:
raise TypeError("the operation %s is not expected to raise %s" % (operation, exc))
# for exception-transformed graphs, store the LLException
# into the exc_data used by this graph
exc_data = self.llinterpreter.get_transformed_exc_data(
self.graph)
if exc_data:
etype = e.args[0]
evalue = e.args[1]
exc_data.exc_type = etype
exc_data.exc_value = evalue
from pypy.translator.c import exceptiontransform
retval = exceptiontransform.error_value(
operation.result.concretetype)
else:
raise
self.setvar(operation.result, retval)
if tracer:
if retval is None:
tracer.dump('\n')
else:
tracer.dump(' ---> %r\n' % (retval,))
def make_llexception(self, exc=None):
if exc is None:
original = sys.exc_info()
exc = original[1]
extraargs = (original,)
else:
extraargs = ()
typer = self.llinterpreter.typer
exdata = typer.getexceptiondata()
if isinstance(exc, OSError):
self.op_direct_call(exdata.fn_raise_OSError, exc.errno)
assert False, "op_direct_call above should have raised"
else:
exc_class = exc.__class__
evalue = self.op_direct_call(exdata.fn_pyexcclass2exc,
self.heap.pyobjectptr(exc_class))
etype = self.op_direct_call(exdata.fn_type_of_exc_inst, evalue)
raise LLException(etype, evalue, *extraargs)
def invoke_callable_with_pyexceptions(self, fptr, *args):
obj = self.llinterpreter.typer.type_system.deref(fptr)
try:
return obj._callable(*args)
except LLException, e:
raise
except Exception:
if getattr(obj, '_debugexc', False):
import sys
from pypy.translator.tool.pdbplus import PdbPlusShow
PdbPlusShow(None).post_mortem(sys.exc_info()[2])
self.make_llexception()
def find_roots(self, roots):
#log.findroots(self.curr_block.inputargs)
PyObjPtr = lltype.Ptr(lltype.PyObject)
for arg in self.curr_block.inputargs:
if (isinstance(arg, Variable) and
isinstance(getattr(arg, 'concretetype', PyObjPtr), lltype.Ptr)):
roots.append(self.getval(arg))
for op in self.curr_block.operations[:self.curr_operation_index]:
if isinstance(getattr(op.result, 'concretetype', PyObjPtr), lltype.Ptr):
roots.append(self.getval(op.result))
# __________________________________________________________
# misc LL operation implementations
def op_debug_view(self, *ll_objects):
from pypy.translator.tool.lltracker import track
track(*ll_objects)
def op_debug_print(self, *ll_args):
from pypy.rpython.lltypesystem.rstr import STR
line = []
for arg in ll_args:
T = lltype.typeOf(arg)
if T == lltype.Ptr(STR):
arg = ''.join(arg.chars)
line.append(str(arg))
line = ' '.join(line)
print line
tracer = self.llinterpreter.tracer
if tracer:
tracer.dump('\n[debug] %s\n' % (line,))
def op_debug_pdb(self, *ll_args):
if self.llinterpreter.tracer:
self.llinterpreter.tracer.flush()
print "entering pdb...", ll_args
import pdb
pdb.set_trace()
def op_debug_assert(self, x, msg):
assert x, msg
def op_debug_fatalerror(self, ll_msg, ll_exc=None):
msg = ''.join(ll_msg.chars)
if ll_exc is None:
raise LLFatalError(msg)
else:
ll_exc_type = lltype.cast_pointer(rclass.OBJECTPTR, ll_exc).typeptr
raise LLFatalError(msg, LLException(ll_exc_type, ll_exc))
def op_instrument_count(self, ll_tag, ll_label):
pass # xxx for now
def op_keepalive(self, value):
pass
def op_hint(self, x, hints):
return x
def op_is_early_constant(self, x):
return False
def op_resume_point(self, *args):
pass
def op_resume_state_create(self, *args):
raise RuntimeError("resume_state_create can not be called.")
def op_resume_state_invoke(self, *args):
raise RuntimeError("resume_state_invoke can not be called.")
def op_decode_arg(self, fname, i, name, vargs, vkwds):
raise NotImplementedError("decode_arg")
def op_decode_arg_def(self, fname, i, name, vargs, vkwds, default):
raise NotImplementedError("decode_arg_def")
def op_check_no_more_arg(self, fname, n, vargs):
raise NotImplementedError("check_no_more_arg")
def op_getslice(self, vargs, start, stop_should_be_None):
raise NotImplementedError("getslice") # only for argument parsing
def op_check_self_nonzero(self, fname, vself):
raise NotImplementedError("check_self_nonzero")
def op_setfield(self, obj, fieldname, fieldvalue):
# obj should be pointer
FIELDTYPE = getattr(lltype.typeOf(obj).TO, fieldname)
if FIELDTYPE != lltype.Void:
gc = self.llinterpreter.gc
if gc is None or not gc.needs_write_barrier(FIELDTYPE):
setattr(obj, fieldname, fieldvalue)
else:
args = gc.get_arg_write_barrier(obj, fieldname, fieldvalue)
write_barrier = gc.get_funcptr_write_barrier()
result = self.op_direct_call(write_barrier, *args)
op_bare_setfield = op_setfield
def op_getarrayitem(self, array, index):
return array[index]
def op_setarrayitem(self, array, index, item):
# array should be a pointer
ITEMTYPE = lltype.typeOf(array).TO.OF
if ITEMTYPE != lltype.Void:
gc = self.llinterpreter.gc
if gc is None or not gc.needs_write_barrier(ITEMTYPE):
array[index] = item
else:
args = gc.get_arg_write_barrier(array, index, item)
write_barrier = gc.get_funcptr_write_barrier()
self.op_direct_call(write_barrier, *args)
op_bare_setarrayitem = op_setarrayitem
def perform_call(self, f, ARGS, args):
fobj = self.llinterpreter.typer.type_system.deref(f)
has_callable = getattr(fobj, '_callable', None) is not None
if has_callable and getattr(fobj._callable, 'suggested_primitive', False):
return self.invoke_callable_with_pyexceptions(f, *args)
if hasattr(fobj, 'graph'):
graph = fobj.graph
else:
assert has_callable, "don't know how to execute %r" % f
return self.invoke_callable_with_pyexceptions(f, *args)
args_v = graph.getargs()
if len(ARGS) != len(args_v):
raise TypeError("graph with %d args called with wrong func ptr type: %r" %(len(args_v), ARGS))
for T, v in zip(ARGS, args_v):
if not lltype.isCompatibleType(T, v.concretetype):
raise TypeError("graph with %r args called with wrong func ptr type: %r" %
(tuple([v.concretetype for v in args_v]), ARGS))
frame = self.__class__(graph, args, self.llinterpreter, self)
return frame.eval()
def op_direct_call(self, f, *args):
FTYPE = self.llinterpreter.typer.type_system.derefType(lltype.typeOf(f))
return self.perform_call(f, FTYPE.ARGS, args)
def op_indirect_call(self, f, *args):
graphs = args[-1]
args = args[:-1]
if graphs is not None:
obj = self.llinterpreter.typer.type_system.deref(f)
if hasattr(obj, 'graph'):
assert obj.graph in graphs
else:
pass
#log.warn("op_indirect_call with graphs=None:", f)
return self.op_direct_call(f, *args)
def op_adr_call(self, TGT, f, *inargs):
checkadr(f)
obj = self.llinterpreter.typer.type_system.deref(f.ref())
assert hasattr(obj, 'graph') # don't want to think about that
graph = obj.graph
args = []
for inarg, arg in zip(inargs, obj.graph.startblock.inputargs):
args.append(lltype._cast_whatever(arg.concretetype, inarg))
frame = self.__class__(graph, args, self.llinterpreter, self)
result = frame.eval()
from pypy.translator.stackless.frame import storage_type
assert storage_type(lltype.typeOf(result)) == TGT
return lltype._cast_whatever(TGT, result)
op_adr_call.need_result_type = True
def op_malloc(self, obj):
if self.llinterpreter.gc is not None:
args = self.llinterpreter.gc.get_arg_malloc(obj)
malloc = self.llinterpreter.gc.get_funcptr_malloc()
result = self.op_direct_call(malloc, *args)
return self.llinterpreter.gc.adjust_result_malloc(result, obj)
else:
return self.heap.malloc(obj)
def op_zero_malloc(self, obj):
assert self.llinterpreter.gc is None
return self.heap.malloc(obj, zero=True)
def op_malloc_varsize(self, obj, size):
if self.llinterpreter.gc is not None:
args = self.llinterpreter.gc.get_arg_malloc(obj, size)
malloc = self.llinterpreter.gc.get_funcptr_malloc()
result = self.op_direct_call(malloc, *args)
return self.llinterpreter.gc.adjust_result_malloc(result, obj, size)
else:
try:
return self.heap.malloc(obj, size)
except MemoryError:
self.make_llexception()
def op_zero_malloc_varsize(self, obj, size):
assert self.llinterpreter.gc is None
return self.heap.malloc(obj, size, zero=True)
def op_flavored_malloc_varsize(self, flavor, obj, size):
# XXX should we keep info about all mallocs for later checks of
# frees?
assert flavor == 'raw'
return self.heap.malloc(obj, size, flavor=flavor)
def op_flavored_malloc(self, flavor, obj):
assert isinstance(flavor, str)
if flavor == "stack":
if isinstance(obj, lltype.Struct) and obj._arrayfld is None:
result = self.heap.malloc(obj)
self.alloca_objects.append(result)
return result
else:
raise ValueError("cannot allocate variable-sized things on the stack")
return self.heap.malloc(obj, flavor=flavor)
def op_flavored_free(self, flavor, obj):
assert isinstance(flavor, str)
self.heap.free(obj, flavor=flavor)
def op_zero_gc_pointers_inside(self, obj):
pass
def op_getfield(self, obj, field):
checkptr(obj)
# check the difference between op_getfield and op_getsubstruct:
assert not isinstance(getattr(lltype.typeOf(obj).TO, field),
lltype.ContainerType)
return getattr(obj, field)
def op_cast_int_to_ptr(self, RESTYPE, int1):
return lltype.cast_int_to_ptr(RESTYPE, int1)
op_cast_int_to_ptr.need_result_type = True
def op_cast_ptr_to_int(self, ptr1):
checkptr(ptr1)
return lltype.cast_ptr_to_int(ptr1)
def op_cast_opaque_ptr(self, RESTYPE, obj):
checkptr(obj)
return lltype.cast_opaque_ptr(RESTYPE, obj)
op_cast_opaque_ptr.need_result_type = True
def op_gc__collect(self):
import gc
gc.collect()
def op_gc_free(self, addr):
# what can you do?
pass
#raise NotImplementedError("gc_free")
def op_gc_fetch_exception(self):
raise NotImplementedError("gc_fetch_exception")
def op_gc_restore_exception(self, exc):
raise NotImplementedError("gc_restore_exception")
def op_gc_call_rtti_destructor(self, rtti, addr):
if hasattr(rtti._obj, 'destructor_funcptr'):
d = rtti._obj.destructor_funcptr
obptr = addr.ref()
return self.op_direct_call(d, obptr)
def op_gc_deallocate(self, TYPE, addr):
raise NotImplementedError("gc_deallocate")
def op_gc_push_alive_pyobj(self, pyobj):
raise NotImplementedError("gc_push_alive_pyobj")
def op_gc_pop_alive_pyobj(self, pyobj):
raise NotImplementedError("gc_pop_alive_pyobj")
def op_gc_protect(self, obj):
raise NotImplementedError("gc_protect")
def op_gc_unprotect(self, obj):
raise NotImplementedError("gc_unprotect")
def op_gc_reload_possibly_moved(self, newaddr, ptr):
raise NotImplementedError("gc_reload_possibly_moved")
def op_yield_current_frame_to_caller(self):
raise NotImplementedError("yield_current_frame_to_caller")
# operations on pyobjects!
for opname in lloperation.opimpls.keys():
exec py.code.Source("""
def op_%(opname)s(self, *pyobjs):
for pyo in pyobjs:
assert lltype.typeOf(pyo) == lltype.Ptr(lltype.PyObject)
func = lloperation.opimpls[%(opname)r]
try:
pyo = func(*[pyo._obj.value for pyo in pyobjs])
except Exception:
self.make_llexception()
return self.heap.pyobjectptr(pyo)
""" % locals()).compile()
del opname
def op_simple_call(self, f, *args):
assert lltype.typeOf(f) == lltype.Ptr(lltype.PyObject)
for pyo in args:
assert lltype.typeOf(pyo) == lltype.Ptr(lltype.PyObject)
res = f._obj.value(*[pyo._obj.value for pyo in args])
return self.heap.pyobjectptr(res)
# __________________________________________________________
# operations on addresses
def op_raw_malloc(self, size):
assert lltype.typeOf(size) == lltype.Signed
return self.heap.raw_malloc(size)
op_boehm_malloc = op_boehm_malloc_atomic = op_raw_malloc
def op_boehm_register_finalizer(self, p, finalizer):
pass
def op_raw_malloc_usage(self, size):
assert lltype.typeOf(size) == lltype.Signed
return self.heap.raw_malloc_usage(size)
def op_raw_free(self, addr):
checkadr(addr)
self.heap.raw_free(addr)
def op_raw_memclear(self, addr, size):
checkadr(addr)
self.heap.raw_memclear(addr, size)
def op_raw_memcopy(self, fromaddr, toaddr, size):
checkadr(fromaddr)
checkadr(toaddr)
self.heap.raw_memcopy(fromaddr, toaddr, size)
def op_raw_load(self, addr, typ, offset):
checkadr(addr)
value = getattr(addr, str(typ).lower())[offset]
assert lltype.typeOf(value) == typ
return value
def op_raw_store(self, addr, typ, offset, value):
checkadr(addr)
assert lltype.typeOf(value) == typ
getattr(addr, str(typ).lower())[offset] = value
# ______ for the JIT ____________
def op_call_boehm_gc_alloc(self):
raise NotImplementedError("call_boehm_gc_alloc")
# ____________________________________________________________
# Overflow-detecting variants
def op_int_neg_ovf(self, x):
assert type(x) is int
try:
return ovfcheck(-x)
except OverflowError:
self.make_llexception()
def op_int_abs_ovf(self, x):
assert type(x) is int
try:
return ovfcheck(abs(x))
except OverflowError:
self.make_llexception()
def op_llong_neg_ovf(self, x):
assert type(x) is r_longlong
try:
return ovfcheck(-x)
except OverflowError:
self.make_llexception()
def op_llong_abs_ovf(self, x):
assert type(x) is r_longlong
try:
return ovfcheck(abs(x))
except OverflowError:
self.make_llexception()
def op_int_lshift_ovf(self, x, y):
assert isinstance(x, int)
assert isinstance(y, int)
try:
return ovfcheck_lshift(x, y)
except OverflowError:
self.make_llexception()
def op_int_lshift_ovf_val(self, x, y):
assert isinstance(x, int)
assert isinstance(y, int)
try:
return ovfcheck_lshift(x, y)
except (OverflowError, ValueError):
self.make_llexception()
def _makefunc2(fn, operator, xtype, ytype=None):
import sys
d = sys._getframe(1).f_locals
if ytype is None:
ytype = xtype
if '_ovf' in fn:
checkfn = 'ovfcheck'
elif fn.startswith('op_int_'):
checkfn = 'intmask'
else:
checkfn = ''
if operator == '//':
code = '''r = %(checkfn)s(x // y)
if x^y < 0 and x%%y != 0:
r += 1
return r
'''%locals()
elif operator == '%':
code = '''r = %(checkfn)s(x %% y)
if x^y < 0 and x%%y != 0:
r -= y
return r
'''%locals()
else:
code = 'return %(checkfn)s(x %(operator)s y)'%locals()
exec py.code.Source("""
def %(fn)s(self, x, y):
assert isinstance(x, %(xtype)s)
assert isinstance(y, %(ytype)s)
try:
%(code)s
except (OverflowError, ValueError, ZeroDivisionError):
self.make_llexception()
""" % locals()).compile() in globals(), d
_makefunc2('op_int_add_ovf', '+', '(int, llmemory.AddressOffset)')
_makefunc2('op_int_mul_ovf', '*', '(int, llmemory.AddressOffset)', 'int')
_makefunc2('op_int_sub_ovf', '-', 'int')
_makefunc2('op_int_floordiv_ovf', '//', 'int')
_makefunc2('op_int_floordiv_zer', '//', 'int')
_makefunc2('op_int_floordiv_ovf_zer', '//', 'int')
_makefunc2('op_int_mod_ovf', '%', 'int')
_makefunc2('op_int_mod_zer', '%', 'int')
_makefunc2('op_int_mod_ovf_zer', '%', 'int')
_makefunc2('op_int_lshift_val', '<<', 'int')
_makefunc2('op_int_rshift_val', '>>', 'int')
_makefunc2('op_uint_floordiv_zer', '//', 'r_uint')
_makefunc2('op_uint_mod_zer', '%', 'r_uint')
_makefunc2('op_uint_lshift_val', '<<', 'r_uint')
_makefunc2('op_uint_rshift_val', '>>', 'r_uint')
_makefunc2('op_llong_floordiv_zer', '//', 'r_longlong')
_makefunc2('op_llong_mod_zer', '%', 'r_longlong')
_makefunc2('op_llong_lshift_val', '<<', 'r_longlong')
_makefunc2('op_llong_rshift_val', '>>', 'r_longlong')
_makefunc2('op_ullong_floordiv_zer', '//', 'r_ulonglong')
_makefunc2('op_ullong_mod_zer', '%', 'r_ulonglong')
_makefunc2('op_ullong_lshift_val', '<<', 'r_ulonglong')
_makefunc2('op_ullong_rshift_val', '>>', 'r_ulonglong')
def op_cast_float_to_int(self, f):
assert type(f) is float
try:
return ovfcheck(int(f))
except OverflowError:
self.make_llexception()
def op_int_is_true(self, x):
# special case
if type(x) is CDefinedIntSymbolic:
x = x.default
assert isinstance(x, int)
return bool(x)
# read frame var support
def op_get_frame_base(self):
return llmemory.fakeaddress(self)
def op_frame_info(self, *vars):
pass
op_frame_info.specialform = True
# hack for jit.codegen.llgraph
def op_check_and_clear_exc(self):
exc_data = self.llinterpreter.get_transformed_exc_data(self.graph)
assert exc_data
etype = exc_data.exc_type
evalue = exc_data.exc_value
exc_data.exc_type = lltype.typeOf(etype )._defl()
exc_data.exc_value = lltype.typeOf(evalue)._defl()
return bool(etype)
#Operation of ootype
def op_new(self, INST):
assert isinstance(INST, (ootype.Instance, ootype.BuiltinType))
return ootype.new(INST)
def op_runtimenew(self, class_):
return ootype.runtimenew(class_)
def op_oonewcustomdict(self, DICT, eq_func, eq_obj, eq_method_name,
hash_func, hash_obj, hash_method_name):
eq_name, interp_eq = \
wrap_callable(self.llinterpreter, eq_func, eq_obj, eq_method_name)
EQ_FUNC = ootype.StaticMethod([DICT._KEYTYPE, DICT._KEYTYPE], ootype.Bool)
sm_eq = ootype.static_meth(EQ_FUNC, eq_name, _callable=interp_eq)
hash_name, interp_hash = \
wrap_callable(self.llinterpreter, hash_func, hash_obj, hash_method_name)
HASH_FUNC = ootype.StaticMethod([DICT._KEYTYPE], ootype.Signed)
sm_hash = ootype.static_meth(HASH_FUNC, hash_name, _callable=interp_hash)
# XXX: is it fine to have StaticMethod type for bound methods, too?
return ootype.oonewcustomdict(DICT, sm_eq, sm_hash)
def op_oosetfield(self, inst, name, value):
checkinst(inst)
assert isinstance(name, str)
FIELDTYPE = lltype.typeOf(inst)._field_type(name)
if FIELDTYPE != lltype.Void:
setattr(inst, name, value)
def op_oogetfield(self, inst, name):
checkinst(inst)
assert isinstance(name, str)
return getattr(inst, name)
def op_oosend(self, message, inst, *args):
checkinst(inst)
assert isinstance(message, str)
bm = getattr(inst, message)
inst = bm.inst
m = bm.meth
args = m._checkargs(args, check_callable=False)
if getattr(m, 'abstract', False):
raise RuntimeError("calling abstract method %r" % (m,))
return self.perform_call(m, (lltype.typeOf(inst),)+lltype.typeOf(m).ARGS, [inst]+args)
def op_ooidentityhash(self, inst):
return ootype.ooidentityhash(inst)
def op_oostring(self, obj, base):
return ootype.oostring(obj, base)
def op_ooparse_int(self, s, base):
try:
return ootype.ooparse_int(s, base)
except ValueError:
self.make_llexception()
def op_ooparse_float(self, s):
try:
return ootype.ooparse_float(s)
except ValueError:
self.make_llexception()
def op_oohash(self, s):
return ootype.oohash(s)
class Tracer(object):
Counter = 0
file = None
HEADER = """<html><head>
<script language=javascript type='text/javascript'>
function togglestate(n) {
var item = document.getElementById('div'+n)
if (item.style.display == 'none')
item.style.display = 'block';
else
item.style.display = 'none';
}
function toggleall(lst) {
for (var i = 0; i<lst.length; i++) {
togglestate(lst[i]);
}
}
</script>
</head>
<body><pre>
"""
FOOTER = """</pre>
<script language=javascript type='text/javascript'>
toggleall(%r);
</script>
</body></html>"""
ENTER = ('''\n\t<a href="javascript:togglestate(%d)">%s</a>'''
'''\n<div id="div%d" style="display: %s">\t''')
LEAVE = '''\n</div>\t'''
def htmlquote(self, s, text_to_html={}):
# HTML quoting, lazily initialized
if not text_to_html:
import htmlentitydefs
for key, value in htmlentitydefs.entitydefs.items():
text_to_html[value] = '&' + key + ';'
return ''.join([text_to_html.get(c, c) for c in s])
def start(self):
# start of a dump file
from pypy.tool.udir import udir
n = Tracer.Counter
Tracer.Counter += 1
filename = 'llinterp_trace_%d.html' % n
self.file = udir.join(filename).open('w')
print >> self.file, self.HEADER
linkname = str(udir.join('llinterp_trace.html'))
try:
os.unlink(linkname)
except OSError:
pass
try:
os.symlink(filename, linkname)
except (AttributeError, OSError):
pass
self.count = 0
self.indentation = ''
self.depth = 0
self.latest_call_chain = []
def stop(self):
# end of a dump file
if self.file:
print >> self.file, self.FOOTER % (self.latest_call_chain[1:])
self.file.close()
self.file = None
def enter(self, graph):
# enter evaluation of a graph
if self.file:
del self.latest_call_chain[self.depth:]
self.depth += 1
self.latest_call_chain.append(self.count)
s = self.htmlquote(str(graph))
i = s.rfind(')')
s = s[:i+1] + '<b>' + s[i+1:] + '</b>'
if self.count == 0:
display = 'block'
else:
display = 'none'
text = self.ENTER % (self.count, s, self.count, display)
self.indentation += ' '
self.file.write(text.replace('\t', self.indentation))
self.count += 1
def leave(self):
# leave evaluation of a graph
if self.file:
self.indentation = self.indentation[:-4]
self.file.write(self.LEAVE.replace('\t', self.indentation))
self.depth -= 1
def dump(self, text, bold=False):
if self.file:
text = self.htmlquote(text)
if bold:
text = '<b>%s</b>' % (text,)
self.file.write(text.replace('\n', '\n'+self.indentation))
def flush(self):
self.file.flush()
def wrap_callable(llinterpreter, fn, obj, method_name):
if method_name is None:
# fn is a HalfConcreteWrapper wrapping a StaticMethod
if obj is not None:
self_arg = [obj]
else:
self_arg = []
func_graph = fn.concretize().value.graph
else:
# obj is an instance, we want to call 'method_name' on it
assert fn is None
self_arg = [obj]
func_graph = obj._TYPE._methods[method_name].graph
return wrap_graph(llinterpreter, func_graph, self_arg)
def wrap_graph(llinterpreter, graph, self_arg):
"""
Returns a callable that inteprets the given func or method_name when called.
"""
def interp_func(*args):
graph_args = self_arg + list(args)
return llinterpreter.eval_graph(graph, args=graph_args)
interp_func.graph = graph
interp_func.self_arg = self_arg
return graph.name, interp_func
def enumerate_exceptions_top_down():
import exceptions
result = []
seen = {}
def addcls(cls):
if (type(cls) is type(Exception) and
issubclass(cls, py.builtin.BaseException)):
if cls in seen:
return
for base in cls.__bases__: # bases first
addcls(base)
result.append(cls)
seen[cls] = True
for cls in exceptions.__dict__.values():
addcls(cls)
return result
# by default we route all logging messages to nothingness
# e.g. tests can then switch on logging to get more help
# for failing tests
from pypy.tool.ansi_print import ansi_log
py.log.setconsumer('llinterp', ansi_log)
| Python |
"""
Dummy low-level implementations for the external functions of the 'time' module.
"""
# See ll_os.py.
import time
def ll_time_time():
return time.time()
ll_time_time.suggested_primitive = True
def ll_time_clock():
return time.clock()
ll_time_clock.suggested_primitive = True
def ll_time_sleep(t):
time.sleep(t)
ll_time_sleep.suggested_primitive = True
| Python |
from pypy.rpython.lltypesystem import lltype
from pypy.rlib import rstack
from pypy.rpython import extfunctable
from pypy.rpython.module.support import from_opaque_object, to_opaque_object
FRAMETOPTYPE = extfunctable.frametop_type_info.get_lltype()
def ll_stackless_stack_frames_depth():
return rstack.stack_frames_depth()
ll_stackless_stack_frames_depth.suggested_primitive = True
def ll_stackless_switch(opaqueframetop):
frametop = from_opaque_object(opaqueframetop)
newframetop = frametop.switch()
if newframetop is None:
return lltype.nullptr(FRAMETOPTYPE)
else:
return to_opaque_object(newframetop)
ll_stackless_switch.suggested_primitive = True
| Python |
from pypy.rlib import rstack
def ll_stack_too_big():
return rstack.stack_too_big()
ll_stack_too_big.suggested_primitive = True
def ll_stack_unwind():
rstack.stack_unwind()
ll_stack_unwind.suggested_primitive = True
def ll_stack_capture():
return rstack.stack_capture()
ll_stack_capture.suggested_primitive = True
def ll_stack_check():
if ll_stack_too_big():
ll_stack_unwind()
| Python |
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.ootypesystem import ootype
from pypy.rpython import extfunctable
from pypy.rpython.lltypesystem.lltype import \
GcStruct, Signed, Array, Char, Ptr, malloc, GcArray
from pypy.rpython.rlist import ll_append
from pypy.rpython.lltypesystem.rlist import ll_newlist, ListRepr,\
ll_getitem_fast
from pypy.rpython.lltypesystem.rstr import string_repr
from pypy.rpython.lltypesystem.rdict import ll_newdict, DictRepr, dum_items,\
ll_kvi, dum_keys, ll_dict_getitem, ll_dict_setitem
from pypy.rpython.lltypesystem.rstr import StringRepr
from pypy.rpython.lltypesystem.rtuple import TupleRepr
from pypy.annotation.dictdef import DictKey, DictValue
from pypy.annotation.model import SomeString
import os
# utility conversion functions
class LLSupport:
_mixin_ = True
def to_rstr(s):
from pypy.rpython.lltypesystem.rstr import STR, mallocstr
if s is None:
return lltype.nullptr(STR)
p = mallocstr(len(s))
for i in range(len(s)):
p.chars[i] = s[i]
return p
to_rstr = staticmethod(to_rstr)
def from_rstr(rs):
if not rs: # null pointer
return None
else:
return ''.join([rs.chars[i] for i in range(len(rs.chars))])
from_rstr = staticmethod(from_rstr)
class OOSupport:
_mixin_ = True
def to_rstr(s):
return ootype.oostring(s, -1)
to_rstr = staticmethod(to_rstr)
def from_rstr(rs):
if not rs: # null pointer
return None
else:
return "".join([rs.ll_stritem_nonneg(i) for i in range(rs.ll_strlen())])
from_rstr = staticmethod(from_rstr)
def ll_strcpy(dst_s, src_s, n):
dstchars = dst_s.chars
srcchars = src_s.chars
i = 0
while i < n:
dstchars[i] = srcchars[i]
i += 1
def _ll_strfill(dst_s, srcchars, n):
dstchars = dst_s.chars
i = 0
while i < n:
dstchars[i] = srcchars[i]
i += 1
def init_opaque_object(opaqueptr, value):
"NOT_RPYTHON"
opaqueptr._obj.externalobj = value
init_opaque_object._annspecialcase_ = "override:init_opaque_object"
def from_opaque_object(opaqueptr):
"NOT_RPYTHON"
return opaqueptr._obj.externalobj
from_opaque_object._annspecialcase_ = "override:from_opaque_object"
def to_opaque_object(value):
"NOT_RPYTHON"
exttypeinfo = extfunctable.typetable[value.__class__]
return lltype.opaqueptr(exttypeinfo.get_lltype(), 'opaque',
externalobj=value)
to_opaque_object._annspecialcase_ = "override:to_opaque_object"
| Python |
#
| Python |
"""
Dummy low-level implementations for the external functions of the 'os.path' module.
"""
# see ll_os.py for comments
import stat
import os
from pypy.tool.staticmethods import ClassMethods
# Does a path exist?
# This is false for dangling symbolic links.
class BaseOsPath:
__metaclass__ = ClassMethods
def ll_os_path_exists(cls, path):
"""Test whether a path exists"""
try:
st = os.stat(cls.from_rstr(path))
except OSError:
return False
return True
def ll_os_path_isdir(cls, path):
try:
(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9) = os.stat(cls.from_rstr(path))
except OSError:
return False
return stat.S_ISDIR(stat0)
| Python |
"""
The low-level implementation of termios module
note that this module should only be imported when
termios module is there
"""
import termios
from pypy.rpython.lltypesystem import rffi
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.extfunc import register_external
from pypy.rlib.rarithmetic import intmask
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.annotation import model as annmodel
from pypy.rpython import rclass
from pypy.rlib import rtermios
# XXX is this portable? well.. not at all, ideally
# I would like to have NCCS = CLaterConstant(NCCS)
TCFLAG_T = rffi.UINT
CC_T = rffi.UCHAR
NCCS = 32
SPEED_T = rffi.UINT
INT = rffi.INT
def termios_error_init(self, num, msg):
self.args = (num, msg)
termios.error.__init__ = termios_error_init
includes = ['termios.h', 'unistd.h']
TERMIOSP = rffi.CStruct('termios', ('c_iflag', TCFLAG_T), ('c_oflag', TCFLAG_T),
('c_cflag', TCFLAG_T), ('c_lflag', TCFLAG_T),
('c_cc', lltype.FixedSizeArray(CC_T, NCCS)))
def c_external(name, args, result):
return rffi.llexternal(name, args, result, includes=includes)
c_tcgetattr = c_external('tcgetattr', [INT, TERMIOSP], INT)
c_tcsetattr = c_external('tcsetattr', [INT, INT, TERMIOSP], INT)
c_cfgetispeed = c_external('cfgetispeed', [TERMIOSP], SPEED_T)
c_cfgetospeed = c_external('cfgetospeed', [TERMIOSP], SPEED_T)
c_cfsetispeed = c_external('cfsetispeed', [TERMIOSP, SPEED_T], INT)
c_cfsetospeed = c_external('cfsetospeed', [TERMIOSP, SPEED_T], INT)
c_tcsendbreak = c_external('tcsendbreak', [INT, INT], INT)
c_tcdrain = c_external('tcdrain', [INT], INT)
c_tcflush = c_external('tcflush', [INT, INT], INT)
c_tcflow = c_external('tcflow', [INT, INT], INT)
#class termios_error(termios.error):
# def __init__(self, num, msg):
# self.args = (num, msg)
def tcgetattr_llimpl(fd):
c_struct = lltype.malloc(TERMIOSP.TO, flavor='raw')
error = c_tcgetattr(fd, c_struct)
try:
if error == -1:
raise termios.error(error, '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')
c_struct.c_c_iflag, c_struct.c_c_oflag, c_struct.c_c_cflag, \
c_struct.c_c_lflag, ispeed, ospeed, cc = attributes
try:
for i in range(NCCS):
c_struct.c_c_cc[i] = rffi.r_uchar(ord(cc[i]))
error = c_cfsetispeed(c_struct, ispeed)
if error == -1:
raise termios.error(error, 'tcsetattr failed')
error = c_cfsetospeed(c_struct, ospeed)
if error == -1:
raise termios.error(error, 'tcsetattr failed')
error = c_tcsetattr(fd, when, c_struct)
if error == -1:
raise termios.error(error, 'tcsetattr failed')
finally:
lltype.free(c_struct, flavor='raw')
r_uint = rffi.r_uint
register_external(rtermios.tcsetattr, [int, int, (r_uint, r_uint, r_uint,
r_uint, r_uint, r_uint, [str])], llimpl=tcsetattr_llimpl,
export_name='termios.tcsetattr')
# a bit C-c C-v code follows...
def tcsendbreak_llimpl(fd, duration):
error = c_tcsendbreak(fd, duration)
if error == -1:
raise termios.error(error, 'tcsendbreak failed')
register_external(termios.tcsendbreak, [int, int],
llimpl=tcsendbreak_llimpl,
export_name='termios.tcsendbreak')
def tcdrain_llimpl(fd):
error = c_tcdrain(fd)
if error == -1:
raise termios.error(error, 'tcdrain failed')
register_external(termios.tcdrain, [int], llimpl=tcdrain_llimpl,
export_name='termios.tcdrain')
def tcflush_llimpl(fd, queue_selector):
error = c_tcflush(fd, queue_selector)
if error == -1:
raise termios.error(error, 'tcflush failed')
register_external(termios.tcflush, [int, int], llimpl=tcflush_llimpl,
export_name='termios.tcflush')
def tcflow_llimpl(fd, action):
error = c_tcflow(fd, action)
if error == -1:
raise termios.error(error, 'tcflow failed')
register_external(termios.tcflow, [int, int], llimpl=tcflow_llimpl,
export_name='termios.tcflow')
| Python |
#
| Python |
"""
Low-level implementations for the external functions of the 'os' module.
"""
# actual idea might be found in doc/rffi.txt
# ------------------------------------------
# WARNING! old vision, don't use it WARNING!
# ------------------------------------------
# Idea: each ll_os_xxx() function calls back the os.xxx() function that it
# is supposed to implement, either directly or indirectly if there is some
# argument decoding and buffering preparation that can be done here.
# The specific function that calls back to os.xxx() is tagged with the
# 'suggested_primitive' flag. The back-end should special-case it and really
# implement it. The back-end can actually choose to special-case any function:
# it can for example special-case ll_os_xxx() directly even if the
# 'suggested_primitive' flag is set to another function, if the conversion
# and buffer preparation stuff is not useful.
import os
from pypy.rpython.module.support import ll_strcpy, _ll_strfill
from pypy.rpython.module.support import to_opaque_object, from_opaque_object
from pypy.rlib import ros
from pypy.rlib.rarithmetic import r_longlong
from pypy.tool.staticmethods import ClassMethods
import stat
from pypy.rpython.extfunc import ExtFuncEntry, register_external
from pypy.annotation.model import SomeString, SomeInteger, s_ImpossibleValue, \
s_None
from pypy.rpython.lltypesystem import rffi
from pypy.rpython.lltypesystem import lltype
# ------------------------------- 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 -------------------------------
os_dup2 = rffi.llexternal('dup2', [lltype.Signed, lltype.Signed], lltype.Signed)
def dup2_lltypeimpl(fd, newfd):
error = os_dup2(fd, newfd)
if error == -1:
raise OSError(rffi.c_errno, "dup2 failed")
register_external(os.dup2, [int, int], s_None, llimpl=dup2_lltypeimpl,
export_name="ll_os.ll_os_dup2")
# ------------------------------- os.utime ------------------------------
UTIMEBUFP = rffi.CStruct('utimbuf', ('actime', rffi.SIZE_T),
('modtime', rffi.SIZE_T))
# XXX sys/types.h is not portable at all
ros_utime = rffi.llexternal('utime', [rffi.CCHARP, UTIMEBUFP], lltype.Signed,
includes=['utime.h', 'sys/types.h'])
def utime_null_lltypeimpl(path):
l_path = rffi.str2charp(path)
error = ros_utime(l_path, lltype.nullptr(UTIMEBUFP.TO))
rffi.free_charp(l_path)
if error == -1:
raise OSError(rffi.c_errno, "utime_null failed")
register_external(ros.utime_null, [str], s_None, "ll_os.utime_null",
llimpl=utime_null_lltypeimpl)
def utime_tuple_lltypeimpl(path, tp):
# XXX right now they're all ints, might change in future
# XXX does not use utimes, even when available
l_path = rffi.str2charp(path)
l_utimebuf = lltype.malloc(UTIMEBUFP.TO, flavor='raw')
actime, modtime = tp
l_utimebuf.c_actime, l_utimebuf.c_modtime = int(actime), int(modtime)
error = ros_utime(l_path, l_utimebuf)
rffi.free_charp(l_path)
lltype.free(l_utimebuf, flavor='raw')
if error == -1:
raise OSError(rffi.c_errno, "utime_tuple failed")
register_external(ros.utime_tuple, [str, (float, float)], s_None, "ll_os.utime_tuple",
llimpl=utime_tuple_lltypeimpl)
# ------------------------------- os.open -------------------------------
def fake_os_open(l_path, flags, mode):
path = rffi.charp2str(l_path)
return os.open(path, flags, mode)
if os.name == 'nt':
mode_t = lltype.Signed
else:
mode_t = rffi.MODE_T
os_open = rffi.llexternal('open', [rffi.CCHARP, lltype.Signed, mode_t],
lltype.Signed, _callable=fake_os_open)
def os_open_lltypeimpl(path, flags, mode):
l_path = rffi.str2charp(path)
mode = lltype.cast_primitive(mode_t, mode)
result = os_open(l_path, flags, mode)
rffi.free_charp(l_path)
if result == -1:
raise OSError(rffi.c_errno, "os_open failed")
return result
def os_open_oofakeimpl(o_path, flags, mode):
return os.open(o_path._str, flags, mode)
register_external(os.open, [str, int, int], int, "ll_os.ll_os_open",
llimpl=os_open_lltypeimpl, oofakeimpl=os_open_oofakeimpl)
# ------------------------------- os.* ----------------------------------
w_star = ['WCOREDUMP', 'WIFCONTINUED', 'WIFSTOPPED',
'WIFSIGNALED', 'WIFEXITED', 'WEXITSTATUS',
'WSTOPSIG', 'WTERMSIG']
# last 3 are returning int
w_star_returning_int = dict.fromkeys(w_star[-3:])
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)
for name in w_star:
if hasattr(os, name):
declare_new_w_star(name)
# ------------------------------- os.ttyname ----------------------------
if hasattr(os, 'ttyname'):
def fake_ttyname(fd):
return rffi.str2charp(os.ttyname(fd))
os_ttyname = rffi.llexternal('ttyname', [lltype.Signed], rffi.CCHARP,
_callable=fake_ttyname)
def ttyname_lltypeimpl(fd):
l_name = os_ttyname(fd)
if not l_name:
raise OSError(rffi.c_errno, "ttyname raised")
return rffi.charp2str(l_name)
register_external(os.ttyname, [int], str, "ll_os.ttyname",
llimpl=ttyname_lltypeimpl)
class BaseOS:
__metaclass__ = ClassMethods
def ll_os_write(cls, fd, astring):
return os.write(fd, cls.from_rstr(astring))
ll_os_write.suggested_primitive = True
def ll_os_getcwd(cls):
return cls.to_rstr(os.getcwd())
ll_os_getcwd.suggested_primitive = True
def ll_read_into(fd, buffer):
data = os.read(fd, len(buffer.chars))
_ll_strfill(buffer, data, len(data))
return len(data)
ll_read_into.suggested_primitive = True
ll_read_into = staticmethod(ll_read_into)
def ll_os_close(cls, fd):
os.close(fd)
ll_os_close.suggested_primitive = True
def ll_os_access(cls, path, mode):
return os.access(cls.from_rstr(path), mode)
ll_os_access.suggested_primitive = True
def ll_os_lseek(cls, fd,pos,how):
return r_longlong(os.lseek(fd,pos,how))
ll_os_lseek.suggested_primitive = True
def ll_os_isatty(cls, fd):
return os.isatty(fd)
ll_os_isatty.suggested_primitive = True
def ll_os_ftruncate(cls, fd,len):
return os.ftruncate(fd,len)
ll_os_ftruncate.suggested_primitive = True
def ll_os_fstat(cls, fd):
(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9) = os.fstat(fd)
return cls.ll_stat_result(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9)
ll_os_fstat.suggested_primitive = True
def ll_os_stat(cls, path):
(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9) = os.stat(cls.from_rstr(path))
return cls.ll_stat_result(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9)
ll_os_stat.suggested_primitive = True
def ll_os_lstat(cls, path):
(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9) = os.lstat(cls.from_rstr(path))
return cls.ll_stat_result(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9)
ll_os_lstat.suggested_primitive = True
def ll_os_strerror(cls, errnum):
return cls.to_rstr(os.strerror(errnum))
ll_os_strerror.suggested_primitive = True
def ll_os_system(cls, cmd):
return os.system(cls.from_rstr(cmd))
ll_os_system.suggested_primitive = True
def ll_os_unlink(cls, path):
os.unlink(cls.from_rstr(path))
ll_os_unlink.suggested_primitive = True
def ll_os_chdir(cls, path):
os.chdir(cls.from_rstr(path))
ll_os_chdir.suggested_primitive = True
def ll_os_mkdir(cls, path, mode):
os.mkdir(cls.from_rstr(path), mode)
ll_os_mkdir.suggested_primitive = True
def ll_os_rmdir(cls, path):
os.rmdir(cls.from_rstr(path))
ll_os_rmdir.suggested_primitive = True
# this function is not really the os thing, but the internal one.
def ll_os_putenv(cls, name_eq_value):
ros.putenv(cls.from_rstr(name_eq_value))
ll_os_putenv.suggested_primitive = True
def ll_os_unsetenv(cls, name):
os.unsetenv(cls.from_rstr(name))
ll_os_unsetenv.suggested_primitive = True
# get the initial environment by indexing
def ll_os_environ(cls, idx):
return ros.environ(idx)
ll_os_environ.suggested_primitive = True
def ll_os_pipe(cls):
fd1, fd2 = os.pipe()
return cls.ll_pipe_result(fd1, fd2)
ll_os_pipe.suggested_primitive = True
def ll_os_chmod(cls, path, mode):
os.chmod(cls.from_rstr(path), mode)
ll_os_chmod.suggested_primitive = True
def ll_os_rename(cls, path1, path2):
os.rename(cls.from_rstr(path1), cls.from_rstr(path2))
ll_os_rename.suggested_primitive = True
def ll_os_umask(cls, mask):
return os.umask(mask)
ll_os_umask.suggested_primitive = True
def ll_os_getpid(cls):
return os.getpid()
ll_os_getpid.suggested_primitive = True
def ll_os_kill(cls, pid, sig):
os.kill(pid, sig)
ll_os_kill.suggested_primitive = True
def ll_os_link(cls, path1, path2):
os.link(cls.from_rstr(path1), cls.from_rstr(path2))
ll_os_link.suggested_primitive = True
def ll_os_symlink(cls, path1, path2):
os.symlink(cls.from_rstr(path1), cls.from_rstr(path2))
ll_os_symlink.suggested_primitive = True
def ll_readlink_into(cls, path, buffer):
data = os.readlink(cls.from_rstr(path))
if len(data) < len(buffer.chars): # safely no overflow
_ll_strfill(buffer, data, len(data))
return len(data)
ll_readlink_into.suggested_primitive = True
ll_readlink_into = staticmethod(ll_readlink_into)
def ll_os_fork(cls):
return os.fork()
ll_os_fork.suggested_primitive = True
def ll_os_spawnv(cls, mode, path, args):
return os.spawnv(mode, path, args)
ll_os_spawnv.suggested_primitive = True
def ll_os_waitpid(cls, pid, options):
pid, status = os.waitpid(pid, options)
return cls.ll_waitpid_result(pid, status)
ll_os_waitpid.suggested_primitive = True
def ll_os__exit(cls, status):
os._exit(status)
ll_os__exit.suggested_primitive = True
# ____________________________________________________________
# opendir/readdir
def ll_os_opendir(cls, dirname):
dir = ros.opendir(cls.from_rstr(dirname))
return to_opaque_object(dir)
ll_os_opendir.suggested_primitive = True
def ll_os_readdir(cls, opaquedir):
dir = from_opaque_object(opaquedir)
nextentry = dir.readdir()
return cls.to_rstr(nextentry)
ll_os_readdir.suggested_primitive = True
def ll_os_closedir(cls, opaquedir):
dir = from_opaque_object(opaquedir)
dir.closedir()
ll_os_closedir.suggested_primitive = True
| Python |
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import inputconst
def rtype_call_specialcase(hop):
s_pbc = hop.args_s[0]
if len(s_pbc.descriptions) != 1:
raise TyperError("not monomorphic call_specialcase")
desc, = s_pbc.descriptions
tag = desc.pyobj._annspecialcase_
if not tag.startswith("override:"):
raise TyperError("call_specialcase only supports 'override:' functions")
tag = tag[9:]
try:
rtype_override_fn = globals()['rtype_override_' + tag]
except KeyError:
raise TyperError("call_specialcase: unknown tag override:" + tag)
hop2 = hop.copy()
hop2.r_s_popfirstarg()
return rtype_override_fn(hop2)
def rtype_override_ignore(hop): # ignore works for methods too
hop.exception_cannot_occur()
return inputconst(hop.r_result, None)
def rtype_identity_function(hop):
hop.exception_cannot_occur()
v, = hop.inputargs(hop.args_r[0])
return v
def rtype_override_init_opaque_object(hop):
return hop.genop('init_opaque_object_should_never_be_seen_by_the_backend',
[], resulttype=hop.r_result)
def rtype_override_from_opaque_object(hop):
return hop.genop('from_opaque_object_should_never_be_seen_by_the_backend',
[], resulttype=hop.r_result)
def rtype_override_to_opaque_object(hop):
return hop.genop('to_opaque_object_should_never_be_seen_by_the_backend',
[], resulttype=hop.r_result)
def rtype_override_yield_current_frame_to_caller(hop):
return hop.genop('yield_current_frame_to_caller', [],
resulttype=hop.r_result)
| Python |
from pypy.rpython.rmodel import Repr
from pypy.rpython.lltypesystem.lltype import Signed, Void
from pypy.objspace.flow.model import Constant
from pypy.annotation import model as annmodel
from pypy.rpython.error import TyperError
class AbstractSliceRepr(Repr):
pass
def select_slice_repr(self):
# Select which one of the three prebuilt reprs to use.
# Return a name.
if not self.step.is_constant() or self.step.const not in (None, 1):
raise TyperError("only supports slices with step 1")
if (self.start.is_constant() and self.start.const in (None, 0) and
self.stop.is_constant() and self.stop.const == -1):
return "minusone_slice_repr" # [:-1]
if isinstance(self.start, annmodel.SomeInteger):
if not self.start.nonneg:
raise TyperError("slice start must be proved non-negative")
if isinstance(self.stop, annmodel.SomeInteger):
if not self.stop.nonneg:
raise TyperError("slice stop must be proved non-negative")
if self.stop.is_constant() and self.stop.const is None:
return "startonly_slice_repr"
else:
return "startstop_slice_repr"
class __extend__(annmodel.SomeSlice):
def rtyper_makerepr(self, rtyper):
return getattr(rtyper.type_system.rslice, select_slice_repr(self))
def rtyper_makekey(self):
return self.__class__, select_slice_repr(self)
def rtype_newslice(hop):
sig = []
for s in hop.args_s:
if s.is_constant() and s.const is None:
sig.append(Void)
else:
sig.append(Signed)
v_start, v_stop, v_step = hop.inputargs(*sig)
assert isinstance(v_step, Constant) and v_step.value in (None, 1)
if isinstance(v_start, Constant) and v_start.value is None:
v_start = hop.inputconst(Signed, 0)
if (isinstance(v_start, Constant) and v_start.value == 0 and
isinstance(v_stop, Constant) and v_stop.value == -1):
# [:-1] slice
return hop.inputconst(Void, slice(None,-1))
if isinstance(v_stop, Constant) and v_stop.value is None:
# start-only slice
# NB. cannot just return v_start in case it is a constant
return hop.genop('same_as', [v_start],
resulttype=hop.rtyper.type_system.rslice.startonly_slice_repr)
else:
# start-stop slice
return hop.gendirectcall(hop.rtyper.type_system.rslice.ll_newslice,
v_start, v_stop)
| Python |
from pypy.annotation import model as annmodel
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.ootypesystem import ootype, bltregistry
from pypy.rpython.rmodel import Repr
from pypy.annotation.signature import annotation
from pypy.annotation.pairtype import pairtype
class ExternalInstanceRepr(Repr):
def __init__(self, rtyper, knowntype):
bk = rtyper.annotator.bookkeeper
self.ext_desc = bk.getexternaldesc(knowntype)
self.lowleveltype = bltregistry.ExternalType(knowntype)
self.name = "<class '%s'>" % self.ext_desc._class_.__name__
def convert_const(self, value):
return bltregistry._external_inst(self.lowleveltype, value)
def rtype_getattr(self, hop):
attr = hop.args_s[1].const
s_inst = hop.args_s[0]
if self.ext_desc._methods.has_key(attr):
# just return instance - will be handled by simple_call
return hop.inputarg(hop.args_r[0], arg=0)
vlist = hop.inputargs(self, ootype.Void)
return hop.genop("oogetfield", vlist,
resulttype = hop.r_result.lowleveltype)
def rtype_setattr(self, hop):
if self.lowleveltype is ootype.Void:
return
vlist = [hop.inputarg(self, arg=0), hop.inputarg(ootype.Void, arg=1)]
field_name = hop.args_s[1].const
obj = self.ext_desc._class_._fields[field_name]
bookkeeper = hop.rtyper.annotator.bookkeeper
# XXX WARNING XXX
# annotation() here should not be called, but we somehow
# have overwritten _fields. This will do no harm, but may hide some
# errors
r = hop.rtyper.getrepr(annotation(obj, bookkeeper))
r.setup()
v = hop.inputarg(r, arg=2)
vlist.append(v)
return hop.genop('oosetfield', vlist)
def call_method(self, name, hop):
bookkeeper = hop.rtyper.annotator.bookkeeper
args_r = []
for s_arg in self.ext_desc._fields[name].analyser.s_args:
r = hop.rtyper.getrepr(s_arg)
r.setup()
args_r.append(r)
vlist = hop.inputargs(self, *args_r)
c_name = hop.inputconst(ootype.Void, name)
hop.exception_is_here()
return hop.genop('oosend', [c_name] + vlist, resulttype=hop.r_result)
def rtype_is_true(self, hop):
vlist = hop.inputargs(self)
return hop.genop('is_true', vlist, resulttype=lltype.Bool)
def ll_str(self, val):
return ootype.oostring(self.name, -1)
def __getattr__(self, attr):
if attr.startswith("rtype_method_"):
name = attr[len("rtype_method_"):]
return lambda hop: self.call_method(name, hop)
else:
raise AttributeError(attr)
class __extend__(pairtype(ExternalInstanceRepr, ExternalInstanceRepr)):
def convert_from_to((from_, to), v, llops):
type_from = from_.ext_desc._class_
type_to = to.ext_desc._class_
if issubclass(type_from, type_to):
# XXX ?
v.concretetype=to.lowleveltype
return v
return NotImplemented
| Python |
from pypy.annotation.pairtype import pairtype
from pypy.rpython.rlist import AbstractBaseListRepr, AbstractListRepr, \
AbstractListIteratorRepr, rtype_newlist, rtype_alloc_and_set
from pypy.rpython.rmodel import Repr, IntegerRepr
from pypy.rpython.rmodel import inputconst, externalvsinternal
from pypy.rpython.lltypesystem.lltype import Signed, Void
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.ootypesystem.rslice import SliceRepr, \
startstop_slice_repr, startonly_slice_repr, minusone_slice_repr
from pypy.rpython.ootypesystem import rstr
class BaseListRepr(AbstractBaseListRepr):
rstr_ll = rstr.LLHelpers
def __init__(self, rtyper, item_repr, listitem=None):
self.rtyper = rtyper
if not isinstance(item_repr, Repr):
assert callable(item_repr)
self._item_repr_computer = item_repr
else:
self.external_item_repr, self.item_repr = \
externalvsinternal(rtyper, item_repr)
self.LIST = ootype.List()
self.lowleveltype = self.LIST
self.listitem = listitem
self.list_cache = {}
# setup() needs to be called to finish this initialization
def _externalvsinternal(self, rtyper, item_repr):
return item_repr, item_repr
def _setup_repr(self):
if 'item_repr' not in self.__dict__:
self.external_item_repr, self.item_repr = \
self._externalvsinternal(self.rtyper, self._item_repr_computer())
if not ootype.hasItemType(self.lowleveltype):
ootype.setItemType(self.lowleveltype, self.item_repr.lowleveltype)
def null_const(self):
return self.LIST._null
def prepare_const(self, n):
result = self.LIST.ll_newlist(n)
return result
def send_message(self, hop, message, can_raise=False, v_args=None):
if v_args is None:
v_args = hop.inputargs(self, *hop.args_r[1:])
c_name = hop.inputconst(ootype.Void, message)
if can_raise:
hop.exception_is_here()
return hop.genop("oosend", [c_name] + v_args,
resulttype=hop.r_result.lowleveltype)
def get_eqfunc(self):
return inputconst(Void, self.item_repr.get_ll_eq_function())
def make_iterator_repr(self):
return ListIteratorRepr(self)
def rtype_hint(self, hop):
hints = hop.args_s[-1].const
if 'maxlength' in hints:
v_list = hop.inputarg(self, arg=0)
# XXX give a hint to pre-allocate the list (see lltypesystem/rlist)
return v_list
if 'fence' in hints:
return hop.inputarg(self, arg=0)
return AbstractBaseListRepr.rtype_hint(self, hop)
class ListRepr(AbstractListRepr, BaseListRepr):
pass
FixedSizeListRepr = ListRepr
class __extend__(pairtype(BaseListRepr, BaseListRepr)):
def rtype_is_((r_lst1, r_lst2), hop):
# NB. this version performs no cast to the common base class
vlist = hop.inputargs(r_lst1, r_lst2)
return hop.genop('oois', vlist, resulttype=ootype.Bool)
def newlist(llops, r_list, items_v):
c_list = inputconst(ootype.Void, r_list.lowleveltype)
v_result = llops.genop("new", [c_list], resulttype=r_list.lowleveltype)
c_resize = inputconst(ootype.Void, "_ll_resize")
c_length = inputconst(ootype.Signed, len(items_v))
llops.genop("oosend", [c_resize, v_result, c_length], resulttype=ootype.Void)
c_setitem = inputconst(ootype.Void, "ll_setitem_fast")
for i, v_item in enumerate(items_v):
ci = inputconst(Signed, i)
llops.genop("oosend", [c_setitem, v_result, ci, v_item], resulttype=ootype.Void)
return v_result
def ll_newlist(LIST, length):
lst = ootype.new(LIST)
lst._ll_resize(length)
return lst
# ____________________________________________________________
#
# Iteration.
class ListIteratorRepr(AbstractListIteratorRepr):
def __init__(self, r_list):
self.r_list = r_list
self.lowleveltype = ootype.Record(
{"iterable": r_list.lowleveltype, "index": ootype.Signed})
self.ll_listiter = ll_listiter
self.ll_listnext = ll_listnext
def ll_listiter(ITER, lst):
iter = ootype.new(ITER)
iter.iterable = lst
iter.index = 0
return iter
def ll_listnext(iter):
l = iter.iterable
index = iter.index
if index >= l.ll_length():
raise StopIteration
iter.index = index + 1
return l.ll_getitem_fast(index)
| Python |
from pypy.rpython.rmodel import CanBeNull, Repr, inputconst, impossible_repr
from pypy.rpython.rpbc import AbstractClassesPBCRepr, AbstractMethodsPBCRepr, \
AbstractMultipleFrozenPBCRepr, MethodOfFrozenPBCRepr, \
AbstractFunctionsPBCRepr, AbstractMultipleUnrelatedFrozenPBCRepr, \
none_frozen_pbc_repr
from pypy.rpython.rclass import rtype_new_instance, getinstancerepr
from pypy.rpython.rpbc import get_concrete_calltable
from pypy.rpython import callparse
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.ootypesystem.rclass import ClassRepr, InstanceRepr
from pypy.rpython.ootypesystem.rclass import mangle
from pypy.annotation import model as annmodel
from pypy.annotation import description
from pypy.annotation.pairtype import pairtype
from pypy.objspace.flow.model import Constant, Variable
import types
def rtype_is_None(robj1, rnone2, hop, pos=0):
if robj1 == none_frozen_pbc_repr:
return hop.inputconst(ootype.Bool, True)
v1 = hop.inputarg(robj1, pos)
v2 = hop.genop('oononnull', [v1], resulttype=ootype.Bool)
v3 = hop.genop('bool_not', [v2], resulttype=ootype.Bool)
return v3
class FunctionsPBCRepr(AbstractFunctionsPBCRepr):
"""Representation selected for a PBC of function(s)."""
def setup_specfunc(self):
fields = {}
for row in self.uniquerows:
fields[row.attrname] = row.fntype
return ootype.Instance('specfunc', ootype.ROOT, fields)
def create_specfunc(self):
return ootype.new(self.lowleveltype)
def get_specfunc_row(self, llop, v, c_rowname, resulttype):
return llop.genop('oogetfield', [v, c_rowname], resulttype=resulttype)
class ClassesPBCRepr(AbstractClassesPBCRepr):
def _instantiate_runtime_class(self, hop, v_meta, r_instance):
classdef = hop.s_result.classdef
c_class_ = hop.inputconst(ootype.Void, "class_")
v_class = hop.genop('oogetfield', [v_meta, c_class_],
resulttype=ootype.Class)
resulttype = getinstancerepr(hop.rtyper, classdef).lowleveltype
v_instance = hop.genop('runtimenew', [v_class], resulttype=resulttype)
c_meta = hop.inputconst(ootype.Void, "meta")
hop.genop('oosetfield', [v_instance, c_meta, v_meta],
resulttype=ootype.Void)
return v_instance
def row_method_name(methodname, rowname):
if rowname is None:
return methodname
else:
return "%s_%s" % (methodname, rowname)
class MethodImplementations(object):
def __init__(self, rtyper, methdescs):
samplemdesc = methdescs.iterkeys().next()
concretetable, uniquerows = get_concrete_calltable(rtyper,
samplemdesc.funcdesc.getcallfamily())
self.row_mapping = {}
for row in uniquerows:
sample_as_static_meth = row.itervalues().next()
SM = ootype.typeOf(sample_as_static_meth)
M = ootype.Meth(SM.ARGS[1:], SM.RESULT) # cut self
self.row_mapping[row.attrname] = row, M
def get(rtyper, s_pbc):
lst = list(s_pbc.descriptions)
lst.sort()
key = tuple(lst)
try:
return rtyper.oo_meth_impls[key]
except KeyError:
methodsimpl = MethodImplementations(rtyper, s_pbc.descriptions)
rtyper.oo_meth_impls[key] = methodsimpl
return methodsimpl
get = staticmethod(get)
def get_impl(self, name, methdesc, is_finalizer=False):
impls = {}
flags = {}
if is_finalizer:
flags['finalizer'] = True
for rowname, (row, M) in self.row_mapping.iteritems():
if methdesc is None:
m = ootype.meth(M, _name=name, abstract=True, **flags)
else:
impl_graph = row[methdesc.funcdesc].graph
m = ootype.meth(M, _name=name, graph=impl_graph, **flags)
derived_name = row_method_name(name, rowname)
impls[derived_name] = m
return impls
class MethodsPBCRepr(AbstractMethodsPBCRepr):
def __init__(self, rtyper, s_pbc):
AbstractMethodsPBCRepr.__init__(self, rtyper, s_pbc)
sampledesc = s_pbc.descriptions.iterkeys().next()
self.concretetable, _ = get_concrete_calltable(rtyper,
sampledesc.funcdesc.getcallfamily())
def rtype_simple_call(self, hop):
return self.call("simple_call", hop)
def rtype_call_args(self, hop):
return self.call("call_args", hop)
def call(self, opname, hop):
s_pbc = hop.args_s[0] # possibly more precise than self.s_pbc
args_s = hop.args_s[1:]
shape, index, callfamily = self._get_shape_index_callfamily(opname, s_pbc, args_s)
row_of_graphs = callfamily.calltables[shape][index]
anygraph = row_of_graphs.itervalues().next() # pick any witness
hop2 = self.add_instance_arg_to_hop(hop, opname == "call_args")
vlist = callparse.callparse(self.rtyper, anygraph, hop2, opname,
r_self = self.r_im_self)
rresult = callparse.getrresult(self.rtyper, anygraph)
derived_mangled = self._get_method_name(opname, s_pbc, args_s)
cname = hop.inputconst(ootype.Void, derived_mangled)
hop.exception_is_here()
# sanity check: make sure that INSTANCE has the method
self.r_im_self.setup()
INSTANCE, meth = self.r_im_self.lowleveltype._lookup(derived_mangled)
assert meth is not None, 'Missing method %s in class %s'\
% (derived_mangled, self.r_im_self.lowleveltype)
v = hop.genop("oosend", [cname]+vlist, resulttype=rresult)
if hop.r_result is impossible_repr:
return None # see test_always_raising_methods
else:
return hop.llops.convertvar(v, rresult, hop.r_result)
def _get_shape_index_callfamily(self, opname, s_pbc, args_s):
bk = self.rtyper.annotator.bookkeeper
args = bk.build_args(opname, args_s)
args = args.prepend(self.s_im_self)
descs = [desc.funcdesc for desc in s_pbc.descriptions]
callfamily = descs[0].getcallfamily()
shape, index = description.FunctionDesc.variant_for_call_site(
bk, callfamily, descs, args)
return shape, index, callfamily
def _get_method_name(self, opname, s_pbc, args_s):
shape, index, callfamily = self._get_shape_index_callfamily(opname, s_pbc, args_s)
mangled = mangle(self.methodname, self.rtyper.getconfig())
row = self.concretetable[shape, index]
derived_mangled = row_method_name(mangled, row.attrname)
return derived_mangled
class __extend__(pairtype(InstanceRepr, MethodsPBCRepr)):
def convert_from_to(_, v, llops):
return v
# ____________________________________________________________
PBCROOT = ootype.Instance('pbcroot', ootype.ROOT)
class MultipleFrozenPBCRepr(AbstractMultipleFrozenPBCRepr):
"""Representation selected for multiple non-callable pre-built constants."""
def __init__(self, rtyper, access_set):
self.rtyper = rtyper
self.access_set = access_set
self.lowleveltype = ootype.Instance('pbc', PBCROOT)
self.pbc_cache = {}
def _setup_repr(self):
fields_list = self._setup_repr_fields()
ootype.addFields(self.lowleveltype, dict(fields_list))
def create_instance(self):
return ootype.new(self.lowleveltype)
def null_instance(self):
return ootype.null(self.lowleveltype)
def getfield(self, vpbc, attr, llops):
mangled_name, r_value = self.fieldmap[attr]
cmangledname = inputconst(ootype.Void, mangled_name)
return llops.genop('oogetfield', [vpbc, cmangledname],
resulttype = r_value)
class MultipleUnrelatedFrozenPBCRepr(AbstractMultipleUnrelatedFrozenPBCRepr):
"""Representation selected for multiple non-callable pre-built constants
with no common access set."""
lowleveltype = PBCROOT
def convert_pbc(self, pbc):
if ootype.typeOf(pbc) != PBCROOT:
pbc = ootype.ooupcast(PBCROOT, pbc)
return pbc
def create_instance(self):
return ootype.new(PBCROOT)
def null_instance(self):
return ootype.null(PBCROOT)
class __extend__(pairtype(MultipleFrozenPBCRepr,
MultipleUnrelatedFrozenPBCRepr)):
def convert_from_to((robj1, robj2), v, llops):
return llops.genop('ooupcast', [v], resulttype=PBCROOT)
| Python |
from pypy.rpython.rmodel import inputconst
from pypy.rpython.rtuple import AbstractTupleRepr, AbstractTupleIteratorRepr
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.ootypesystem import rstr
class TupleRepr(AbstractTupleRepr):
rstr_ll = rstr.LLHelpers
def __init__(self, rtyper, items_r):
AbstractTupleRepr.__init__(self, rtyper, items_r)
self.lowleveltype = ootype.Record(dict(zip(self.fieldnames, self.lltypes)))
def newtuple(cls, llops, r_tuple, items_v):
# items_v should have the lowleveltype of the internal reprs
if len(r_tuple.items_r) == 0:
return inputconst(r_tuple, ()) # always the same empty tuple
c1 = inputconst(ootype.Void, r_tuple.lowleveltype)
v_result = llops.genop("new", [c1], resulttype=r_tuple.lowleveltype)
for i in range(len(r_tuple.items_r)):
cname = inputconst(ootype.Void, r_tuple.fieldnames[i])
llops.genop("oosetfield", [v_result, cname, items_v[i]])
return v_result
newtuple = classmethod(newtuple)
def instantiate(self):
return ootype.new(self.lowleveltype)
def getitem_internal(self, llops, v_tuple, index):
# ! returns internal repr lowleveltype
name = self.fieldnames[index]
llresult = self.lltypes[index]
cname = inputconst(ootype.Void, name)
return llops.genop("oogetfield", [v_tuple, cname], resulttype=llresult)
def rtype_id(self, hop):
vinst, = hop.inputargs(self)
return hop.genop('ooidentityhash', [vinst], resulttype=ootype.Signed)
def rtype_bltn_list(self, hop):
from pypy.rpython.ootypesystem import rlist
v_tup = hop.inputarg(self, 0)
LIST = hop.r_result.lowleveltype
c_list = inputconst(ootype.Void, LIST)
v_list = hop.genop('new', [c_list], resulttype=LIST)
c_resize = inputconst(ootype.Void, '_ll_resize')
c_setitem = inputconst(ootype.Void, 'll_setitem_fast')
c_length = inputconst(ootype.Signed, len(self.items_r))
hop.genop('oosend', [c_resize, v_list, c_length], resulttype=ootype.Void)
for index in range(len(self.items_r)):
name = self.fieldnames[index]
r_item = self.items_r[index]
c_name = hop.inputconst(ootype.Void, name)
v_item = hop.genop("oogetfield", [v_tup, c_name], resulttype=r_item)
v_item = hop.llops.convertvar(v_item, r_item, hop.r_result.item_repr)
c_index = inputconst(ootype.Signed, index)
hop.genop('oosend', [c_setitem, v_list, c_index, v_item], resulttype=ootype.Void)
return v_list
def rtype_newtuple(hop):
return TupleRepr._rtype_newtuple(hop)
newtuple = TupleRepr.newtuple
# ____________________________________________________________
#
# Iteration.
class Length1TupleIteratorRepr(AbstractTupleIteratorRepr):
def __init__(self, r_tuple):
self.r_tuple = r_tuple
self.lowleveltype = ootype.Record(
{"iterable": r_tuple.lowleveltype, "index": ootype.Signed})
self.ll_tupleiter = ll_tupleiter
self.ll_tuplenext = ll_tuplenext
TupleRepr.IteratorRepr = Length1TupleIteratorRepr
def ll_tupleiter(ITERINST, tuple):
iter = ootype.new(ITERINST)
iter.iterable = tuple
return iter
def ll_tuplenext(iter):
# for iterating over length 1 tuples only!
t = iter.iterable
if t:
iter.iterable = ootype.null(ootype.typeOf(t))
return t.item0
else:
raise StopIteration
| Python |
from pypy.rpython.ootypesystem import ootype
# ____________________________________________________________
# Implementation of the 'canfold' oo operations
def op_ooupcast(INST, inst):
return ootype.ooupcast(INST, inst)
op_ooupcast.need_result_type = True
def op_oodowncast(INST, inst):
return ootype.oodowncast(INST, inst)
op_oodowncast.need_result_type = True
def op_oononnull(inst):
checkinst(inst)
return bool(inst)
def op_oois(obj1, obj2):
if is_inst(obj1):
checkinst(obj2)
return obj1 == obj2 # NB. differently-typed NULLs must be equal
elif isinstance(obj1, ootype._class):
assert isinstance(obj2, ootype._class)
return obj1 is obj2
else:
assert False, "oois on something silly"
def op_instanceof(inst, INST):
return ootype.instanceof(inst, INST)
def op_classof(inst):
return ootype.classof(inst)
def op_subclassof(class1, class2):
return ootype.subclassof(class1, class2)
def is_inst(inst):
return isinstance(ootype.typeOf(inst), (ootype.Instance, ootype.BuiltinType, ootype.StaticMethod))
def checkinst(inst):
assert is_inst(inst)
# ____________________________________________________________
def get_op_impl(opname):
# get the op_xxx() function from the globals above
return globals()['op_' + opname]
| Python |
from pypy.rpython.lltypesystem.lltype import LowLevelType, Signed, Unsigned, Float, Char
from pypy.rpython.lltypesystem.lltype import Bool, Void, UniChar, typeOf, \
Primitive, isCompatibleType, enforce, saferecursive, SignedLongLong, UnsignedLongLong
from pypy.rpython.lltypesystem.lltype import frozendict, isCompatibleType
from pypy.rlib.rarithmetic import intmask
from pypy.rlib import objectmodel
from pypy.tool.uid import uid
try:
set
except NameError:
from sets import Set as set
STATICNESS = True
class OOType(LowLevelType):
def _is_compatible(TYPE1, TYPE2):
if TYPE1 == TYPE2:
return True
if isinstance(TYPE1, Instance) and isinstance(TYPE2, Instance):
return isSubclass(TYPE1, TYPE2)
else:
return False
def _enforce(TYPE2, value):
TYPE1 = typeOf(value)
if TYPE1 == TYPE2:
return value
if isinstance(TYPE1, Instance) and isinstance(TYPE2, Instance):
if isSubclass(TYPE1, TYPE2):
return value._enforce(TYPE2)
raise TypeError
class Class(OOType):
def _defl(self):
return nullruntimeclass
Class = Class()
class Instance(OOType):
"""this is the type of user-defined objects"""
def __init__(self, name, superclass, fields={}, methods={},
_is_root=False, _hints = {}):
self._name = name
self._hints = frozendict(_hints)
self._subclasses = []
if _is_root:
self._superclass = None
else:
if superclass is not None:
self._set_superclass(superclass)
self._methods = frozendict()
self._fields = frozendict()
self._overridden_defaults = frozendict()
self._add_fields(fields)
self._add_methods(methods)
self._null = make_null_instance(self)
self._class = _class(self)
def __eq__(self, other):
return self is other
def __ne__(self, other):
return self is not other
def __hash__(self):
return object.__hash__(self)
def _defl(self):
return self._null
def _example(self): return new(self)
def __repr__(self):
return '<%s>' % (self,)
def __str__(self):
return '%s(%s)' % (self.__class__.__name__, self._name)
def _set_superclass(self, superclass):
assert isinstance(superclass, Instance)
self._superclass = superclass
self._superclass._add_subclass(self)
def _add_subclass(self, INSTANCE):
assert isinstance(INSTANCE, Instance)
self._subclasses.append(INSTANCE)
def _add_fields(self, fields):
fields = fields.copy() # mutated below
for name, defn in fields.iteritems():
_, meth = self._lookup(name)
if meth is not None:
raise TypeError("Cannot add field %r: method already exists" % name)
if self._superclass is not None:
if self._superclass._has_field(name):
raise TypeError("Field %r exists in superclass" % name)
if type(defn) is not tuple:
if isinstance(defn, Meth):
raise TypeError("Attempting to store method in field")
fields[name] = (defn, defn._defl())
else:
ootype, default = defn
if isinstance(ootype, Meth):
raise TypeError("Attempting to store method in field")
if ootype != typeOf(default):
raise TypeError("Expected type %r for default" % (ootype,))
self._fields.update(fields)
def _override_default_for_fields(self, fields):
# sanity check
for field in fields:
INST, TYPE = self._superclass._lookup_field(field)
assert TYPE is not None, "Can't find field %s in superclasses" % field
self._overridden_defaults.update(fields)
def _add_methods(self, methods):
# Note to the unwary: _add_methods adds *methods* whereas
# _add_fields adds *descriptions* of fields. This is obvious
# if you are in the right state of mind (swiss?), but
# certainly not necessarily if not.
for name, method in methods.iteritems():
if self._has_field(name):
raise TypeError("Can't add method %r: field already exists" % name)
if not isinstance(typeOf(method), Meth):
raise TypeError("added methods must be _meths, not %s" % type(method))
self._methods.update(methods)
def _init_instance(self, instance):
if self._superclass is not None:
self._superclass._init_instance(instance)
for name, (ootype, default) in self._fields.iteritems():
instance.__dict__[name] = enforce(ootype, default)
for name, (ootype, default) in self._overridden_defaults.iteritems():
instance.__dict__[name] = enforce(ootype, default)
def _has_field(self, name):
try:
self._fields[name]
return True
except KeyError:
if self._superclass is None:
return False
return self._superclass._has_field(name)
def _field_type(self, name):
try:
return self._fields[name][0]
except KeyError:
if self._superclass is None:
raise TypeError("No field names %r" % name)
return self._superclass._field_type(name)
_check_field = _field_type
def _lookup_field(self, name):
field = self._fields.get(name)
if field is None and self._superclass is not None:
return self._superclass._lookup_field(name)
try:
return self, field[0]
except TypeError:
return self, None
def _lookup(self, meth_name):
meth = self._methods.get(meth_name)
if meth is None and self._superclass is not None:
return self._superclass._lookup(meth_name)
return self, meth
def _allfields(self):
if self._superclass is None:
all = {}
else:
all = self._superclass._allfields()
all.update(self._fields)
return all
class SpecializableType(OOType):
def _specialize_type(self, TYPE, generic_types):
if isinstance(TYPE, SpecializableType):
res = TYPE._specialize(generic_types)
else:
res = generic_types.get(TYPE, TYPE)
assert res is not None
return res
def _specialize(self, generic_types):
raise NotImplementedError
class StaticMethod(SpecializableType):
__slots__ = ['_null']
def __init__(self, args, result):
self.ARGS = tuple(args)
self.RESULT = result
self._null = _static_meth(self, _callable=None)
def _example(self):
_retval = self.RESULT._example()
return _static_meth(self, _callable=lambda *args: _retval)
def _defl(self):
return null(self)
def __repr__(self):
return "<%s(%s, %s)>" % (self.__class__.__name__, list(self.ARGS), self.RESULT)
def _specialize(self, generic_types):
ARGS = tuple([self._specialize_type(ARG, generic_types)
for ARG in self.ARGS])
RESULT = self._specialize_type(self.RESULT, generic_types)
return self.__class__(ARGS, RESULT)
class Meth(StaticMethod):
def __init__(self, args, result):
StaticMethod.__init__(self, args, result)
class BuiltinType(SpecializableType):
def _example(self):
return new(self)
def _defl(self):
return self._null
def _get_interp_class(self):
raise NotImplementedError
class Record(BuiltinType):
# We try to keep Record as similar to Instance as possible, so backends
# can treat them polymorphically, if they choose to do so.
def __init__(self, fields):
self._fields = frozendict()
for name, ITEMTYPE in fields.items():
self._fields[name] = ITEMTYPE, ITEMTYPE._defl()
self._null = _null_record(self)
def _defl(self):
return self._null
def _get_interp_class(self):
return _record
def _field_type(self, name):
try:
return self._fields[name][0]
except KeyError:
raise TypeError("No field names %r" % name)
_check_field = _field_type
def _lookup(self, meth_name):
return self, None
def _lookup_field(self, name):
try:
return self, self._field_type(name)
except TypeError:
return self, None
def __str__(self):
item_str = ["%s: %s" % (str(name), str(ITEMTYPE))
for name, (ITEMTYPE, _) in self._fields.items()]
return '%s(%s)' % (self.__class__.__name__, ", ".join(item_str))
class BuiltinADTType(BuiltinType):
def _setup_methods(self, generic_types, can_raise=[]):
methods = {}
for name, meth in self._GENERIC_METHODS.iteritems():
args = [self._specialize_type(arg, generic_types) for arg in meth.ARGS]
result = self._specialize_type(meth.RESULT, generic_types)
methods[name] = Meth(args, result)
self._METHODS = frozendict(methods)
self._can_raise = tuple(can_raise)
def _lookup(self, meth_name):
METH = self._METHODS.get(meth_name)
meth = None
if METH is not None:
cls = self._get_interp_class()
can_raise = meth_name in self._can_raise
meth = _meth(METH, _name=meth_name, _callable=getattr(cls, meth_name), _can_raise=can_raise)
meth._virtual = False
return self, meth
# WARNING: the name 'String' is rebound at the end of file
class String(BuiltinADTType):
SELFTYPE_T = object()
def __init__(self):
self._null = _null_string(self)
generic_types = { self.SELFTYPE_T: self }
self._GENERIC_METHODS = frozendict({
"ll_stritem_nonneg": Meth([Signed], Char),
"ll_strlen": Meth([], Signed),
"ll_strconcat": Meth([self.SELFTYPE_T], self.SELFTYPE_T),
"ll_streq": Meth([self.SELFTYPE_T], Bool),
"ll_strcmp": Meth([self.SELFTYPE_T], Signed),
"ll_startswith": Meth([self.SELFTYPE_T], Bool),
"ll_endswith": Meth([self.SELFTYPE_T], Bool),
"ll_find": Meth([self.SELFTYPE_T, Signed, Signed], Signed),
"ll_rfind": Meth([self.SELFTYPE_T, Signed, Signed], Signed),
"ll_count": Meth([self.SELFTYPE_T, Signed, Signed], Signed),
"ll_find_char": Meth([Char, Signed, Signed], Signed),
"ll_rfind_char": Meth([Char, Signed, Signed], Signed),
"ll_count_char": Meth([Char, Signed, Signed], Signed),
"ll_strip": Meth([Char, Bool, Bool], self.SELFTYPE_T),
"ll_upper": Meth([], self.SELFTYPE_T),
"ll_lower": Meth([], self.SELFTYPE_T),
"ll_substring": Meth([Signed, Signed], self.SELFTYPE_T), # ll_substring(start, count)
"ll_split_chr": Meth([Char], List(self.SELFTYPE_T)),
"ll_contains": Meth([Char], Bool),
"ll_replace_chr_chr": Meth([Char, Char], self.SELFTYPE_T),
})
self._setup_methods(generic_types)
def _enforce(self, value):
TYPE = typeOf(value)
if TYPE == Char:
return make_string(value)
else:
return BuiltinADTType._enforce(self, value)
# TODO: should it return _null or ''?
def _defl(self):
return make_string("")
def _example(self):
return self._defl()
def _get_interp_class(self):
return _string
def _specialize(self, generic_types):
return self
# WARNING: the name 'StringBuilder' is rebound at the end of file
class StringBuilder(BuiltinADTType):
def __init__(self):
self._null = _null_string_builder(self)
self._GENERIC_METHODS = frozendict({
"ll_allocate": Meth([Signed], Void),
"ll_append_char": Meth([Char], Void),
"ll_append": Meth([String], Void),
"ll_build": Meth([], String),
})
self._setup_methods({})
def _defl(self):
return self._null
def _get_interp_class(self):
return _string_builder
def _specialize(self, generic_types):
return self
class List(BuiltinADTType):
# placeholders for types
# make sure that each derived class has his own SELFTYPE_T
# placeholder, because we want backends to distinguish that.
SELFTYPE_T = object()
ITEMTYPE_T = object()
def __init__(self, ITEMTYPE=None):
self._ITEMTYPE = ITEMTYPE
self._null = _null_list(self)
if ITEMTYPE is not None:
self._init_methods()
def _init_methods(self):
# This defines the abstract list interface that backends will
# have to map to their native list implementations.
# 'ITEMTYPE_T' is used as a placeholder for indicating
# arguments that should have ITEMTYPE type. 'SELFTYPE_T' indicates 'self'
# XXX clean-up later! Rename _ITEMTYPE to ITEM. For now they are
# just synonyms, please use ITEM in new code.
self.ITEM = self._ITEMTYPE
generic_types = {
self.SELFTYPE_T: self,
self.ITEMTYPE_T: self._ITEMTYPE,
}
# the methods are named after the ADT methods of lltypesystem's lists
self._GENERIC_METHODS = frozendict({
# "name": Meth([ARGUMENT1_TYPE, ARGUMENT2_TYPE, ...], RESULT_TYPE)
"ll_length": Meth([], Signed),
"ll_getitem_fast": Meth([Signed], self.ITEMTYPE_T),
"ll_setitem_fast": Meth([Signed, self.ITEMTYPE_T], Void),
"_ll_resize_ge": Meth([Signed], Void),
"_ll_resize_le": Meth([Signed], Void),
"_ll_resize": Meth([Signed], Void),
})
self._setup_methods(generic_types)
# this is the equivalent of the lltypesystem ll_newlist that is
# marked as typeMethod.
def ll_newlist(self, length):
from pypy.rpython.ootypesystem import rlist
return rlist.ll_newlist(self, length)
# NB: We are expecting Lists of the same ITEMTYPE to compare/hash
# equal. We don't redefine __eq__/__hash__ since the implementations
# from LowLevelType work fine, especially in the face of recursive
# data structures. But it is important to make sure that attributes
# of supposedly equal Lists compare/hash equal.
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, List):
return False
if self._ITEMTYPE is None or other._ITEMTYPE is None:
raise TypeError("Can't compare uninitialized List type.")
return BuiltinADTType.__eq__(self, other)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
if self._ITEMTYPE is None:
raise TypeError("Can't hash uninitialized List type.")
return BuiltinADTType.__hash__(self)
def __str__(self):
return '%s(%s)' % (self.__class__.__name__,
saferecursive(str, "...")(self._ITEMTYPE))
def _get_interp_class(self):
return _list
def _specialize(self, generic_types):
ITEMTYPE = self._specialize_type(self._ITEMTYPE, generic_types)
return self.__class__(ITEMTYPE)
def _defl(self):
return self._null
def _set_itemtype(self, ITEMTYPE):
self._ITEMTYPE = ITEMTYPE
self._init_methods()
class Dict(BuiltinADTType):
# placeholders for types
SELFTYPE_T = object()
KEYTYPE_T = object()
VALUETYPE_T = object()
def __init__(self, KEYTYPE=None, VALUETYPE=None):
self._KEYTYPE = KEYTYPE
self._VALUETYPE = VALUETYPE
self._null = _null_dict(self)
if self._is_initialized():
self._init_methods()
def _is_initialized(self):
return self._KEYTYPE is not None and self._VALUETYPE is not None
def _init_methods(self):
# XXX clean-up later! Rename _KEYTYPE and _VALUETYPE to KEY and VALUE.
# For now they are just synonyms, please use KEY/VALUE in new code.
self.KEY = self._KEYTYPE
self.VALUE = self._VALUETYPE
self._generic_types = frozendict({
self.SELFTYPE_T: self,
self.KEYTYPE_T: self._KEYTYPE,
self.VALUETYPE_T: self._VALUETYPE
})
# ll_get() is always used just after a call to ll_contains(),
# always with the same key, so backends can optimize/cache the
# result
self._GENERIC_METHODS = frozendict({
"ll_length": Meth([], Signed),
"ll_get": Meth([self.KEYTYPE_T], self.VALUETYPE_T),
"ll_set": Meth([self.KEYTYPE_T, self.VALUETYPE_T], Void),
"ll_remove": Meth([self.KEYTYPE_T], Bool), # return False is key was not present
"ll_contains": Meth([self.KEYTYPE_T], Bool),
"ll_clear": Meth([], Void),
"ll_get_items_iterator": Meth([], DictItemsIterator(self.KEYTYPE_T, self.VALUETYPE_T)),
})
self._setup_methods(self._generic_types)
# NB: We are expecting Dicts of the same KEYTYPE, VALUETYPE to
# compare/hash equal. We don't redefine __eq__/__hash__ since the
# implementations from LowLevelType work fine, especially in the
# face of recursive data structures. But it is important to make
# sure that attributes of supposedly equal Dicts compare/hash
# equal.
def __str__(self):
return '%s(%s, %s)' % (self.__class__.__name__,
self._KEYTYPE, saferecursive(str, "...")(self._VALUETYPE))
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, Dict):
return False
if not self._is_initialized() or not other._is_initialized():
raise TypeError("Can't compare uninitialized Dict type.")
return BuiltinADTType.__eq__(self, other)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
if not self._is_initialized():
raise TypeError("Can't hash uninitialized Dict type.")
return BuiltinADTType.__hash__(self)
def _get_interp_class(self):
return _dict
def _specialize(self, generic_types):
KEYTYPE = self._specialize_type(self._KEYTYPE, generic_types)
VALUETYPE = self._specialize_type(self._VALUETYPE, generic_types)
return self.__class__(KEYTYPE, VALUETYPE)
def _set_types(self, KEYTYPE, VALUETYPE):
self._KEYTYPE = KEYTYPE
self._VALUETYPE = VALUETYPE
self._init_methods()
class CustomDict(Dict):
def __init__(self, KEYTYPE=None, VALUETYPE=None):
Dict.__init__(self, KEYTYPE, VALUETYPE)
self._null = _null_custom_dict(self)
if self._is_initialized():
self._init_methods()
def _init_methods(self):
Dict._init_methods(self)
EQ_FUNC = StaticMethod([self.KEYTYPE_T, self.KEYTYPE_T], Bool)
HASH_FUNC = StaticMethod([self.KEYTYPE_T], Signed)
self._GENERIC_METHODS['ll_set_functions'] = Meth([EQ_FUNC, HASH_FUNC], Void)
self._GENERIC_METHODS['ll_copy'] = Meth([], self.SELFTYPE_T)
self._setup_methods(self._generic_types, can_raise=['ll_get', 'll_set', 'll_remove', 'll_contains'])
def _get_interp_class(self):
return _custom_dict
class DictItemsIterator(BuiltinADTType):
SELFTYPE_T = object()
KEYTYPE_T = object()
VALUETYPE_T = object()
def __init__(self, KEYTYPE, VALUETYPE):
self._KEYTYPE = KEYTYPE
self._VALUETYPE = VALUETYPE
self._null = _null_dict_items_iterator(self)
generic_types = {
self.SELFTYPE_T: self,
self.KEYTYPE_T: KEYTYPE,
self.VALUETYPE_T: VALUETYPE
}
# Dictionaries are not allowed to be changed during an
# iteration. The ll_go_next method should check this condition
# and raise RuntimeError in that case.
self._GENERIC_METHODS = frozendict({
"ll_go_next": Meth([], Bool), # move forward; return False is there is no more data available
"ll_current_key": Meth([], self.KEYTYPE_T),
"ll_current_value": Meth([], self.VALUETYPE_T),
})
self._setup_methods(generic_types, can_raise=['ll_go_next'])
def __str__(self):
return '%s%s' % (self.__class__.__name__,
saferecursive(str, "(...)")((self._KEYTYPE, self._VALUETYPE)))
def _get_interp_class(self):
return _dict_items_iterator
def _specialize(self, generic_types):
KEYTYPE = self._specialize_type(self._KEYTYPE, generic_types)
VALUETYPE = self._specialize_type(self._VALUETYPE, generic_types)
return self.__class__(KEYTYPE, VALUETYPE)
# ____________________________________________________________
class _class(object):
_TYPE = Class
def __init__(self, INSTANCE):
self._INSTANCE = INSTANCE
nullruntimeclass = _class(None)
class _instance(object):
def __init__(self, INSTANCE):
self.__dict__["_TYPE"] = INSTANCE
INSTANCE._init_instance(self)
def __repr__(self):
return '<%s>' % (self,)
def __str__(self):
return '%r inst at 0x%x' % (self._TYPE._name, uid(self))
def __getattr__(self, name):
DEFINST, meth = self._TYPE._lookup(name)
if meth is not None:
return meth._bound(DEFINST, self)
self._TYPE._check_field(name)
return self.__dict__[name]
def __setattr__(self, name, value):
self.__getattr__(name)
FLDTYPE = self._TYPE._field_type(name)
try:
val = enforce(FLDTYPE, value)
except TypeError:
raise TypeError("Expected type %r" % FLDTYPE)
self.__dict__[name] = value
def __nonzero__(self):
return True # better be explicit -- overridden in _null_instance
def __eq__(self, other):
if not isinstance(other, _instance):
raise TypeError("comparing an _instance with %r" % (other,))
return self is other # same comment as __nonzero__
def __ne__(self, other):
return not (self == other)
def _instanceof(self, INSTANCE):
assert isinstance(INSTANCE, Instance)
return bool(self) and isSubclass(self._TYPE, INSTANCE)
def _classof(self):
assert bool(self)
return runtimeClass(self._TYPE)
def _upcast(self, INSTANCE):
assert instanceof(self, INSTANCE)
return self
_enforce = _upcast
def _downcast(self, INSTANCE):
assert instanceof(self, INSTANCE)
return self
def _identityhash(self):
if self:
return intmask(id(self))
else:
return 0 # for all null instances
def _null_mixin(klass):
class mixin(object):
def __str__(self):
try:
name = self._TYPE._name
except AttributeError:
name = self._TYPE
return '%r null inst' % (name,)
def __getattribute__(self, name):
if name.startswith("_"):
return object.__getattribute__(self, name)
raise RuntimeError("Access to field in null object")
def __setattr__(self, name, value):
klass.__setattr__(self, name, value)
raise RuntimeError("Assignment to field in null object")
def __nonzero__(self):
return False
def __eq__(self, other):
if not isinstance(other, klass):
raise TypeError("comparing an %s with %r" % (klass.__name__, other))
return not other
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(self._TYPE)
return mixin
class _null_instance(_null_mixin(_instance), _instance):
def __init__(self, INSTANCE):
self.__dict__["_TYPE"] = INSTANCE
class _view(object):
def __init__(self, INSTANCE, inst):
self.__dict__['_TYPE'] = INSTANCE
assert isinstance(inst, _instance)
assert isSubclass(inst._TYPE, INSTANCE)
self.__dict__['_inst'] = inst
def __repr__(self):
if self._TYPE == self._inst._TYPE:
return repr(self._inst)
else:
return '<%r view of %s>' % (self._TYPE._name, self._inst)
def __ne__(self, other):
return not (self == other)
def __eq__(self, other):
assert isinstance(other, _view)
return self._inst == other._inst
def __hash__(self):
return hash(self._inst)
def __nonzero__(self):
return bool(self._inst)
def __setattr__(self, name, value):
self._TYPE._check_field(name)
setattr(self._inst, name, value)
def __getattr__(self, name):
_, meth = self._TYPE._lookup(name)
meth or self._TYPE._check_field(name)
res = getattr(self._inst, name)
if meth:
assert isinstance(res, _bound_meth)
return res.__class__(res.DEFINST, _view(res.DEFINST, res.inst), res.meth)
return res
def _instanceof(self, INSTANCE):
return self._inst._instanceof(INSTANCE)
def _classof(self):
return self._inst._classof()
def _upcast(self, INSTANCE):
assert isSubclass(self._TYPE, INSTANCE)
return _view(INSTANCE, self._inst)
_enforce = _upcast
def _downcast(self, INSTANCE):
assert isSubclass(INSTANCE, self._TYPE)
return _view(INSTANCE, self._inst)
def _identityhash(self):
return self._inst._identityhash()
if STATICNESS:
instance_impl = _view
else:
instance_impl = _instance
def make_string(value):
assert isinstance(value, str)
return _string(String, value)
def make_instance(INSTANCE):
inst = _instance(INSTANCE)
if STATICNESS:
inst = _view(INSTANCE, inst)
return inst
def make_null_instance(INSTANCE):
inst = _null_instance(INSTANCE)
if STATICNESS:
inst = _view(INSTANCE, inst)
return inst
class _callable(object):
def __init__(self, TYPE, **attrs):
self._TYPE = TYPE
self._name = "?"
self._callable = None
self.__dict__.update(attrs)
def _checkargs(self, args, check_callable=True):
if len(args) != len(self._TYPE.ARGS):
raise TypeError,"calling %r with wrong argument number: %r" % (self._TYPE, args)
checked_args = []
for a, ARG in zip(args, self._TYPE.ARGS):
try:
if ARG is not Void:
a = enforce(ARG, a)
except TypeError:
raise TypeError,"calling %r with wrong argument types: %r" % (self._TYPE, args)
checked_args.append(a)
if not check_callable:
return checked_args
callb = self._callable
if callb is None:
raise RuntimeError,"calling undefined or null function"
return callb, checked_args
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.__dict__ == other.__dict__)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(frozendict(self.__dict__))
class _static_meth(_callable):
def __init__(self, STATICMETHOD, **attrs):
assert isinstance(STATICMETHOD, StaticMethod)
_callable.__init__(self, STATICMETHOD, **attrs)
def __call__(self, *args):
callb, checked_args = self._checkargs(args)
return callb(*checked_args)
def __repr__(self):
return 'sm %s' % self._name
class _bound_meth(object):
def __init__(self, DEFINST, inst, meth):
self.DEFINST = DEFINST
self.inst = inst
self.meth = meth
def __call__(self, *args):
callb, checked_args = self.meth._checkargs(args)
return callb(self.inst, *checked_args)
class _meth(_callable):
_bound_class = _bound_meth
def __init__(self, METHOD, **attrs):
assert isinstance(METHOD, Meth)
_callable.__init__(self, METHOD, **attrs)
def _bound(self, DEFINST, inst):
TYPE = typeOf(inst)
assert isinstance(TYPE, (Instance, BuiltinType))
return self._bound_class(DEFINST, inst, self)
class _overloaded_meth_desc:
def __init__(self, name, TYPE):
self.name = name
self.TYPE = TYPE
class _overloaded_bound_meth(_bound_meth):
def __init__(self, DEFINST, inst, meth):
self.DEFINST = DEFINST
self.inst = inst
self.meth = meth
def _get_bound_meth(self, *args):
ARGS = tuple([typeOf(arg) for arg in args])
meth = self.meth._resolver.resolve(ARGS)
assert isinstance(meth, _meth)
return meth._bound(self.DEFINST, self.inst)
def __call__(self, *args):
bound_meth = self._get_bound_meth(*args)
return bound_meth(*args)
class OverloadingResolver(object):
def __init__(self, overloadings):
self.overloadings = overloadings
self._check_overloadings()
def _check_overloadings(self):
signatures = set()
for meth in self.overloadings:
ARGS = meth._TYPE.ARGS
if ARGS in signatures:
raise TypeError, 'Bad overloading'
signatures.add(ARGS)
def annotate(self, args_s):
ARGS = tuple([self.annotation_to_lltype(arg_s) for arg_s in args_s])
METH = self.resolve(ARGS)._TYPE
return self.lltype_to_annotation(METH.RESULT)
def resolve(self, ARGS):
# this overloading resolution algorithm is quite simple:
# 1) if there is an exact match between ARGS and meth.ARGS, return meth
# 2) if there is *only one* meth such as ARGS can be converted
# to meth.ARGS with one or more upcasts, return meth
# 3) otherwise, fail
matches = []
for meth in self.overloadings:
METH = meth._TYPE
if METH.ARGS == ARGS:
return meth # case 1
elif self._check_signature(ARGS, METH.ARGS):
matches.append(meth)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
raise TypeError, 'More than one method match, please use explicit casts'
else:
raise TypeError, 'No suitable overloading found for method'
def _check_signature(self, ARGS1, ARGS2):
if len(ARGS1) != len(ARGS2):
return False
for ARG1, ARG2 in zip(ARGS1, ARGS2):
if not self._can_convert_from_to(ARG1, ARG2):
return False
return True
def _can_convert_from_to(self, ARG1, ARG2):
if isinstance(ARG1, Instance) and isinstance(ARG2, Instance) and isSubclass(ARG1, ARG2):
return True
else:
return False
def annotation_to_lltype(cls, ann):
from pypy.annotation import model as annmodel
return annmodel.annotation_to_lltype(ann)
annotation_to_lltype = classmethod(annotation_to_lltype)
def lltype_to_annotation(cls, TYPE):
from pypy.annotation import model as annmodel
return annmodel.lltype_to_annotation(TYPE)
lltype_to_annotation = classmethod(lltype_to_annotation)
class _overloaded_meth(_meth):
_bound_class = _overloaded_bound_meth
_desc_class = _overloaded_meth_desc
def __init__(self, *overloadings, **attrs):
assert '_callable' not in attrs
resolver = attrs.pop('resolver', OverloadingResolver)
_meth.__init__(self, Meth([], Void), _callable=None, **attrs) # use a fake method type
self._resolver = resolver(overloadings)
def _get_desc(self, name, ARGS):
meth = self._resolver.resolve(ARGS)
return _overloaded_meth_desc(name, meth._TYPE)
class _builtin_type(object):
def __getattribute__(self, name):
TYPE = object.__getattribute__(self, "_TYPE")
_, meth = TYPE._lookup(name)
if meth is not None:
return meth._bound(TYPE, self)
return object.__getattribute__(self, name)
class _string(_builtin_type):
def __init__(self, STRING, value = ''):
self._str = value
self._TYPE = STRING
def __hash__(self):
return hash(self._str)
def __cmp__(self, other):
return cmp(self._str, other._str)
def ll_stritem_nonneg(self, i):
# NOT_RPYTHON
s = self._str
assert 0 <= i < len(s)
return s[i]
def ll_strlen(self):
# NOT_RPYTHON
return len(self._str)
def ll_strconcat(self, s):
# NOT_RPYTHON
return make_string(self._str + s._str)
def ll_streq(self, s):
# NOT_RPYTON
return self._str == s._str
def ll_strcmp(self, s):
# NOT_RPYTHON
return cmp(self._str, s._str)
def ll_startswith(self, s):
# NOT_RPYTHON
return self._str.startswith(s._str)
def ll_endswith(self, s):
# NOT_RPYTHON
return self._str.endswith(s._str)
def ll_find(self, s, start, end):
# NOT_RPYTHON
return self._str.find(s._str, start, end)
def ll_rfind(self, s, start, end):
# NOT_RPYTHON
return self._str.rfind(s._str, start, end)
def ll_count(self, s, start, end):
# NOT_RPYTHON
return self._str.count(s._str, start, end)
def ll_find_char(self, ch, start, end):
# NOT_RPYTHON
return self._str.find(ch, start, end)
def ll_rfind_char(self, ch, start, end):
# NOT_RPYTHON
return self._str.rfind(ch, start, end)
def ll_count_char(self, ch, start, end):
# NOT_RPYTHON
return self._str.count(ch, start, end)
def ll_strip(self, ch, left, right):
# NOT_RPYTHON
s = self._str
if left:
s = s.lstrip(ch)
if right:
s = s.rstrip(ch)
return make_string(s)
def ll_upper(self):
# NOT_RPYTHON
return make_string(self._str.upper())
def ll_lower(self):
# NOT_RPYTHON
return make_string(self._str.lower())
def ll_substring(self, start, count):
# NOT_RPYTHON
return make_string(self._str[start:start+count])
def ll_split_chr(self, ch):
# NOT_RPYTHON
res = _list(List(String))
res._list = [make_string(s) for s in self._str.split(ch)]
return res
def ll_contains(self, ch):
# NOT_RPYTHON
return ch in self._str
def ll_replace_chr_chr(self, ch1, ch2):
# NOT_RPYTHON
return make_string(self._str.replace(ch1, ch2))
class _null_string(_null_mixin(_string), _string):
def __init__(self, STRING):
self.__dict__["_TYPE"] = STRING
self.__dict__["_str"] = None
class _string_builder(_builtin_type):
def __init__(self, STRING_BUILDER):
self._TYPE = STRING_BUILDER
self._buf = []
def ll_allocate(self, n):
assert isinstance(n, int)
assert n >= 0
# do nothing
def ll_append_char(self, ch):
assert isinstance(ch, str) and len(ch) == 1
self._buf.append(ch)
def ll_append(self, s):
assert isinstance(s, _string)
self._buf.append(s._str)
def ll_build(self):
return make_string(''.join(self._buf))
class _null_string_builder(_null_mixin(_string_builder), _string_builder):
def __init__(self, STRING_BUILDER):
self.__dict__["_TYPE"] = STRING_BUILDER
class _list(_builtin_type):
def __init__(self, LIST):
self._TYPE = LIST
self._list = []
# The following are implementations of the abstract list interface for
# use by the llinterpreter and ootype tests. There are NOT_RPYTHON
# because the annotator is not supposed to follow them.
def ll_length(self):
# NOT_RPYTHON
return len(self._list)
def _ll_resize_ge(self, length):
# NOT_RPYTHON
if len(self._list) < length:
diff = length - len(self._list)
self._list += [self._TYPE._ITEMTYPE._defl()] * diff
assert len(self._list) >= length
def _ll_resize_le(self, length):
# NOT_RPYTHON
if length < len(self._list):
del self._list[length:]
assert len(self._list) <= length
def _ll_resize(self, length):
# NOT_RPYTHON
if length > len(self._list):
self._ll_resize_ge(length)
elif length < len(self._list):
self._ll_resize_le(length)
assert len(self._list) == length
def ll_getitem_fast(self, index):
# NOT_RPYTHON
assert typeOf(index) == Signed
assert index >= 0
return self._list[index]
def ll_setitem_fast(self, index, item):
# NOT_RPYTHON
assert self._TYPE._ITEMTYPE is Void or typeOf(item) == self._TYPE._ITEMTYPE
assert typeOf(index) == Signed
assert index >= 0
self._list[index] = item
class _null_list(_null_mixin(_list), _list):
def __init__(self, LIST):
self.__dict__["_TYPE"] = LIST
class _dict(_builtin_type):
def __init__(self, DICT):
self._TYPE = DICT
self._dict = {}
self._stamp = 0
self._last_key = object() # placeholder != to everything else
def ll_length(self):
# NOT_RPYTHON
return len(self._dict)
def ll_get(self, key):
# NOT_RPYTHON
assert typeOf(key) == self._TYPE._KEYTYPE
assert key in self._dict
assert key == self._last_key
return self._dict[key]
def ll_set(self, key, value):
# NOT_RPYTHON
assert typeOf(key) == self._TYPE._KEYTYPE
assert typeOf(value) == self._TYPE._VALUETYPE
self._dict[key] = value
self._stamp += 1
def ll_remove(self, key):
# NOT_RPYTHON
assert typeOf(key) == self._TYPE._KEYTYPE
try:
del self._dict[key]
self._stamp += 1
return True
except KeyError:
return False
def ll_contains(self, key):
# NOT_RPYTHON
assert typeOf(key) == self._TYPE._KEYTYPE
self._last_key = key
return key in self._dict
def ll_clear(self):
self._dict.clear()
self._stamp += 1
def ll_get_items_iterator(self):
# NOT_RPYTHON
ITER = DictItemsIterator(self._TYPE._KEYTYPE, self._TYPE._VALUETYPE)
iter = _dict_items_iterator(ITER)
iter._set_dict(self)
return iter
class _null_dict(_null_mixin(_dict), _dict):
def __init__(self, DICT):
self.__dict__["_TYPE"] = DICT
class _custom_dict(_dict):
def __init__(self, DICT):
self._TYPE = DICT
self._stamp = 0
self._dict = 'DICT_NOT_CREATED_YET' # it's created inside ll_set_functions
def ll_set_functions(self, sm_eq, sm_hash):
"NOT_RPYTHON"
key_eq = sm_eq._callable
key_hash = sm_hash._callable
self._dict = objectmodel.r_dict(key_eq, key_hash)
def ll_copy(self):
"NOT_RPYTHON"
res = self.__class__(self._TYPE)
res._dict = self._dict.copy()
return res
class _null_custom_dict(_null_mixin(_custom_dict), _custom_dict):
def __init__(self, DICT):
self.__dict__["_TYPE"] = DICT
class _dict_items_iterator(_builtin_type):
def __init__(self, ITER):
self._TYPE = ITER
self._index = -1
def _set_dict(self, d):
self._dict = d
self._items = d._dict.items()
self._stamp = d._stamp
def _check_stamp(self):
if self._stamp != self._dict._stamp:
raise RuntimeError, 'Dictionary changed during iteration'
def ll_go_next(self):
# NOT_RPYTHON
self._check_stamp()
self._index += 1
if self._index >= len(self._items):
return False
else:
return True
def ll_current_key(self):
# NOT_RPYTHON
self._check_stamp()
assert 0 <= self._index < len(self._items)
return self._items[self._index][0]
def ll_current_value(self):
# NOT_RPYTHON
self._check_stamp()
assert 0 <= self._index < len(self._items)
return self._items[self._index][1]
class _null_dict_items_iterator(_null_mixin(_dict_items_iterator), _dict_items_iterator):
def __init__(self, ITER):
self.__dict__["_TYPE"] = ITER
class _record(object):
def __init__(self, TYPE):
self._items = {}
self._TYPE = TYPE
for name, (_, default) in TYPE._fields.items():
self._items[name] = default
def __getattr__(self, name):
items = self.__dict__["_items"]
if name in items:
return items[name]
return self.__dict__[name]
def __setattr__(self, name, value):
if hasattr(self, "_items") and name in self._items:
self._items[name] = value
else:
self.__dict__[name] = value
def _identityhash(self):
if self:
return intmask(id(self))
else:
return 0 # for all null tuples
def __hash__(self):
key = tuple(self._items.keys()), tuple(self._items.values())
return hash(key)
def __eq__(self, other):
return self._TYPE == other._TYPE and self._items == other._items
def __ne__(self, other):
return not (self == other)
class _null_record(_null_mixin(_record), _record):
def __init__(self, RECORD):
self.__dict__["_TYPE"] = RECORD
def new(TYPE):
if isinstance(TYPE, Instance):
return make_instance(TYPE)
elif isinstance(TYPE, BuiltinType):
return TYPE._get_interp_class()(TYPE)
def oonewcustomdict(DICT, ll_eq, ll_hash):
d = new(DICT)
d.ll_set_functions(ll_eq, ll_hash)
return d
def runtimenew(class_):
assert isinstance(class_, _class)
assert class_ is not nullruntimeclass
return make_instance(class_._INSTANCE)
def static_meth(FUNCTION, name, **attrs):
return _static_meth(FUNCTION, _name=name, **attrs)
def meth(METHOD, **attrs):
return _meth(METHOD, **attrs)
def overload(*overloadings, **attrs):
return _overloaded_meth(*overloadings, **attrs)
def null(INSTANCE_OR_FUNCTION):
return INSTANCE_OR_FUNCTION._null
def instanceof(inst, INSTANCE):
# this version of instanceof() accepts a NULL instance and always
# returns False in this case.
assert isinstance(typeOf(inst), Instance)
return inst._instanceof(INSTANCE)
def classof(inst):
assert isinstance(typeOf(inst), Instance)
return inst._classof()
def dynamicType(inst):
assert isinstance(typeOf(inst), Instance)
return classof(inst)._INSTANCE
def subclassof(class1, class2):
assert isinstance(class1, _class)
assert isinstance(class2, _class)
assert class1 is not nullruntimeclass
assert class2 is not nullruntimeclass
return isSubclass(class1._INSTANCE, class2._INSTANCE)
def addFields(INSTANCE, fields):
INSTANCE._add_fields(fields)
def addMethods(INSTANCE, methods):
INSTANCE._add_methods(methods)
def overrideDefaultForFields(INSTANCE, fields):
INSTANCE._override_default_for_fields(fields)
def runtimeClass(INSTANCE):
assert isinstance(INSTANCE, Instance)
return INSTANCE._class
def isSubclass(C1, C2):
c = C1
while c is not None:
if c == C2:
return True
c = c._superclass
return False
def commonBaseclass(INSTANCE1, INSTANCE2):
c = INSTANCE1
while c is not None:
if isSubclass(INSTANCE2, c):
return c
c = c._superclass
return None
def ooupcast(INSTANCE, instance):
return instance._upcast(INSTANCE)
def oodowncast(INSTANCE, instance):
return instance._downcast(INSTANCE)
def ooidentityhash(inst):
assert isinstance(typeOf(inst), (Instance, Record))
return inst._identityhash()
def oohash(inst):
assert typeOf(inst) is String # for now only strings are supported
return hash(inst._str)
def oostring(obj, base):
"""
Convert char, int, float, instances and str to str.
Base is used only for formatting int: for other types is ignored
and should be set to -1. For int only base 8, 10 and 16 are
supported.
"""
if isinstance(obj, int):
assert base in (-1, 8, 10, 16)
fmt = {-1:'%d', 8:'%o', 10:'%d', 16:'%x'}[base]
obj = fmt % obj
elif isinstance(obj, _view):
obj = '<%s object>' % obj._inst._TYPE._name
return make_string(str(obj))
def ooparse_int(s, base):
return int(s._str, base)
def ooparse_float(s):
return float(s._str)
def setItemType(LIST, ITEMTYPE):
return LIST._set_itemtype(ITEMTYPE)
def hasItemType(LIST):
return LIST._ITEMTYPE is not None
def setDictTypes(DICT, KEYTYPE, VALUETYPE):
return DICT._set_types(KEYTYPE, VALUETYPE)
def setDictFunctions(DICT, ll_eq, ll_hash):
return DICT._set_functions(ll_eq, ll_hash)
def hasDictTypes(DICT):
return DICT._is_initialized()
String = String()
StringBuilder = StringBuilder()
ROOT = Instance('Root', None, _is_root=True)
| Python |
from pypy.rpython.exceptiondata import AbstractExceptionData
from pypy.rpython.ootypesystem import rclass
from pypy.rpython.ootypesystem import ootype
from pypy.annotation import model as annmodel
from pypy.annotation.classdef import FORCE_ATTRIBUTES_INTO_CLASSES
class ExceptionData(AbstractExceptionData):
"""Public information for the code generators to help with exceptions."""
def __init__(self, rtyper):
AbstractExceptionData.__init__(self, rtyper)
self._compute_exception_instance(rtyper)
def _compute_exception_instance(self, rtyper):
excdef = rtyper.annotator.bookkeeper.getuniqueclassdef(Exception)
excrepr = rclass.getinstancerepr(rtyper, excdef)
self._EXCEPTION_INST = excrepr.lowleveltype
def is_exception_instance(self, INSTANCE):
return ootype.isSubclass(INSTANCE, self._EXCEPTION_INST)
def make_helpers(self, rtyper):
self.fn_exception_match = self.make_exception_matcher(rtyper)
self.fn_pyexcclass2exc = self.make_pyexcclass2exc(rtyper)
self.fn_type_of_exc_inst = self.make_type_of_exc_inst(rtyper)
self.fn_raise_OSError = self.make_raise_OSError(rtyper)
def make_exception_matcher(self, rtyper):
# ll_exception_matcher(real_exception_meta, match_exception_meta)
s_classtype = annmodel.SomeOOInstance(self.lltype_of_exception_type)
helper_fn = rtyper.annotate_helper_fn(rclass.ll_issubclass, [s_classtype, s_classtype])
return helper_fn
def make_type_of_exc_inst(self, rtyper):
# ll_type_of_exc_inst(exception_instance) -> exception_vtable
s_excinst = annmodel.SomeOOInstance(self.lltype_of_exception_value)
helper_fn = rtyper.annotate_helper_fn(rclass.ll_inst_type, [s_excinst])
return helper_fn
def make_pyexcclass2exc(self, rtyper):
# ll_pyexcclass2exc(python_exception_class) -> exception_instance
table = {}
Exception_def = rtyper.annotator.bookkeeper.getuniqueclassdef(Exception)
for clsdef in rtyper.class_reprs:
if (clsdef and clsdef is not Exception_def
and clsdef.issubclass(Exception_def)):
if not hasattr(clsdef.classdesc, 'pyobj'):
continue
cls = clsdef.classdesc.pyobj
if cls in self.standardexceptions and cls not in FORCE_ATTRIBUTES_INTO_CLASSES:
is_standard = True
assert not clsdef.attrs, (
"%r should not have grown attributes" % (cls,))
else:
is_standard = (cls.__module__ == 'exceptions'
and not clsdef.attrs)
if is_standard:
r_inst = rclass.getinstancerepr(rtyper, clsdef)
example = r_inst.get_reusable_prebuilt_instance()
example = ootype.ooupcast(self.lltype_of_exception_value, example)
table[cls] = example
r_inst = rclass.getinstancerepr(rtyper, None)
r_inst.setup()
r_class = rclass.getclassrepr(rtyper, None)
r_class.setup()
default_excinst = ootype.new(self.lltype_of_exception_value)
default_excinst.meta = r_class.get_meta_instance()
# build the table in order base classes first, subclasses last
sortedtable = []
def add_class(cls):
if cls in table:
for base in cls.__bases__:
add_class(base)
sortedtable.append((cls, table[cls]))
del table[cls]
for cls in table.keys():
add_class(cls)
assert table == {}
initial_value_of_i = len(sortedtable) - 1
def pyexcclass2exc(python_exception_class):
python_exception_class = python_exception_class._obj.value
i = initial_value_of_i
while i >= 0:
if issubclass(python_exception_class, sortedtable[i][0]):
return sortedtable[i][1]
i -= 1
return default_excinst
# This function will only be used by the llinterpreter which usually
# expects a low-level callable (_meth, _static_meth), so we just
# fake it here.
FakeCallableType = ootype.OOType()
FakeCallableType.ARGS = ()
class fake_callable(object):
def __init__(self, fn):
self._TYPE = FakeCallableType
self._callable = fn
return fake_callable(pyexcclass2exc)
| Python |
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.annotation import model as annmodel
from pypy.rpython.ootypesystem import ootype
class Entry_oostring(ExtRegistryEntry):
_about_ = ootype.oostring
def compute_result_annotation(self, obj_s, base_s):
assert isinstance(obj_s, (annmodel.SomeInteger,
annmodel.SomeChar,
annmodel.SomeFloat,
annmodel.SomeOOInstance,
annmodel.SomeString))
assert isinstance(base_s, annmodel.SomeInteger)
return annmodel.SomeOOInstance(ootype.String)
def specialize_call(self, hop):
assert isinstance(hop.args_s[0],(annmodel.SomeInteger,
annmodel.SomeChar,
annmodel.SomeString,
annmodel.SomeFloat,
annmodel.SomeOOInstance,
annmodel.SomeString))
vlist = hop.inputargs(hop.args_r[0], ootype.Signed)
return hop.genop('oostring', vlist, resulttype = ootype.String)
class Entry_ootype_string(ExtRegistryEntry):
_type_ = ootype._string
def compute_annotation(self):
return annmodel.SomeOOInstance(ootype=ootype.String)
class Entry_ooparse_int(ExtRegistryEntry):
_about_ = ootype.ooparse_int
def compute_result_annotation(self, str_s, base_s):
assert isinstance(str_s, annmodel.SomeOOInstance)\
and str_s.ootype is ootype.String
assert isinstance(base_s, annmodel.SomeInteger)
return annmodel.SomeInteger()
def specialize_call(self, hop):
assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)\
and hop.args_s[0].ootype is ootype.String
vlist = hop.inputargs(hop.args_r[0], ootype.Signed)
hop.has_implicit_exception(ValueError)
hop.exception_is_here()
return hop.genop('ooparse_int', vlist, resulttype = ootype.Signed)
class Entry_ooparse_float(ExtRegistryEntry):
_about_ = ootype.ooparse_float
def compute_result_annotation(self, str_s):
assert isinstance(str_s, annmodel.SomeOOInstance)\
and str_s.ootype is ootype.String
return annmodel.SomeFloat()
def specialize_call(self, hop):
assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)\
and hop.args_s[0].ootype is ootype.String
vlist = hop.inputargs(hop.args_r[0])
hop.has_implicit_exception(ValueError)
hop.exception_is_here()
return hop.genop('ooparse_float', vlist, resulttype = ootype.Float)
class Entry_oohash(ExtRegistryEntry):
_about_ = ootype.oohash
def compute_result_annotation(self, str_s):
assert isinstance(str_s, annmodel.SomeOOInstance)\
and str_s.ootype is ootype.String
return annmodel.SomeInteger()
def specialize_call(self, hop):
assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)\
and hop.args_s[0].ootype is ootype.String
vlist = hop.inputargs(hop.args_r[0])
return hop.genop('oohash', vlist, resulttype=ootype.Signed)
| Python |
import sys
from pypy.rpython.ootypesystem.ootype import new, oostring, StringBuilder
from pypy.rpython.ootypesystem.ootype import make_string
def ll_int_str(repr, i):
return ll_int2dec(i)
def ll_int2dec(i):
return oostring(i, 10)
SPECIAL_VALUE = -sys.maxint-1
SPECIAL_VALUE_HEX = make_string(
'-' + hex(sys.maxint+1).replace('L', '').replace('l', ''))
SPECIAL_VALUE_OCT = make_string(
'-' + oct(sys.maxint+1).replace('L', '').replace('l', ''))
def ll_int2hex(i, addPrefix):
if not addPrefix:
return oostring(i, 16)
buf = new(StringBuilder)
if i<0:
if i == SPECIAL_VALUE:
return SPECIAL_VALUE_HEX
i = -i
buf.ll_append_char('-')
buf.ll_append_char('0')
buf.ll_append_char('x')
buf.ll_append(oostring(i, 16))
return buf.ll_build()
def ll_int2oct(i, addPrefix):
if not addPrefix or i==0:
return oostring(i, 8)
buf = new(StringBuilder)
if i<0:
if i == SPECIAL_VALUE:
return SPECIAL_VALUE_OCT
i = -i
buf.ll_append_char('-')
buf.ll_append_char('0')
buf.ll_append(oostring(i, 8))
return buf.ll_build()
def ll_float_str(repr, f):
return oostring(f, -1)
| Python |
import types
from pypy.annotation import model as annmodel
from pypy.annotation import description
from pypy.objspace.flow import model as flowmodel
from pypy.rpython.rmodel import inputconst, TyperError, warning
from pypy.rpython.rmodel import mangle as pbcmangle
from pypy.rpython.rclass import AbstractClassRepr, AbstractInstanceRepr, \
getinstancerepr, getclassrepr, get_type_repr
from pypy.rpython.ootypesystem import ootype
from pypy.annotation.pairtype import pairtype
from pypy.tool.sourcetools import func_with_new_name
CLASSTYPE = ootype.Instance("Object_meta", ootype.ROOT,
fields={"class_": ootype.Class})
OBJECT = ootype.Instance("Object", ootype.ROOT,
fields={'meta': CLASSTYPE})
class ClassRepr(AbstractClassRepr):
def __init__(self, rtyper, classdef):
AbstractClassRepr.__init__(self, rtyper, classdef)
if self.classdef is not None:
self.rbase = getclassrepr(self.rtyper, self.classdef.basedef)
base_type = self.rbase.lowleveltype
self.lowleveltype = ootype.Instance(
self.classdef.name + "_meta", base_type)
else:
# we are ROOT
self.lowleveltype = CLASSTYPE
def _setup_repr(self):
clsfields = {}
pbcfields = {}
if self.classdef is not None:
# class attributes
llfields = []
"""
attrs = self.classdef.attrs.items()
attrs.sort()
for name, attrdef in attrs:
if attrdef.readonly:
s_value = attrdef.s_value
s_unboundmethod = self.prepare_method(s_value)
if s_unboundmethod is not None:
allmethods[name] = True
s_value = s_unboundmethod
r = self.rtyper.getrepr(s_value)
mangled_name = 'cls_' + name
clsfields[name] = mangled_name, r
llfields.append((mangled_name, r.lowleveltype))
"""
# attributes showing up in getattrs done on the class as a PBC
extra_access_sets = self.rtyper.class_pbc_attributes.get(
self.classdef, {})
for access_set, (attr, counter) in extra_access_sets.items():
r = self.rtyper.getrepr(access_set.s_value)
mangled_name = pbcmangle('pbc%d' % counter, attr)
pbcfields[access_set, attr] = mangled_name, r
llfields.append((mangled_name, r.lowleveltype))
self.rbase.setup()
ootype.addFields(self.lowleveltype, dict(llfields))
#self.clsfields = clsfields
self.pbcfields = pbcfields
self.meta_instance = None
def get_meta_instance(self, cast_to_root_meta=True):
if self.meta_instance is None:
self.meta_instance = ootype.new(self.lowleveltype)
self.setup_meta_instance(self.meta_instance, self)
meta_instance = self.meta_instance
if cast_to_root_meta:
meta_instance = ootype.ooupcast(CLASSTYPE, meta_instance)
return meta_instance
def setup_meta_instance(self, meta_instance, rsubcls):
if self.classdef is None:
rinstance = getinstancerepr(self.rtyper, rsubcls.classdef)
setattr(meta_instance, 'class_', rinstance.lowleveltype._class)
else:
# setup class attributes: for each attribute name at the level
# of 'self', look up its value in the subclass rsubcls
def assign(mangled_name, value):
if isinstance(value, flowmodel.Constant) and isinstance(value.value, staticmethod):
value = flowmodel.Constant(value.value.__get__(42)) # staticmethod => bare function
llvalue = r.convert_desc_or_const(value)
setattr(meta_instance, mangled_name, llvalue)
#mro = list(rsubcls.classdef.getmro())
#for fldname in self.clsfields:
# mangled_name, r = self.clsfields[fldname]
# if r.lowleveltype is Void:
# continue
# value = rsubcls.classdef.classdesc.read_attribute(fldname, None)
# if value is not None:
# assign(mangled_name, value)
# extra PBC attributes
for (access_set, attr), (mangled_name, r) in self.pbcfields.items():
if rsubcls.classdef.classdesc not in access_set.descs:
continue # only for the classes in the same pbc access set
if r.lowleveltype is ootype.Void:
continue
attrvalue = rsubcls.classdef.classdesc.read_attribute(attr, None)
if attrvalue is not None:
assign(mangled_name, attrvalue)
# then initialize the 'super' portion of the vtable
meta_instance_super = ootype.ooupcast(
self.rbase.lowleveltype, meta_instance)
self.rbase.setup_meta_instance(meta_instance_super, rsubcls)
getruntime = get_meta_instance
def fromclasstype(self, vclass, llops):
return llops.genop('oodowncast', [vclass],
resulttype=self.lowleveltype)
def getpbcfield(self, vcls, access_set, attr, llops):
if (access_set, attr) not in self.pbcfields:
raise TyperError("internal error: missing PBC field")
mangled_name, r = self.pbcfields[access_set, attr]
v_meta = self.fromclasstype(vcls, llops)
cname = inputconst(ootype.Void, mangled_name)
return llops.genop('oogetfield', [v_meta, cname], resulttype=r)
def rtype_issubtype(self, hop):
class_repr = get_type_repr(self.rtyper)
vmeta1, vmeta2 = hop.inputargs(class_repr, class_repr)
return hop.gendirectcall(ll_issubclass, vmeta1, vmeta2)
def ll_issubclass(meta1, meta2):
class1 = meta1.class_
class2 = meta2.class_
return ootype.subclassof(class1, class2)
# ____________________________________________________________
def mangle(name, config):
# XXX temporary: for now it looks like a good idea to mangle names
# systematically to trap bugs related to a confusion between mangled
# and non-mangled names
if config.translation.ootype.mangle:
return 'o' + name
else:
not_allowed = ('_hash_cache_', 'meta', 'class_')
assert name not in not_allowed, "%s is a reserved name" % name
return name
def unmangle(mangled, config):
if config.translation.ootype.mangle:
assert mangled.startswith('o')
return mangled[1:]
else:
return mangled
class InstanceRepr(AbstractInstanceRepr):
def __init__(self, rtyper, classdef, gcflavor='ignored'):
AbstractInstanceRepr.__init__(self, rtyper, classdef)
self.baserepr = None
if self.classdef is None:
self.lowleveltype = OBJECT
else:
b = self.classdef.basedef
if b is not None:
self.baserepr = getinstancerepr(rtyper, b)
b = self.baserepr.lowleveltype
else:
b = OBJECT
if hasattr(classdef.classdesc.pyobj, '_rpython_hints'):
hints = classdef.classdesc.pyobj._rpython_hints
else:
hints = {}
self.lowleveltype = ootype.Instance(classdef.name, b, {}, {}, _hints = hints)
self.prebuiltinstances = {} # { id(x): (x, _ptr) }
self.object_type = self.lowleveltype
self.gcflavor = gcflavor
def _setup_repr(self):
if self.classdef is None:
self.allfields = {}
self.allmethods = {}
self.allclassattributes = {}
self.classattributes = {}
return
if self.baserepr is not None:
allfields = self.baserepr.allfields.copy()
allmethods = self.baserepr.allmethods.copy()
allclassattributes = self.baserepr.allclassattributes.copy()
else:
allfields = {}
allmethods = {}
allclassattributes = {}
fields = {}
fielddefaults = {}
selfattrs = self.classdef.attrs
for name, attrdef in selfattrs.iteritems():
mangled = mangle(name, self.rtyper.getconfig())
if not attrdef.readonly:
repr = self.rtyper.getrepr(attrdef.s_value)
allfields[mangled] = repr
oot = repr.lowleveltype
fields[mangled] = oot
try:
value = self.classdef.classdesc.read_attribute(name)
fielddefaults[mangled] = repr.convert_desc_or_const(value)
except AttributeError:
pass
else:
s_value = attrdef.s_value
if isinstance(s_value, annmodel.SomePBC):
if len(s_value.descriptions) > 0 and s_value.getKind() == description.MethodDesc:
# attrdef is for a method
if mangled in allclassattributes:
raise TyperError("method overrides class attribute")
allmethods[mangled] = name, self.classdef.lookup_filter(s_value)
continue
# class attribute
if mangled in allmethods:
raise TyperError("class attribute overrides method")
allclassattributes[mangled] = name, s_value
special_methods = ["__init__", "__del__"]
for meth_name in special_methods:
if meth_name not in selfattrs and \
self.classdef.classdesc.find_source_for(meth_name) is not None:
s_meth = self.classdef.classdesc.s_get_value(self.classdef,
meth_name)
if isinstance(s_meth, annmodel.SomePBC):
mangled = mangle(meth_name, self.rtyper.getconfig())
allmethods[mangled] = meth_name, s_meth
# else: it's the __init__ of a builtin exception
#
# hash() support
if self.rtyper.needs_hash_support(self.classdef):
from pypy.rpython import rint
allfields['_hash_cache_'] = rint.signed_repr
fields['_hash_cache_'] = ootype.Signed
ootype.addFields(self.lowleveltype, fields)
self.rbase = getinstancerepr(self.rtyper, self.classdef.basedef)
self.rbase.setup()
methods = {}
classattributes = {}
baseInstance = self.lowleveltype._superclass
classrepr = getclassrepr(self.rtyper, self.classdef)
for mangled, (name, s_value) in allmethods.iteritems():
methdescs = s_value.descriptions
origin = dict([(methdesc.originclassdef, methdesc) for
methdesc in methdescs])
if self.classdef in origin:
methdesc = origin[self.classdef]
else:
if name in selfattrs:
for superdef in self.classdef.getmro():
if superdef in origin:
# put in methods
methdesc = origin[superdef]
break
else:
# abstract method
methdesc = None
else:
continue
# get method implementation
from pypy.rpython.ootypesystem.rpbc import MethodImplementations
methimpls = MethodImplementations.get(self.rtyper, s_value)
m_impls = methimpls.get_impl(mangled, methdesc,
is_finalizer=name == "__del__")
methods.update(m_impls)
for classdef in self.classdef.getmro():
for name, attrdef in classdef.attrs.iteritems():
if not attrdef.readonly:
continue
mangled = mangle(name, self.rtyper.getconfig())
if mangled in allclassattributes:
selfdesc = self.classdef.classdesc
if name not in selfattrs:
# if the attr was already found in a parent class,
# we register it again only if it is overridden.
if selfdesc.find_source_for(name) is None:
continue
value = selfdesc.read_attribute(name)
else:
# otherwise, for new attrs, we look in all parent
# classes to see if it's defined in a parent but only
# actually first used in self.classdef.
value = selfdesc.read_attribute(name, None)
# a non-method class attribute
if not attrdef.s_value.is_constant():
classattributes[mangled] = attrdef.s_value, value
ootype.addMethods(self.lowleveltype, methods)
self.allfields = allfields
self.allmethods = allmethods
self.allclassattributes = allclassattributes
self.classattributes = classattributes
# the following is done after the rest of the initialization because
# convert_const can require 'self' to be fully initialized.
# step 2: provide default values for fields
for mangled, impl in fielddefaults.items():
oot = fields[mangled]
ootype.addFields(self.lowleveltype, {mangled: (oot, impl)})
def _setup_repr_final(self):
# step 3: provide accessor methods for class attributes that
# are really overridden in subclasses. Must be done here
# instead of _setup_repr to avoid recursion problems if class
# attributes are Instances of self.lowleveltype.
for mangled, (s_value, value) in self.classattributes.items():
r = self.rtyper.getrepr(s_value)
m = self.attach_class_attr_accessor(mangled, value, r)
# step 4: do the same with instance fields whose default
# values are overridden in subclasses. Not sure it's the best
# way to do it.
overridden_defaults = {}
if self.classdef is not None:
for name, constant in self.classdef.classdesc.classdict.iteritems():
# look for the attrdef in the superclasses
classdef = self.classdef.basedef
attrdef = None
while classdef is not None:
if name in classdef.attrs:
attrdef = classdef.attrs[name]
break
classdef = classdef.basedef
if attrdef is not None and not attrdef.readonly:
# it means that the default value for this field
# is overridden in this subclass. Record we know
# about it
repr = self.rtyper.getrepr(attrdef.s_value)
oot = repr.lowleveltype
mangled = mangle(name, self.rtyper.getconfig())
value = self.classdef.classdesc.read_attribute(name)
default = repr.convert_desc_or_const(value)
overridden_defaults[mangled] = oot, default
ootype.overrideDefaultForFields(self.lowleveltype, overridden_defaults)
def attach_class_attr_accessor(self, mangled, value, r_value):
def ll_getclassattr(self):
return oovalue
M = ootype.Meth([], r_value.lowleveltype)
if value is None:
m = ootype.meth(M, _name=mangled, abstract=True)
else:
oovalue = r_value.convert_desc_or_const(value)
ll_getclassattr = func_with_new_name(ll_getclassattr,
'll_get_' + mangled)
graph = self.rtyper.annotate_helper(ll_getclassattr, [self.lowleveltype])
m = ootype.meth(M, _name=mangled, _callable=ll_getclassattr,
graph=graph)
ootype.addMethods(self.lowleveltype, {mangled: m})
def get_ll_hash_function(self):
return ll_inst_hash
def rtype_getattr(self, hop):
v_inst, _ = hop.inputargs(self, ootype.Void)
s_inst = hop.args_s[0]
attr = hop.args_s[1].const
mangled = mangle(attr, self.rtyper.getconfig())
v_attr = hop.inputconst(ootype.Void, mangled)
if mangled in self.allfields:
# regular instance attributes
self.lowleveltype._check_field(mangled)
return hop.genop("oogetfield", [v_inst, v_attr],
resulttype = hop.r_result.lowleveltype)
elif mangled in self.allmethods:
# special case for methods: represented as their 'self' only
# (see MethodsPBCRepr)
return hop.r_result.get_method_from_instance(self, v_inst,
hop.llops)
elif mangled in self.allclassattributes:
# class attributes
if hop.s_result.is_constant():
return hop.inputconst(hop.r_result, hop.s_result.const)
else:
cname = hop.inputconst(ootype.Void, mangled)
return hop.genop("oosend", [cname, v_inst],
resulttype = hop.r_result.lowleveltype)
elif attr == '__class__':
if hop.r_result.lowleveltype is ootype.Void:
# special case for when the result of '.__class__' is constant
[desc] = hop.s_result.descriptions
return hop.inputconst(ootype.Void, desc.pyobj)
else:
cmeta = inputconst(ootype.Void, "meta")
return hop.genop('oogetfield', [v_inst, cmeta],
resulttype=CLASSTYPE)
else:
raise TyperError("no attribute %r on %r" % (attr, self))
def rtype_setattr(self, hop):
attr = hop.args_s[1].const
mangled = mangle(attr, self.rtyper.getconfig())
self.lowleveltype._check_field(mangled)
r_value = self.allfields[mangled]
v_inst, _, v_newval = hop.inputargs(self, ootype.Void, r_value)
v_attr = hop.inputconst(ootype.Void, mangled)
return hop.genop('oosetfield', [v_inst, v_attr, v_newval])
def setfield(self, vinst, attr, vvalue, llops):
# this method emulates behaviour from the corresponding
# lltypesystem one. It is referenced in some obscure corners
# like rtyping of OSError.
mangled_name = mangle(attr, self.rtyper.getconfig())
cname = inputconst(ootype.Void, mangled_name)
llops.genop('oosetfield', [vinst, cname, vvalue])
def rtype_is_true(self, hop):
vinst, = hop.inputargs(self)
return hop.genop('oononnull', [vinst], resulttype=ootype.Bool)
def ll_str(self, instance):
return ootype.oostring(instance, -1)
def rtype_type(self, hop):
if hop.s_result.is_constant():
return hop.inputconst(hop.r_result, hop.s_result.const)
vinst, = hop.inputargs(self)
if hop.args_s[0].can_be_none():
return hop.gendirectcall(ll_inst_type, vinst)
else:
cmeta = inputconst(ootype.Void, "meta")
return hop.genop('oogetfield', [vinst, cmeta], resulttype=CLASSTYPE)
def rtype_id(self, hop):
vinst, = hop.inputargs(self)
return hop.genop('ooidentityhash', [vinst], resulttype=ootype.Signed)
def null_instance(self):
return ootype.null(self.lowleveltype)
def upcast(self, result):
return ootype.ooupcast(self.lowleveltype, result)
def create_instance(self):
return ootype.new(self.object_type)
def new_instance(self, llops, classcallhop=None):
"""Build a new instance, without calling __init__."""
classrepr = getclassrepr(self.rtyper, self.classdef)
v_instance = llops.genop("new",
[inputconst(ootype.Void, self.lowleveltype)], self.lowleveltype)
cmeta = inputconst(ootype.Void, "meta")
cmeta_instance = inputconst(CLASSTYPE, classrepr.get_meta_instance())
llops.genop("oosetfield", [v_instance, cmeta, cmeta_instance],
resulttype=ootype.Void)
return v_instance
def initialize_prebuilt_instance(self, value, classdef, result):
# then add instance attributes from this level
classrepr = getclassrepr(self.rtyper, self.classdef)
for mangled, (oot, default) in self.lowleveltype._allfields().items():
if oot is ootype.Void:
llattrvalue = None
elif mangled == 'meta':
llattrvalue = classrepr.get_meta_instance()
elif mangled == '_hash_cache_': # hash() support
llattrvalue = hash(value)
else:
name = unmangle(mangled, self.rtyper.getconfig())
try:
attrvalue = getattr(value, name)
except AttributeError:
attrvalue = self.classdef.classdesc.read_attribute(name, None)
if attrvalue is None:
warning("prebuilt instance %r has no attribute %r" % (
value, name))
continue
llattrvalue = self.allfields[mangled].convert_desc_or_const(attrvalue)
else:
llattrvalue = self.allfields[mangled].convert_const(attrvalue)
setattr(result, mangled, llattrvalue)
buildinstancerepr = InstanceRepr
class __extend__(pairtype(InstanceRepr, InstanceRepr)):
def convert_from_to((r_ins1, r_ins2), v, llops):
# which is a subclass of which?
if r_ins1.classdef is None or r_ins2.classdef is None:
basedef = None
else:
basedef = r_ins1.classdef.commonbase(r_ins2.classdef)
if basedef == r_ins2.classdef:
# r_ins1 is an instance of the subclass: converting to parent
v = llops.genop('ooupcast', [v],
resulttype = r_ins2.lowleveltype)
return v
elif basedef == r_ins1.classdef:
# r_ins2 is an instance of the subclass: potentially unsafe
# casting, but we do it anyway (e.g. the annotator produces
# such casts after a successful isinstance() check)
v = llops.genop('oodowncast', [v],
resulttype = r_ins2.lowleveltype)
return v
else:
return NotImplemented
def rtype_is_((r_ins1, r_ins2), hop):
# NB. this version performs no cast to the common base class
vlist = hop.inputargs(r_ins1, r_ins2)
return hop.genop('oois', vlist, resulttype=ootype.Bool)
rtype_eq = rtype_is_
def rtype_ne(rpair, hop):
v = rpair.rtype_eq(hop)
return hop.genop("bool_not", [v], resulttype=ootype.Bool)
def ll_inst_hash(ins):
cached = ins._hash_cache_
if cached == 0:
cached = ins._hash_cache_ = ootype.ooidentityhash(ins)
return cached
def ll_inst_type(obj):
if obj:
return obj.meta
else:
# type(None) -> NULL (for now)
return ootype.null(CLASSTYPE)
| Python |
from pypy.annotation import model as annmodel
from pypy.rpython.ootypesystem import ootype, rootype
from pypy.rpython.ootypesystem import rclass
from pypy.rpython.ootypesystem.rdict import rtype_r_dict
from pypy.objspace.flow.model import Constant
from pypy.rlib import objectmodel
from pypy.rpython.error import TyperError
def rtype_new(hop):
assert hop.args_s[0].is_constant()
vlist = hop.inputargs(ootype.Void)
return hop.genop('new', vlist,
resulttype = hop.r_result.lowleveltype)
def rtype_null(hop):
assert hop.args_s[0].is_constant()
TYPE = hop.args_s[0].const
nullvalue = ootype.null(TYPE)
return hop.inputconst(TYPE, nullvalue)
def rtype_classof(hop):
assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)
vlist = hop.inputargs(hop.args_r[0])
return hop.genop('classof', vlist,
resulttype = ootype.Class)
def rtype_subclassof(hop):
vlist = hop.inputargs(rootype.ooclass_repr, rootype.ooclass_repr)
return hop.genop('subclassof', vlist,
resulttype = ootype.Bool)
def rtype_runtimenew(hop):
vlist = hop.inputargs(rootype.ooclass_repr)
return hop.genop('runtimenew', vlist,
resulttype = hop.r_result.lowleveltype)
def rtype_ooidentityhash(hop):
assert isinstance(hop.args_s[0], annmodel.SomeOOInstance)
vlist = hop.inputargs(hop.args_r[0])
return hop.genop('ooidentityhash', vlist,
resulttype = ootype.Signed)
def rtype_builtin_isinstance(hop):
if hop.s_result.is_constant():
return hop.inputconst(ootype.Bool, hop.s_result.const)
if hop.args_s[1].is_constant() and hop.args_s[1].const == list:
if hop.args_s[0].knowntype != list:
raise TyperError("isinstance(x, list) expects x to be known statically to be a list or None")
v_list = hop.inputarg(hop.args_r[0], arg=0)
return hop.genop('oononnull', [v_list], resulttype=ootype.Bool)
class_repr = rclass.get_type_repr(hop.rtyper)
instance_repr = hop.args_r[0]
assert isinstance(instance_repr, rclass.InstanceRepr)
v_obj, v_cls = hop.inputargs(instance_repr, class_repr)
if isinstance(v_cls, Constant):
c_cls = hop.inputconst(ootype.Void, v_cls.value.class_._INSTANCE)
return hop.genop('instanceof', [v_obj, c_cls], resulttype=ootype.Bool)
else:
return hop.gendirectcall(ll_isinstance, v_obj, v_cls)
def ll_isinstance(inst, meta):
c1 = inst.meta.class_
c2 = meta.class_
return ootype.subclassof(c1, c2)
def rtype_instantiate(hop):
if hop.args_s[0].is_constant():
## INSTANCE = hop.s_result.rtyper_makerepr(hop.rtyper).lowleveltype
## v_instance = hop.inputconst(ootype.Void, INSTANCE)
## hop2 = hop.copy()
## hop2.r_s_popfirstarg()
## s_instance = hop.rtyper.annotator.bookkeeper.immutablevalue(INSTANCE)
## hop2.v_s_insertfirstarg(v_instance, s_instance)
## return rtype_new(hop2)
r_instance = hop.s_result.rtyper_makerepr(hop.rtyper)
return r_instance.new_instance(hop.llops)
else:
r_instance = hop.s_result.rtyper_makerepr(hop.rtyper)
INSTANCE = r_instance.lowleveltype
c_instance = hop.inputconst(ootype.Void, INSTANCE)
v_cls = hop.inputarg(hop.args_r[0], arg=0)
v_obj = hop.gendirectcall(ll_instantiate, c_instance, v_cls)
v_instance = hop.genop('oodowncast', [v_obj], resulttype=hop.r_result.lowleveltype)
c_meta = hop.inputconst(ootype.Void, "meta")
hop.genop("oosetfield", [v_instance, c_meta, v_cls], resulttype=ootype.Void)
return v_instance
def ll_instantiate(INST, C):
return ootype.runtimenew(C.class_)
BUILTIN_TYPER = {}
BUILTIN_TYPER[ootype.new] = rtype_new
BUILTIN_TYPER[ootype.null] = rtype_null
BUILTIN_TYPER[ootype.classof] = rtype_classof
BUILTIN_TYPER[ootype.subclassof] = rtype_subclassof
BUILTIN_TYPER[ootype.runtimenew] = rtype_runtimenew
BUILTIN_TYPER[ootype.ooidentityhash] = rtype_ooidentityhash
BUILTIN_TYPER[isinstance] = rtype_builtin_isinstance
BUILTIN_TYPER[objectmodel.r_dict] = rtype_r_dict
BUILTIN_TYPER[objectmodel.instantiate] = rtype_instantiate
| Python |
from pypy.rpython.error import TyperError
from pypy.annotation.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.objspace.flow.model import Constant
from pypy.rpython.rdict import AbstractDictRepr, AbstractDictIteratorRepr,\
rtype_newdict, dum_variant, dum_keys, dum_values, dum_items
from pypy.rpython.rpbc import MethodOfFrozenPBCRepr,\
AbstractFunctionsPBCRepr, AbstractMethodsPBCRepr
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.ootypesystem.rlist import ll_newlist
from pypy.rlib.rarithmetic import r_uint
from pypy.rlib.objectmodel import hlinvoke
from pypy.rpython import robject
from pypy.rlib import objectmodel
from pypy.rpython import rmodel
from pypy.rpython import llinterp
class DictRepr(AbstractDictRepr):
def __init__(self, rtyper, key_repr, value_repr, dictkey, dictvalue,
custom_eq_hash=None):
self.rtyper = rtyper
self.custom_eq_hash = custom_eq_hash is not None
already_computed = True
if not isinstance(key_repr, rmodel.Repr): # not computed yet, done by setup()
assert callable(key_repr)
self._key_repr_computer = key_repr
already_computed = False
else:
self.external_key_repr, self.key_repr = self.pickkeyrepr(key_repr)
if not isinstance(value_repr, rmodel.Repr): # not computed yet, done by setup()
assert callable(value_repr)
self._value_repr_computer = value_repr
already_computed = False
else:
self.external_value_repr, self.value_repr = self.pickrepr(value_repr)
if self.custom_eq_hash:
Dict = ootype.CustomDict
else:
Dict = ootype.Dict
if already_computed:
self.DICT = Dict(key_repr.lowleveltype, value_repr.lowleveltype)
else:
self.DICT = Dict()
self.lowleveltype = self.DICT
self.dictkey = dictkey
self.dictvalue = dictvalue
self.dict_cache = {}
self._custom_eq_hash_repr = custom_eq_hash
# setup() needs to be called to finish this initialization
def _externalvsinternal(self, rtyper, item_repr):
return item_repr, item_repr
def _setup_repr(self):
if 'key_repr' not in self.__dict__:
key_repr = self._key_repr_computer()
self.external_key_repr, self.key_repr = self.pickkeyrepr(key_repr)
if 'value_repr' not in self.__dict__:
self.external_value_repr, self.value_repr = self.pickrepr(self._value_repr_computer())
if not ootype.hasDictTypes(self.DICT):
ootype.setDictTypes(self.DICT, self.key_repr.lowleveltype,
self.value_repr.lowleveltype)
if self.custom_eq_hash:
self.r_rdict_eqfn, self.r_rdict_hashfn = self._custom_eq_hash_repr()
def send_message(self, hop, message, can_raise=False, v_args=None):
if v_args is None:
v_args = hop.inputargs(self, *hop.args_r[1:])
c_name = hop.inputconst(ootype.Void, message)
if can_raise:
hop.exception_is_here()
return hop.genop("oosend", [c_name] + v_args,
resulttype=hop.r_result.lowleveltype)
def make_iterator_repr(self, *variant):
return DictIteratorRepr(self, *variant)
def rtype_len(self, hop):
v_dict, = hop.inputargs(self)
hop.exception_cannot_occur()
return self.send_message(hop, 'll_length')
def rtype_is_true(self, hop):
v_dict, = hop.inputargs(self)
return hop.gendirectcall(ll_dict_is_true, v_dict)
def rtype_method_get(self, hop):
v_dict, v_key, v_default = hop.inputargs(self, self.key_repr,
self.value_repr)
hop.exception_cannot_occur()
v_res = hop.gendirectcall(ll_dict_get, v_dict, v_key, v_default)
return self.recast_value(hop.llops, v_res)
def rtype_method_setdefault(self, hop):
v_dict, v_key, v_default = hop.inputargs(self, self.key_repr,
self.value_repr)
hop.exception_cannot_occur()
v_res = hop.gendirectcall(ll_dict_setdefault, v_dict, v_key, v_default)
return self.recast_value(hop.llops, v_res)
def rtype_method_copy(self, hop):
v_dict, = hop.inputargs(self)
cDICT = hop.inputconst(ootype.Void, self.lowleveltype)
hop.exception_cannot_occur()
if self.custom_eq_hash:
c_copy = hop.inputconst(ootype.Void, 'll_copy')
return hop.genop('oosend', [c_copy, v_dict], resulttype=hop.r_result.lowleveltype)
else:
return hop.gendirectcall(ll_dict_copy, cDICT, v_dict)
def rtype_method_update(self, hop):
v_dict1, v_dict2 = hop.inputargs(self, self)
hop.exception_cannot_occur()
return hop.gendirectcall(ll_dict_update, v_dict1, v_dict2)
def rtype_method_keys(self, hop):
return self._rtype_method_kvi(hop, dum_keys)
def rtype_method_values(self, hop):
return self._rtype_method_kvi(hop, dum_values)
def rtype_method_items(self, hop):
return self._rtype_method_kvi(hop, dum_items)
def _rtype_method_kvi(self, hop, spec):
v_dict, = hop.inputargs(self)
r_list = hop.r_result
cLIST = hop.inputconst(ootype.Void, r_list.lowleveltype)
c_func = hop.inputconst(ootype.Void, spec)
hop.exception_cannot_occur()
return hop.gendirectcall(ll_dict_kvi, v_dict, cLIST, c_func)
def rtype_method_iterkeys(self, hop):
hop.exception_cannot_occur()
return DictIteratorRepr(self, "keys").newiter(hop)
def rtype_method_itervalues(self, hop):
hop.exception_cannot_occur()
return DictIteratorRepr(self, "values").newiter(hop)
def rtype_method_iteritems(self, hop):
hop.exception_cannot_occur()
return DictIteratorRepr(self, "items").newiter(hop)
def rtype_method_clear(self, hop):
v_dict, = hop.inputargs(self)
hop.exception_cannot_occur()
return self.send_message(hop, 'll_clear')
def __get_func(self, interp, r_func, fn, TYPE):
if isinstance(r_func, MethodOfFrozenPBCRepr):
obj = r_func.r_im_self.convert_const(fn.im_self)
r_func, nimplicitarg = r_func.get_r_implfunc()
else:
obj = None
callable = r_func.convert_const(fn)
func_name, interp_fn = llinterp.wrap_callable(interp, callable, obj, None)
return ootype.static_meth(TYPE, func_name, _callable=interp_fn)
def convert_const(self, dictobj):
if dictobj is None:
return self.DICT._defl()
if not isinstance(dictobj, dict) and not isinstance(dictobj, objectmodel.r_dict):
raise TyperError("expected a dict: %r" % (dictobj,))
try:
key = Constant(dictobj)
return self.dict_cache[key]
except KeyError:
self.setup()
l_dict = ll_newdict(self.DICT)
if self.custom_eq_hash:
interp = llinterp.LLInterpreter(self.rtyper)
EQ_FUNC = ootype.StaticMethod([self.DICT._KEYTYPE, self.DICT._KEYTYPE], ootype.Bool)
sm_eq = self.__get_func(interp, self.r_rdict_eqfn, dictobj.key_eq, EQ_FUNC)
HASH_FUNC = ootype.StaticMethod([self.DICT._KEYTYPE], ootype.Signed)
sm_hash = self.__get_func(interp, self.r_rdict_hashfn, dictobj.key_hash, HASH_FUNC)
l_dict.ll_set_functions(sm_eq, sm_hash)
self.dict_cache[key] = l_dict
r_key = self.key_repr
r_value = self.value_repr
if self.custom_eq_hash:
for dictkeycont, dictvalue in dictobj._dict.items():
llkey = r_key.convert_const(dictkeycont.key)
llvalue = r_value.convert_const(dictvalue)
llhash = dictkeycont.hash
l_dictkeycont = objectmodel._r_dictkey_with_hash(l_dict._dict, llkey, llhash)
l_dict._dict._dict[l_dictkeycont] = llvalue
else:
for dictkey, dictvalue in dictobj.items():
llkey = r_key.convert_const(dictkey)
llvalue = r_value.convert_const(dictvalue)
l_dict.ll_set(llkey, llvalue)
return l_dict
class __extend__(pairtype(DictRepr, rmodel.Repr)):
def rtype_getitem((r_dict, r_key), hop):
v_dict, v_key = hop.inputargs(r_dict, r_dict.key_repr)
if not r_dict.custom_eq_hash: # TODO: why only in this case?
hop.has_implicit_exception(KeyError) # record that we know about it
hop.exception_is_here()
v_res = hop.gendirectcall(ll_dict_getitem, v_dict, v_key)
return r_dict.recast_value(hop.llops, v_res)
def rtype_delitem((r_dict, r_key), hop):
v_dict, v_key = hop.inputargs(r_dict, r_dict.key_repr)
if not r_dict.custom_eq_hash: # TODO: why only in this case?
hop.has_implicit_exception(KeyError) # record that we know about it
hop.exception_is_here()
return hop.gendirectcall(ll_dict_delitem, v_dict, v_key)
def rtype_setitem((r_dict, r_key), hop):
vlist = hop.inputargs(r_dict, r_dict.key_repr, r_dict.value_repr)
if not r_dict.custom_eq_hash:
hop.exception_cannot_occur() # XXX: maybe should we move this inside send_message?
return r_dict.send_message(hop, 'll_set', can_raise=r_dict.custom_eq_hash, v_args=vlist)
def rtype_contains((r_dict, r_key), hop):
vlist = hop.inputargs(r_dict, r_dict.key_repr)
hop.exception_cannot_occur()
return r_dict.send_message(hop, 'll_contains', v_args=vlist)
def _get_call_vars(hop, r_func, arg, params_annotation):
if isinstance(r_func, AbstractFunctionsPBCRepr):
v_fn = hop.inputarg(r_func, arg=arg)
v_obj = hop.inputconst(ootype.Void, None)
c_method_name = hop.inputconst(ootype.Void, None)
elif isinstance(r_func, AbstractMethodsPBCRepr):
s_pbc_fn = hop.args_s[arg]
methodname = r_func._get_method_name("simple_call", s_pbc_fn, params_annotation)
v_fn = hop.inputconst(ootype.Void, None)
v_obj = hop.inputarg(r_func, arg=arg)
c_method_name = hop.inputconst(ootype.Void, methodname)
elif isinstance(r_func, MethodOfFrozenPBCRepr):
r_impl, nimplicitarg = r_func.get_r_implfunc()
v_fn = hop.inputconst(r_impl, r_func.funcdesc.pyobj)
v_obj = hop.inputarg(r_func, arg=arg)
c_method_name = hop.inputconst(ootype.Void, None)
return v_fn, v_obj, c_method_name
def rtype_r_dict(hop):
r_dict = hop.r_result
if not r_dict.custom_eq_hash:
raise TyperError("r_dict() call does not return an r_dict instance")
cDICT = hop.inputconst(ootype.Void, r_dict.DICT)
hop.exception_cannot_occur()
# the signature of oonewcustomdict is a bit complicated because we
# can have three different ways to pass the equal (and hash)
# callables:
# 1. pass a plain function: v_eqfn is a StaticMethod, v_eqobj
# and c_eq_method_name are None
# 2. pass a bound method: v_eqfn is None, v_eqobj is the
# instance, c_method_name is the name of the method,
# 3. pass a method of a frozen PBC: v_eqfn is a StaticMethod,
# v_eqobj is the PBC to be pushed in front of the StaticMethod,
# c_eq_method_name is None
s_key = r_dict.dictkey.s_value
v_eqfn, v_eqobj, c_eq_method_name =\
_get_call_vars(hop, r_dict.r_rdict_eqfn, 0, [s_key, s_key])
v_hashfn, v_hashobj, c_hash_method_name =\
_get_call_vars(hop, r_dict.r_rdict_hashfn, 1, [s_key])
return hop.genop("oonewcustomdict", [cDICT,
v_eqfn, v_eqobj, c_eq_method_name,
v_hashfn, v_hashobj, c_hash_method_name],
resulttype=hop.r_result.lowleveltype)
def ll_newdict(DICT):
return ootype.new(DICT)
def ll_dict_is_true(d):
# check if a dict is True, allowing for None
return bool(d) and d.ll_length() != 0
def ll_dict_copy(DICT, d):
res = ootype.new(DICT)
ll_dict_update(res, d)
return res
def ll_dict_update(d1, d2):
it = d2.ll_get_items_iterator()
while it.ll_go_next():
key = it.ll_current_key()
value = it.ll_current_value()
d1.ll_set(key, value)
def ll_dict_getitem(d, key):
if d.ll_contains(key):
return d.ll_get(key)
else:
raise KeyError
def ll_dict_delitem(d, key):
if not d.ll_remove(key):
raise KeyError
def ll_dict_get(d, key, default):
if d.ll_contains(key):
return d.ll_get(key)
else:
return default
def ll_dict_setdefault(d, key, default):
try:
return ll_dict_getitem(d, key)
except KeyError:
d.ll_set(key, default)
return default
def ll_dict_kvi(d, LIST, func):
length = d.ll_length()
result = ll_newlist(LIST, length)
it = d.ll_get_items_iterator()
i = 0
while it.ll_go_next():
if func is dum_keys:
result.ll_setitem_fast(i, it.ll_current_key())
elif func is dum_values:
result.ll_setitem_fast(i, it.ll_current_value())
if func is dum_items:
r = ootype.new(LIST._ITEMTYPE)
r.item0 = it.ll_current_key() # TODO: do we need casting?
r.item1 = it.ll_current_value()
result.ll_setitem_fast(i, r)
i += 1
assert i == length
return result
# ____________________________________________________________
#
# Iteration.
class DictIteratorRepr(AbstractDictIteratorRepr):
def __init__(self, r_dict, variant="keys"):
self.r_dict = r_dict
self.variant = variant
self.lowleveltype = self._get_type()
self.ll_dictiter = ll_dictiter
self.ll_dictnext = ll_dictnext
def _get_type(self):
KEYTYPE = self.r_dict.key_repr.lowleveltype
VALUETYPE = self.r_dict.value_repr.lowleveltype
ITER = ootype.DictItemsIterator(KEYTYPE, VALUETYPE)
return ootype.Record({"iterator": ITER})
def _next_implicit_exceptions(self, hop):
hop.has_implicit_exception(StopIteration)
hop.has_implicit_exception(RuntimeError)
def ll_dictiter(ITER, d):
iter = ootype.new(ITER)
iter.iterator = d.ll_get_items_iterator()
return iter
def ll_dictnext(iter, func, RETURNTYPE):
it = iter.iterator
if not it.ll_go_next():
raise StopIteration
if func is dum_keys:
return it.ll_current_key()
elif func is dum_values:
return it.ll_current_value()
elif func is dum_items:
res = ootype.new(RETURNTYPE)
res.item0 = it.ll_current_key()
res.item1 = it.ll_current_value()
return res
| Python |
""" extdesc - some descriptions for external entries
"""
from pypy.annotation.signature import annotation
class ArgDesc(object):
""" Description of argument, given as name + example value
(used to deduce type)
"""
def __init__(self, name, _type):
self.name = name
self._type = _type
def __repr__(self):
return "<ArgDesc %s: %s>" % (self.name, self._type)
class MethodDesc(object):
""" Description of method to be external,
args are taken from examples given as keyword arguments or as args,
return value must be specified, because this will not be flown
"""
def __init__(self, args, retval = None):
self.num = 0
self.args = [self.convert_val(arg) for arg in args]
self.retval = self.convert_val(retval)
self.example = self
def convert_val(self, val):
if isinstance(val, ArgDesc) or isinstance(val, MethodDesc):
return val
elif isinstance(val, tuple):
return ArgDesc(*val)
else:
self.num += 1
return ArgDesc('v%d' % (self.num-1), val)
def __repr__(self):
return "<MethodDesc (%r)>" % (self.args,)
| Python |
import math
from pypy.rpython.ootypesystem import ootype
FREXP_RESULT = ootype.Record({"item0": ootype.Float, "item1": ootype.Signed})
MODF_RESULT = ootype.Record({"item0": ootype.Float, "item1": ootype.Float})
def ll_frexp_result(mantissa, exponent):
tup = ootype.new(FREXP_RESULT)
tup.item0 = mantissa
tup.item1 = exponent
return tup
def ll_modf_result(fracpart, intpart):
tup = ootype.new(MODF_RESULT)
tup.item0 = fracpart
tup.item1 = intpart
return tup
def ll_math_frexp(x):
mantissa, exponent = math.frexp(x)
return ll_frexp_result(mantissa, exponent)
def ll_math_modf(x):
fracpart, intpart = math.modf(x)
return ll_modf_result(fracpart, intpart)
| Python |
from pypy.rlib import rarithmetic
from pypy.rpython.module.support import OOSupport
from pypy.tool.staticmethods import ClassMethods
class Implementation(object, OOSupport):
__metaclass__ = ClassMethods
def ll_strtod_formatd(cls, fmt, x):
return cls.to_rstr(rarithmetic.formatd(cls.from_rstr(fmt), x))
ll_strtod_formatd.suggested_primitive = True
def ll_strtod_parts_to_float(cls, sign, beforept, afterpt, exponent):
return rarithmetic.parts_to_float(cls.from_rstr(sign),
cls.from_rstr(beforept),
cls.from_rstr(afterpt),
cls.from_rstr(exponent))
ll_strtod_parts_to_float.suggested_primitive = True
| Python |
from pypy.rpython.module.support import OOSupport
from pypy.rpython.module.ll_os_path import BaseOsPath
class Implementation(BaseOsPath, OOSupport):
pass
| Python |
import os
from pypy.rpython.module.support import OOSupport
from pypy.rpython.module.ll_os import BaseOS
from pypy.rpython.ootypesystem import ootype
from pypy.rlib.rarithmetic import intmask
def _make_tuple(FIELDS):
n = len(FIELDS)
fieldnames = ['item%d' % i for i in range(n)]
fields = dict(zip(fieldnames, FIELDS))
return ootype.Record(fields)
STAT_RESULT = _make_tuple([ootype.Signed]*10)
PIPE_RESULT = _make_tuple([ootype.Signed]*2)
WAITPID_RESULT = _make_tuple([ootype.Signed]*2)
class Implementation(BaseOS, OOSupport):
def ll_stat_result(stat0, stat1, stat2, stat3, stat4,
stat5, stat6, stat7, stat8, stat9):
tup = ootype.new(STAT_RESULT)
tup.item0 = intmask(stat0)
tup.item1 = intmask(stat1)
tup.item2 = intmask(stat2)
tup.item3 = intmask(stat3)
tup.item4 = intmask(stat4)
tup.item5 = intmask(stat5)
tup.item6 = intmask(stat6)
tup.item7 = intmask(stat7)
tup.item8 = intmask(stat8)
tup.item9 = intmask(stat9)
return tup
ll_stat_result = staticmethod(ll_stat_result)
def ll_os_read(cls, fd, count):
return cls.to_rstr(os.read(fd, count))
ll_os_read.suggested_primitive = True
def ll_pipe_result(fd1, fd2):
tup = ootype.new(PIPE_RESULT)
tup.item0 = fd1
tup.item1 = fd2
return tup
ll_pipe_result = staticmethod(ll_pipe_result)
def ll_os_readlink(cls, path):
return cls.to_rstr(os.readlink(path))
ll_os_readlink.suggested_primitive = True
def ll_waitpid_result(fd1, fd2):
tup = ootype.new(WAITPID_RESULT)
tup.item0 = fd1
tup.item1 = fd2
return tup
ll_waitpid_result = staticmethod(ll_waitpid_result)
| Python |
from pypy.rpython.rslice import AbstractSliceRepr
from pypy.rpython.lltypesystem.lltype import Void, Signed
from pypy.rpython.ootypesystem import ootype
SLICE = ootype.Instance('Slice', ootype.ROOT, {'start': Signed, 'stop': Signed})
class SliceRepr(AbstractSliceRepr):
pass
startstop_slice_repr = SliceRepr()
startstop_slice_repr.lowleveltype = SLICE
startonly_slice_repr = SliceRepr()
startonly_slice_repr.lowleveltype = Signed
minusone_slice_repr = SliceRepr()
minusone_slice_repr.lowleveltype = Void # only for [:-1]
# ____________________________________________________________
def ll_newslice(start, stop):
s = ootype.new(SLICE)
s.start = start
s.stop = stop
return s
| Python |
from pypy.annotation import model as annmodel
from pypy.rpython.rmodel import Repr
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.ootypesystem.ootype import Void, Class
from pypy.annotation.pairtype import pairtype
class __extend__(annmodel.SomeOOClass):
def rtyper_makerepr(self, rtyper):
return ooclass_repr
def rtyper_makekey(self):
return self.__class__,
class __extend__(annmodel.SomeOOInstance):
def rtyper_makerepr(self, rtyper):
return OOInstanceRepr(self.ootype)
def rtyper_makekey(self):
return self.__class__, self.ootype
class __extend__(annmodel.SomeOOBoundMeth):
def rtyper_makerepr(self, rtyper):
return OOBoundMethRepr(self.ootype, self.name)
def rtyper_makekey(self):
return self.__class__, self.ootype, self.name
class __extend__(annmodel.SomeOOStaticMeth):
def rtyper_makerepr(self, rtyper):
return OOStaticMethRepr(self.method)
def rtyper_makekey(self):
return self.__class__, self.method
class OOClassRepr(Repr):
lowleveltype = Class
ooclass_repr = OOClassRepr()
class OOInstanceRepr(Repr):
def __init__(self, ootype):
self.lowleveltype = ootype
def rtype_getattr(self, hop):
attr = hop.args_s[1].const
s_inst = hop.args_s[0]
_, meth = self.lowleveltype._lookup(attr)
if meth is not None:
# just return instance - will be handled by simple_call
return hop.inputarg(hop.r_result, arg=0)
self.lowleveltype._check_field(attr)
vlist = hop.inputargs(self, Void)
return hop.genop("oogetfield", vlist,
resulttype = hop.r_result.lowleveltype)
def rtype_setattr(self, hop):
if self.lowleveltype is Void:
return
attr = hop.args_s[1].const
self.lowleveltype._check_field(attr)
vlist = hop.inputargs(self, Void, hop.args_r[2])
return hop.genop('oosetfield', vlist)
def rtype_is_true(self, hop):
vlist = hop.inputargs(self)
return hop.genop('oononnull', vlist, resulttype=ootype.Bool)
def convert_const(self, value):
if value is None:
return ootype.null(self.lowleveltype)
else:
return Repr.convert_const(self, value)
class __extend__(pairtype(OOInstanceRepr, OOInstanceRepr)):
def rtype_is_((r_ins1, r_ins2), hop):
# NB. this version performs no cast to the common base class
vlist = hop.inputargs(r_ins1, r_ins2)
return hop.genop('oois', vlist, resulttype=ootype.Bool)
rtype_eq = rtype_is_
def rtype_ne(rpair, hop):
v = rpair.rtype_eq(hop)
return hop.genop("bool_not", [v], resulttype=ootype.Bool)
class OOBoundMethRepr(Repr):
def __init__(self, ootype, name):
self.lowleveltype = ootype
self.name = name
def rtype_simple_call(self, hop):
TYPE = hop.args_r[0].lowleveltype
_, meth = TYPE._lookup(self.name)
if isinstance(meth, ootype._overloaded_meth):
ARGS = tuple([repr.lowleveltype for repr in hop.args_r[1:]])
desc = meth._get_desc(self.name, ARGS)
cname = hop.inputconst(Void, desc)
else:
cname = hop.inputconst(Void, self.name)
vlist = hop.inputargs(self, *hop.args_r[1:])
hop.exception_is_here()
return hop.genop("oosend", [cname]+vlist,
resulttype = hop.r_result.lowleveltype)
class OOStaticMethRepr(Repr):
def __init__(self, METHODTYPE):
self.lowleveltype = METHODTYPE
class __extend__(pairtype(OOInstanceRepr, OOBoundMethRepr)):
def convert_from_to(_, v, llops):
return v
| Python |
from pypy.rpython.ootypesystem.ootype import Signed, Record, new
from pypy.rpython.rrange import AbstractRangeRepr, AbstractRangeIteratorRepr
RANGE = Record({"start": Signed, "stop": Signed})
RANGEITER = Record({"next": Signed, "stop": Signed})
RANGEST = Record({"start": Signed, "stop": Signed, "step": Signed})
RANGESTITER = Record({"next": Signed, "stop": Signed, "step": Signed})
class RangeRepr(AbstractRangeRepr):
RANGE = RANGE
RANGEITER = RANGEITER
RANGEST = RANGEST
RANGESTITER = RANGESTITER
getfield_opname = "oogetfield"
def __init__(self, *args):
AbstractRangeRepr.__init__(self, *args)
self.ll_newrange = ll_newrange
self.ll_newrangest = ll_newrangest
def make_iterator_repr(self):
return RangeIteratorRepr(self)
def ll_newrange(_RANGE, start, stop):
l = new(RANGE)
l.start = start
l.stop = stop
return l
def ll_newrangest(start, stop, step):
if step == 0:
raise ValueError
l = new(RANGEST)
l.start = start
l.stop = stop
l.step = step
return l
class RangeIteratorRepr(AbstractRangeIteratorRepr):
def __init__(self, *args):
AbstractRangeIteratorRepr.__init__(self, *args)
self.ll_rangeiter = ll_rangeiter
def ll_rangeiter(ITER, rng):
iter = new(ITER)
iter.next = rng.start
iter.stop = rng.stop
if ITER is RANGESTITER:
iter.step = rng.step
return iter
| Python |
""" External objects registry,
"""
from pypy.annotation import model as annmodel
from pypy.objspace.flow.model import Variable, Constant
from pypy.rpython.ootypesystem import ootype
from pypy.annotation.bookkeeper import getbookkeeper
from pypy.rpython.lltypesystem.lltype import frozendict, isCompatibleType
from types import MethodType
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.rpython.ootypesystem.extdesc import MethodDesc, ArgDesc
from pypy.annotation.signature import annotation
from pypy.annotation.model import unionof
class CallableEntry(ExtRegistryEntry):
_type_ = MethodDesc
def compute_annotation(self):
bookkeeper = getbookkeeper()
args_s = [annotation(i._type) for i in self.instance.args]
s_result = annotation(self.instance.result._type)
return annmodel.SomeGenericCallable(args=args_s, result=s_result)
class BasicMetaExternal(type):
def _is_compatible(type2):
return type(type2) is BasicMetaExternal
def __new__(self, _name, _type, _vars):
retval = type.__new__(self, _name, _type, _vars)
if not retval._methods:
retval._methods = {}
for name, var in _vars.iteritems():
if hasattr(var, '_method'):
meth_name, desc = var._method
retval._methods[meth_name] = desc
return retval
_is_compatible = staticmethod(_is_compatible)
def typeof(val):
""" Small wrapper, which tries to resemble example -> python type
which can go to annotation path
"""
if isinstance(val, list):
return [typeof(val[0])]
if isinstance(val, dict):
return {typeof(val.keys()[0]):typeof(val.values()[0])}
if isinstance(val, tuple):
return tuple([typeof(i) for i in val])
return type(val)
def load_dict_args(varnames, defs, args):
argcount = len(varnames)
assert(argcount < len(defs) + len(args), "Not enough information for describing method")
for arg in xrange(1, argcount - len(defs)):
assert varnames[arg] in args, "Don't have type for arg %s" % varnames[arg]
arg_pass = []
start_pos = argcount - len(defs)
for arg in xrange(1, argcount):
varname = varnames[arg]
if varname in args:
arg_pass.append((varname, args[varname]))
else:
arg_pass.append((varname, typeof(defs[arg - start_pos])))
return arg_pass
class BasicExternal(object):
__metaclass__ = BasicMetaExternal
__self__ = None
_fields = {}
_methods = {}
def described(retval=None, args={}):
def decorator(func):
if isinstance(args, dict):
defs = func.func_defaults
if defs is None:
defs = ()
vars = func.func_code.co_varnames[:func.func_code.co_argcount]
arg_pass = load_dict_args(vars, defs, args)
else:
assert isinstance(args, list)
arg_pass = args
func._method = (func.__name__, MethodDesc(arg_pass, retval))
return func
return decorator
described = staticmethod(described)
described = BasicExternal.described
class Analyzer(object):
def __init__(self, name, value, s_retval, s_args):
self.name = name
self.args, self.retval = value.args, value.retval
self.s_retval = s_retval
self.s_args = s_args
self.value = value
def __ne__(self, other):
return not (self == other)
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.__dict__ == other.__dict__)
def __call__(self, *args):
args = args[1:]
assert len(self.s_args) == len(args),\
"Function %s expects %d arguments, got %d instead" % (self.name,
len(self.s_args), len(args))
for num, (arg, expected) in enumerate(zip(args, self.s_args)):
res = unionof(arg, expected)
assert expected.contains(res)
return self.s_retval
class ExternalInstanceDesc(object):
def __init__(self, class_):
self._class_ = class_
def setup(self):
_signs = self._methods = {}
self._fields = {}
for i, val in self._class_._methods.iteritems():
retval = annotation(val.retval._type)
values = [annotation(arg._type) for arg in val.args]
s_args = [j for j in values]
_signs[i] = MethodDesc(tuple(s_args), retval)
next = annmodel.SomeBuiltin(Analyzer(i, val, retval, s_args),
s_self = annmodel.SomeExternalInstance(self._class_),
methodname = i)
next.const = True
self._fields[i] = next
for i, val in self._class_._fields.iteritems():
self._fields[i] = annotation(val)
def set_field(self, attr, knowntype):
assert attr in self._fields
field_ann = self._fields[attr]
res = unionof(knowntype, field_ann)
assert res.contains(knowntype)
def get_field(self, attr):
try:
return self._fields[attr]
except KeyError:
from pypy.tool.error import NoSuchAttrError
raise NoSuchAttrError("Basic external %s has no attribute %s" %
(self._class_, attr))
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self._name)
class Entry_basicexternalmeta(ExtRegistryEntry):
_metatype_ = BasicMetaExternal
def compute_annotation(self):
return annmodel.SomeExternalInstance(self.type)
def get_field_annotation(self, _, attr):
bk = getbookkeeper()
ext_desc = bk.getexternaldesc(self.type)
return ext_desc.get_field(attr)
def set_field_annotation(self, _, attr, s_val):
bk = getbookkeeper()
ext_desc = bk.getexternaldesc(self.type)
ext_desc.set_field(attr, s_val)
def get_repr(self, rtyper, s_extinst):
from pypy.rpython.ootypesystem import rbltregistry
return rbltregistry.ExternalInstanceRepr(rtyper, s_extinst.knowntype)
class Entry_basicexternal(ExtRegistryEntry):
_type_ = BasicExternal.__metaclass__
def compute_result_annotation(self):
return annmodel.SomeExternalInstance(self.instance)
def specialize_call(self, hop):
value = hop.r_result.lowleveltype
return hop.genop('new', [Constant(value, concretetype=ootype.Void)], \
resulttype = value)
class ExternalType(ootype.OOType):
def __init__(self, class_):
self._class_ = class_
self._name = str(class_) # xxx fragile
self._superclass = None
self._root = True
def _is_compatible(type2):
return type(type2) is ExternalType
_is_compatible = staticmethod(_is_compatible)
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self._class_ is other._class_)
def __hash__(self):
return hash(self._name)
def _defl(self):
return _external_inst(self, None)
def __str__(self):
return "%s(%s)" % (self.__class__.__name__, self._name)
class _external_inst(object):
def __init__(self, et, value):
self._TYPE = et
self.value = value
| Python |
from pypy.rpython.error import TyperError
from pypy.rpython.rstr import AbstractStringRepr,AbstractCharRepr,\
AbstractUniCharRepr, AbstractStringIteratorRepr,\
AbstractLLHelpers
from pypy.rpython.rmodel import IntegerRepr
from pypy.rpython.lltypesystem.lltype import Ptr, Char, UniChar
from pypy.rpython.ootypesystem import ootype
# TODO: investigate if it's possible and it's worth to concatenate a
# String and a Char directly without passing to Char-->String
# conversion
class StringRepr(AbstractStringRepr):
"""
Some comments about the state of ootype strings at the end of Tokyo sprint
What was accomplished:
- The rstr module was split in an lltype and ootype version.
- There is the beginnings of a String type in ootype.
- The runtime representation of Strings is a subclass of the builtin str.
The idea is that this saves us from boilerplate code implementing the
builtin str methods.
Nothing more was done because of lack of time and paralysis in the face
of too many problems. Among other things, to write any meaningful tests
we first need conversion from Chars to Strings (because
test_llinterp.interpret won't accept strings as arguments). We will need a
new low-level operation (convert_char_to_oostring or some such) for this.
"""
lowleveltype = ootype.String
def __init__(self, *args):
AbstractStringRepr.__init__(self, *args)
self.ll = LLHelpers
def convert_const(self, value):
if value is None:
return ootype.String._null
if not isinstance(value, str):
raise TyperError("not a str: %r" % (value,))
return ootype.make_string(value)
def make_iterator_repr(self):
return string_iterator_repr
def _list_length_items(self, hop, v_lst, LIST):
# ootypesystem list has a different interface that
# lltypesystem list, so we don't need to calculate the lenght
# here and to pass the 'items' array. Let's pass the list
# itself and let LLHelpers.join to manipulate it directly.
c_length = hop.inputconst(ootype.Void, None)
return c_length, v_lst
class CharRepr(AbstractCharRepr, StringRepr):
lowleveltype = Char
class UniCharRepr(AbstractUniCharRepr):
lowleveltype = UniChar
class LLHelpers(AbstractLLHelpers):
def ll_chr2str(ch):
return ootype.oostring(ch, -1)
def ll_strhash(s):
return ootype.oohash(s)
def ll_strfasthash(s):
return ootype.oohash(s)
def ll_char_mul(ch, times):
if times < 0:
times = 0
buf = ootype.new(ootype.StringBuilder)
buf.ll_allocate(times)
i = 0
while i<times:
buf.ll_append_char(ch)
i+= 1
return buf.ll_build()
def ll_streq(s1, s2):
if s1 is None:
return s2 is None
return s1.ll_streq(s2)
def ll_strcmp(s1, s2):
if not s1 and not s2:
return True
if not s1 or not s2:
return False
return s1.ll_strcmp(s2)
def ll_join(s, length_dummy, lst):
length = lst.ll_length()
buf = ootype.new(ootype.StringBuilder)
# TODO: check if it's worth of preallocating the buffer with
# the exact length
## itemslen = 0
## i = 0
## while i < length:
## itemslen += lst.ll_getitem_fast(i).ll_strlen()
## i += 1
## resultlen = itemslen + s.ll_strlen()*(length-1)
## buf.ll_allocate(resultlen)
i = 0
while i < length-1:
item = lst.ll_getitem_fast(i)
buf.ll_append(item)
buf.ll_append(s)
i += 1
if length > 0:
lastitem = lst.ll_getitem_fast(i)
buf.ll_append(lastitem)
return buf.ll_build()
def ll_join_chars(length_dummy, lst):
buf = ootype.new(ootype.StringBuilder)
length = lst.ll_length()
buf.ll_allocate(length)
i = 0
while i < length:
buf.ll_append_char(lst.ll_getitem_fast(i))
i += 1
return buf.ll_build()
def ll_join_strs(length_dummy, lst):
buf = ootype.new(ootype.StringBuilder)
length = lst.ll_length()
#buf.ll_allocate(length)
i = 0
while i < length:
buf.ll_append(lst.ll_getitem_fast(i))
i += 1
return buf.ll_build()
def ll_stringslice_startonly(s, start):
return s.ll_substring(start, s.ll_strlen() - start)
def ll_stringslice(s, slice):
start = slice.start
stop = slice.stop
length = s.ll_strlen()
if stop > length:
stop = length
return s.ll_substring(start, stop-start)
def ll_stringslice_minusone(s):
return s.ll_substring(0, s.ll_strlen()-1)
def ll_split_chr(LIST, s, c):
return s.ll_split_chr(c)
def ll_int(s, base):
if not 2 <= base <= 36:
raise ValueError
strlen = s.ll_strlen()
i = 0
#XXX: only space is allowed as white space for now
while i < strlen and s.ll_stritem_nonneg(i) == ' ':
i += 1
if not i < strlen:
raise ValueError
#check sign
sign = 1
if s.ll_stritem_nonneg(i) == '-':
sign = -1
i += 1
elif s.ll_stritem_nonneg(i) == '+':
i += 1;
# skip whitespaces between sign and digits
while i < strlen and s.ll_stritem_nonneg(i) == ' ':
i += 1
#now get digits
val = 0
oldpos = i
while i < strlen:
c = ord(s.ll_stritem_nonneg(i))
if ord('a') <= c <= ord('z'):
digit = c - ord('a') + 10
elif ord('A') <= c <= ord('Z'):
digit = c - ord('A') + 10
elif ord('0') <= c <= ord('9'):
digit = c - ord('0')
else:
break
if digit >= base:
break
val = val * base + digit
i += 1
if i == oldpos:
raise ValueError # catch strings like '+' and '+ '
#skip trailing whitespace
while i < strlen and s.ll_stritem_nonneg(i) == ' ':
i += 1
if not i == strlen:
raise ValueError
return sign * val
def ll_float(ll_str):
# XXX workaround for an inlining bug
try:
return ootype.ooparse_float(ll_str)
except ValueError:
raise
# interface to build strings:
# x = ll_build_start(n)
# ll_build_push(x, next_string, 0)
# ll_build_push(x, next_string, 1)
# ...
# ll_build_push(x, next_string, n-1)
# s = ll_build_finish(x)
def ll_build_start(parts_count):
return ootype.new(ootype.StringBuilder)
def ll_build_push(buf, next_string, index):
buf.ll_append(next_string)
def ll_build_finish(buf):
return buf.ll_build()
def ll_constant(s):
return ootype.make_string(s)
ll_constant._annspecialcase_ = 'specialize:memo'
def do_stringformat(cls, hop, sourcevarsrepr):
InstanceRepr = hop.rtyper.type_system.rclass.InstanceRepr
string_repr = hop.rtyper.type_system.rstr.string_repr
s_str = hop.args_s[0]
assert s_str.is_constant()
s = s_str.const
c_append = hop.inputconst(ootype.Void, 'll_append')
c_build = hop.inputconst(ootype.Void, 'll_build')
cm1 = hop.inputconst(ootype.Signed, -1)
c8 = hop.inputconst(ootype.Signed, 8)
c10 = hop.inputconst(ootype.Signed, 10)
c16 = hop.inputconst(ootype.Signed, 16)
c_StringBuilder = hop.inputconst(ootype.Void, ootype.StringBuilder)
v_buf = hop.genop("new", [c_StringBuilder], resulttype=ootype.StringBuilder)
things = cls.parse_fmt_string(s)
argsiter = iter(sourcevarsrepr)
for thing in things:
if isinstance(thing, tuple):
code = thing[0]
vitem, r_arg = argsiter.next()
if not hasattr(r_arg, 'll_str'):
raise TyperError("ll_str unsupported for: %r" % r_arg)
if code == 's' or (code == 'r' and isinstance(r_arg, InstanceRepr)):
vchunk = hop.gendirectcall(r_arg.ll_str, vitem)
elif code == 'd':
assert isinstance(r_arg, IntegerRepr)
vchunk = hop.genop('oostring', [vitem, c10], resulttype=ootype.String)
elif code == 'f':
#assert isinstance(r_arg, FloatRepr)
vchunk = hop.gendirectcall(r_arg.ll_str, vitem)
elif code == 'x':
assert isinstance(r_arg, IntegerRepr)
vchunk = hop.genop('oostring', [vitem, c16], resulttype=ootype.String)
elif code == 'o':
assert isinstance(r_arg, IntegerRepr)
vchunk = hop.genop('oostring', [vitem, c8], resulttype=ootype.String)
else:
raise TyperError, "%%%s is not RPython" % (code, )
else:
vchunk = hop.inputconst(string_repr, thing)
#i = inputconst(Signed, i)
#hop.genop('setarrayitem', [vtemp, i, vchunk])
hop.genop('oosend', [c_append, v_buf, vchunk], resulttype=ootype.Void)
hop.exception_cannot_occur() # to ignore the ZeroDivisionError of '%'
return hop.genop('oosend', [c_build, v_buf], resulttype=ootype.String)
do_stringformat = classmethod(do_stringformat)
def add_helpers():
dic = {}
for name, meth in ootype.String._GENERIC_METHODS.iteritems():
if name in LLHelpers.__dict__:
continue
n_args = len(meth.ARGS)
args = ', '.join(['arg%d' % i for i in range(n_args)])
code = """
def %s(obj, %s):
return obj.%s(%s)
""" % (name, args, name, args)
exec code in dic
setattr(LLHelpers, name, staticmethod(dic[name]))
add_helpers()
del add_helpers
do_stringformat = LLHelpers.do_stringformat
string_repr = StringRepr()
char_repr = CharRepr()
unichar_repr = UniCharRepr()
char_repr.ll = LLHelpers
unichar_repr.ll = LLHelpers
emptystr = string_repr.convert_const("")
class StringIteratorRepr(AbstractStringIteratorRepr):
lowleveltype = ootype.Record({'string': string_repr.lowleveltype,
'index': ootype.Signed})
def __init__(self):
self.ll_striter = ll_striter
self.ll_strnext = ll_strnext
def ll_striter(string):
iter = ootype.new(string_iterator_repr.lowleveltype)
iter.string = string
iter.index = 0
return iter
def ll_strnext(iter):
string = iter.string
index = iter.index
if index >= string.ll_strlen():
raise StopIteration
iter.index = index + 1
return string.ll_stritem_nonneg(index)
string_iterator_repr = StringIteratorRepr()
# these should be in rclass, but circular imports prevent (also it's
# not that insane that a string constant is built in this file).
instance_str_prefix = string_repr.convert_const("<")
instance_str_suffix = string_repr.convert_const(" object>")
unboxed_instance_str_prefix = string_repr.convert_const("<unboxed ")
unboxed_instance_str_suffix = string_repr.convert_const(">")
list_str_open_bracket = string_repr.convert_const("[")
list_str_close_bracket = string_repr.convert_const("]")
list_str_sep = string_repr.convert_const(", ")
| Python |
from pypy.rpython.rgeneric import AbstractGenericCallableRepr
from pypy.rpython.ootypesystem import ootype
class GenericCallableRepr(AbstractGenericCallableRepr):
def create_low_leveltype(self):
l_args = [r_arg.lowleveltype for r_arg in self.args_r]
l_retval = self.r_result.lowleveltype
return ootype.StaticMethod(l_args, l_retval)
| Python |
from pypy.annotation.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.objspace.flow import model as flowmodel
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import Repr, IntegerRepr
from pypy.rlib.rarithmetic import r_uint
class __extend__(annmodel.SomePtr):
def rtyper_makerepr(self, rtyper):
## if self.is_constant() and not self.const: # constant NULL
## return nullptr_repr
## else:
return PtrRepr(self.ll_ptrtype)
def rtyper_makekey(self):
## if self.is_constant() and not self.const:
## return None
## else:
return self.__class__, self.ll_ptrtype
class PtrRepr(Repr):
def __init__(self, ptrtype):
assert isinstance(ptrtype, lltype.Ptr)
self.lowleveltype = ptrtype
def ll_str(self, p):
from pypy.rpython.lltypesystem.rstr import ll_str
id = lltype.cast_ptr_to_int(p)
return ll_str.ll_int2hex(r_uint(id), True)
def rtype_getattr(self, hop):
attr = hop.args_s[1].const
if isinstance(hop.s_result, annmodel.SomeLLADTMeth):
return hop.inputarg(hop.r_result, arg=0)
FIELD_TYPE = getattr(self.lowleveltype.TO, attr)
if isinstance(FIELD_TYPE, lltype.ContainerType):
newopname = 'getsubstruct'
else:
newopname = 'getfield'
vlist = hop.inputargs(self, lltype.Void)
return hop.genop(newopname, vlist,
resulttype = hop.r_result.lowleveltype)
def rtype_setattr(self, hop):
attr = hop.args_s[1].const
FIELD_TYPE = getattr(self.lowleveltype.TO, attr)
assert not isinstance(FIELD_TYPE, lltype.ContainerType)
vlist = hop.inputargs(self, lltype.Void, hop.args_r[2])
hop.genop('setfield', vlist)
def rtype_len(self, hop):
ARRAY = hop.args_r[0].lowleveltype.TO
if isinstance(ARRAY, lltype.FixedSizeArray):
return hop.inputconst(lltype.Signed, ARRAY.length)
else:
vlist = hop.inputargs(self)
return hop.genop('getarraysize', vlist,
resulttype = hop.r_result.lowleveltype)
def rtype_is_true(self, hop):
vlist = hop.inputargs(self)
return hop.genop('ptr_nonzero', vlist, resulttype=lltype.Bool)
def rtype_simple_call(self, hop):
if not isinstance(self.lowleveltype.TO, lltype.FuncType):
raise TyperError("calling a non-function %r", self.lowleveltype.TO)
vlist = hop.inputargs(*hop.args_r)
nexpected = len(self.lowleveltype.TO.ARGS)
nactual = len(vlist)-1
if nactual != nexpected:
raise TyperError("argcount mismatch: expected %d got %d" %
(nexpected, nactual))
if isinstance(vlist[0], flowmodel.Constant):
if hasattr(vlist[0].value, 'graph'):
hop.llops.record_extra_call(vlist[0].value.graph)
opname = 'direct_call'
else:
opname = 'indirect_call'
vlist.append(hop.inputconst(lltype.Void, None))
hop.exception_is_here()
return hop.genop(opname, vlist,
resulttype = self.lowleveltype.TO.RESULT)
def rtype_call_args(self, hop):
from pypy.rpython.rbuiltin import call_args_expand
hop, _ = call_args_expand(hop, takes_kwds=False)
hop.swap_fst_snd_args()
hop.r_s_popfirstarg()
return self.rtype_simple_call(hop)
class __extend__(pairtype(PtrRepr, IntegerRepr)):
def rtype_getitem((r_ptr, r_int), hop):
ARRAY = r_ptr.lowleveltype.TO
ITEM_TYPE = ARRAY.OF
if isinstance(ITEM_TYPE, lltype.ContainerType):
newopname = 'getarraysubstruct'
else:
newopname = 'getarrayitem'
vlist = hop.inputargs(r_ptr, lltype.Signed)
return hop.genop(newopname, vlist,
resulttype = hop.r_result.lowleveltype)
def rtype_setitem((r_ptr, r_int), hop):
ARRAY = r_ptr.lowleveltype.TO
ITEM_TYPE = ARRAY.OF
assert not isinstance(ITEM_TYPE, lltype.ContainerType)
vlist = hop.inputargs(r_ptr, lltype.Signed, hop.args_r[2])
hop.genop('setarrayitem', vlist)
# ____________________________________________________________
#
# Null Pointers
##class NullPtrRepr(Repr):
## lowleveltype = lltype.Void
## def rtype_is_true(self, hop):
## return hop.inputconst(lltype.Bool, False)
##nullptr_repr = NullPtrRepr()
##class __extend__(pairtype(NullPtrRepr, PtrRepr)):
## def convert_from_to((r_null, r_ptr), v, llops):
## # nullptr to general pointer
## return inputconst(r_ptr, _ptr(r_ptr.lowleveltype, None))
# ____________________________________________________________
#
# Comparisons
class __extend__(pairtype(PtrRepr, Repr)):
def rtype_eq((r_ptr, r_any), hop):
vlist = hop.inputargs(r_ptr, r_ptr)
return hop.genop('ptr_eq', vlist, resulttype=lltype.Bool)
def rtype_ne((r_ptr, r_any), hop):
vlist = hop.inputargs(r_ptr, r_ptr)
return hop.genop('ptr_ne', vlist, resulttype=lltype.Bool)
class __extend__(pairtype(Repr, PtrRepr)):
def rtype_eq((r_any, r_ptr), hop):
vlist = hop.inputargs(r_ptr, r_ptr)
return hop.genop('ptr_eq', vlist, resulttype=lltype.Bool)
def rtype_ne((r_any, r_ptr), hop):
vlist = hop.inputargs(r_ptr, r_ptr)
return hop.genop('ptr_ne', vlist, resulttype=lltype.Bool)
# ________________________________________________________________
# ADT methods
class __extend__(annmodel.SomeLLADTMeth):
def rtyper_makerepr(self, rtyper):
return LLADTMethRepr(self)
def rtyper_makekey(self):
return self.__class__, self.ll_ptrtype, self.func
class LLADTMethRepr(Repr):
def __init__(self, adtmeth):
self.func = adtmeth.func
self.lowleveltype = adtmeth.ll_ptrtype
def rtype_simple_call(self, hop):
hop2 = hop.copy()
func = self.func
s_func = hop.rtyper.annotator.bookkeeper.immutablevalue(func)
v_ptr = hop2.args_v[0]
hop2.r_s_popfirstarg()
hop2.v_s_insertfirstarg(v_ptr, annmodel.SomePtr(self.lowleveltype))
hop2.v_s_insertfirstarg(flowmodel.Constant(func), s_func)
return hop2.dispatch()
class __extend__(pairtype(PtrRepr, LLADTMethRepr)):
def convert_from_to((r_from, r_to), v, llops):
if r_from.lowleveltype == r_to.lowleveltype:
return v
return NotImplemented
| Python |
#
| Python |
from pypy.annotation.pairtype import pairtype
from pypy.rpython.error import TyperError
from pypy.rpython.lltypesystem.lltype import Signed, Void, Ptr
from pypy.rpython.rmodel import Repr, IntegerRepr, IteratorRepr
from pypy.objspace.flow.model import Constant
from pypy.rpython.rlist import dum_nocheck, dum_checkidx
class AbstractRangeRepr(Repr):
def __init__(self, step):
self.step = step
if step != 0:
self.lowleveltype = self.RANGE
else:
self.lowleveltype = self.RANGEST
def _getstep(self, v_rng, hop):
return hop.genop(self.getfield_opname,
[v_rng, hop.inputconst(Void, 'step')], resulttype=Signed)
def rtype_len(self, hop):
v_rng, = hop.inputargs(self)
if self.step != 0:
cstep = hop.inputconst(Signed, self.step)
else:
cstep = self._getstep(v_rng, hop)
return hop.gendirectcall(ll_rangelen, v_rng, cstep)
class __extend__(pairtype(AbstractRangeRepr, IntegerRepr)):
def rtype_getitem((r_rng, r_int), hop):
if hop.has_implicit_exception(IndexError):
spec = dum_checkidx
else:
spec = dum_nocheck
v_func = hop.inputconst(Void, spec)
v_lst, v_index = hop.inputargs(r_rng, Signed)
if r_rng.step != 0:
cstep = hop.inputconst(Signed, r_rng.step)
else:
cstep = r_rng._getstep(v_lst, hop)
if hop.args_s[1].nonneg:
llfn = ll_rangeitem_nonneg
else:
llfn = ll_rangeitem
hop.exception_is_here()
return hop.gendirectcall(llfn, v_func, v_lst, v_index, cstep)
# ____________________________________________________________
#
# Low-level methods.
def _ll_rangelen(start, stop, step):
if step > 0:
result = (stop - start + (step-1)) // step
else:
result = (start - stop - (step+1)) // (-step)
if result < 0:
result = 0
return result
def ll_rangelen(l, step):
return _ll_rangelen(l.start, l.stop, step)
def ll_rangeitem_nonneg(func, l, index, step):
if func is dum_checkidx and index >= _ll_rangelen(l.start, l.stop, step):
raise IndexError
return l.start + index * step
def ll_rangeitem(func, l, index, step):
if func is dum_checkidx:
length = _ll_rangelen(l.start, l.stop, step)
if index < 0:
index += length
if index < 0 or index >= length:
raise IndexError
else:
if index < 0:
length = _ll_rangelen(l.start, l.stop, step)
index += length
return l.start + index * step
# ____________________________________________________________
#
# Irregular operations.
def rtype_builtin_range(hop):
vstep = hop.inputconst(Signed, 1)
if hop.nb_args == 1:
vstart = hop.inputconst(Signed, 0)
vstop, = hop.inputargs(Signed)
elif hop.nb_args == 2:
vstart, vstop = hop.inputargs(Signed, Signed)
else:
vstart, vstop, vstep = hop.inputargs(Signed, Signed, Signed)
if isinstance(vstep, Constant) and vstep.value == 0:
# not really needed, annotator catches it. Just in case...
raise TyperError("range cannot have a const step of zero")
if isinstance(hop.r_result, AbstractRangeRepr):
if hop.r_result.step != 0:
c_rng = hop.inputconst(Void, hop.r_result.RANGE)
return hop.gendirectcall(hop.r_result.ll_newrange, c_rng, vstart, vstop)
else:
return hop.gendirectcall(hop.r_result.ll_newrangest, vstart, vstop, vstep)
else:
# cannot build a RANGE object, needs a real list
r_list = hop.r_result
ITEMTYPE = r_list.lowleveltype
if isinstance(ITEMTYPE, Ptr):
ITEMTYPE = ITEMTYPE.TO
cLIST = hop.inputconst(Void, ITEMTYPE)
return hop.gendirectcall(ll_range2list, cLIST, vstart, vstop, vstep)
rtype_builtin_xrange = rtype_builtin_range
def ll_range2list(LIST, start, stop, step):
if step == 0:
raise ValueError
length = _ll_rangelen(start, stop, step)
l = LIST.ll_newlist(length)
if LIST.ITEM is not Void:
idx = 0
while idx < length:
l.ll_setitem_fast(idx, start)
start += step
idx += 1
return l
# ____________________________________________________________
#
# Iteration.
class AbstractRangeIteratorRepr(IteratorRepr):
def __init__(self, r_rng):
self.r_rng = r_rng
if r_rng.step != 0:
self.lowleveltype = r_rng.RANGEITER
else:
self.lowleveltype = r_rng.RANGESTITER
def newiter(self, hop):
v_rng, = hop.inputargs(self.r_rng)
citerptr = hop.inputconst(Void, self.lowleveltype)
return hop.gendirectcall(self.ll_rangeiter, citerptr, v_rng)
def rtype_next(self, hop):
v_iter, = hop.inputargs(self)
args = hop.inputconst(Signed, self.r_rng.step),
if self.r_rng.step > 0:
llfn = ll_rangenext_up
elif self.r_rng.step < 0:
llfn = ll_rangenext_down
else:
llfn = ll_rangenext_updown
args = ()
hop.has_implicit_exception(StopIteration) # record that we know about it
hop.exception_is_here()
return hop.gendirectcall(llfn, v_iter, *args)
def ll_rangenext_up(iter, step):
next = iter.next
if next >= iter.stop:
raise StopIteration
iter.next = next + step
return next
def ll_rangenext_down(iter, step):
next = iter.next
if next <= iter.stop:
raise StopIteration
iter.next = next + step
return next
def ll_rangenext_updown(iter):
step = iter.step
if step > 0:
return ll_rangenext_up(iter, step)
else:
return ll_rangenext_down(iter, step)
| Python |
from pypy.tool.pairtype import pairtype
from pypy.objspace.flow.model import Constant
from pypy.rpython.rmodel import Repr
from pypy.rpython.error import TyperError
class ControlledInstanceRepr(Repr):
def __init__(self, rtyper, s_real_obj, controller):
self.rtyper = rtyper
self.s_real_obj = s_real_obj
self.r_real_obj = rtyper.getrepr(s_real_obj)
self.controller = controller
self.lowleveltype = self.r_real_obj.lowleveltype
def convert_const(self, value):
real_value = self.controller.convert(value)
return self.r_real_obj.convert_const(real_value)
def reveal(self, r):
if r is not self:
raise TyperError("expected %r, got %r" % (self, r))
return self.s_real_obj, self.r_real_obj
def rtype_getattr(self, hop):
return self.controller.rtype_getattr(hop)
def rtype_setattr(self, hop):
return self.controller.rtype_setattr(hop)
def rtype_is_true(self, hop):
return self.controller.rtype_is_true(hop)
class __extend__(pairtype(ControlledInstanceRepr, Repr)):
def rtype_getitem((r_controlled, r_key), hop):
return r_controlled.controller.rtype_getitem(hop)
def rtype_setitem((r_controlled, r_key), hop):
return r_controlled.controller.rtype_setitem(hop)
def rtypedelegate(callable, hop, revealargs=[0], revealresult=False):
bk = hop.rtyper.annotator.bookkeeper
c_meth = Constant(callable)
s_meth = bk.immutablevalue(callable)
hop2 = hop.copy()
for index in revealargs:
r_controlled = hop2.args_r[index]
if not isinstance(r_controlled, ControlledInstanceRepr):
raise TyperError("args_r[%d] = %r, expected ControlledInstanceRepr"
% (index, r_controlled))
s_new, r_new = r_controlled.s_real_obj, r_controlled.r_real_obj
hop2.args_s[index], hop2.args_r[index] = s_new, r_new
v = hop2.args_v[index]
if isinstance(v, Constant):
real_value = r_controlled.controller.convert(v.value)
hop2.args_v[index] = Constant(real_value)
if revealresult:
r_controlled = hop2.r_result
if not isinstance(r_controlled, ControlledInstanceRepr):
raise TyperError("r_result = %r, expected ControlledInstanceRepr"
% (r_controlled,))
s_new, r_new = r_controlled.s_real_obj, r_controlled.r_real_obj
hop2.s_result, hop2.r_result = s_new, r_new
hop2.v_s_insertfirstarg(c_meth, s_meth)
hop2.forced_opname = 'simple_call'
return hop2.dispatch()
| Python |
from pypy.annotation import model as annmodel
from pypy.annotation.pairtype import pairtype
from pypy.annotation.bookkeeper import getbookkeeper
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.rpython.annlowlevel import cachedtype
from pypy.rpython.error import TyperError
class ControllerEntry(ExtRegistryEntry):
def compute_result_annotation(self, *args_s, **kwds_s):
controller = self.getcontroller(*args_s, **kwds_s)
return controller.ctrl_new_ex(self.bookkeeper, *args_s, **kwds_s)
def getcontroller(self, *args_s, **kwds_s):
return self._controller_()
def specialize_call(self, hop, **kwds_i):
if hop.s_result == annmodel.s_ImpossibleValue:
raise TyperError("object creation always raises: %s" % (
hop.spaceop,))
controller = hop.s_result.controller
return controller.rtype_new(hop, **kwds_i)
def controlled_instance_box(controller, obj):
XXX # only for special-casing by ExtRegistryEntry below
def controlled_instance_unbox(controller, obj):
XXX # only for special-casing by ExtRegistryEntry below
def controlled_instance_is_box(controller, obj):
XXX # only for special-casing by ExtRegistryEntry below
class ControllerEntryForPrebuilt(ExtRegistryEntry):
def compute_annotation(self):
controller = self.getcontroller()
real_obj = controller.convert(self.instance)
s_real_obj = self.bookkeeper.immutablevalue(real_obj)
return SomeControlledInstance(s_real_obj, controller)
def getcontroller(self):
return self._controller_()
class Controller(object):
__metaclass__ = cachedtype
def _freeze_(self):
return True
def box(self, obj):
return controlled_instance_box(self, obj)
box._annspecialcase_ = 'specialize:arg(0)'
def unbox(self, obj):
return controlled_instance_unbox(self, obj)
unbox._annspecialcase_ = 'specialize:arg(0)'
def is_box(self, obj):
return controlled_instance_is_box(self, obj)
is_box._annspecialcase_ = 'specialize:arg(0)'
def ctrl_new(self, *args_s, **kwds_s):
if kwds_s:
raise TypeError("cannot handle keyword arguments in %s" % (
self.new,))
s_real_obj = delegate(self.new, *args_s)
if s_real_obj == annmodel.s_ImpossibleValue:
return annmodel.s_ImpossibleValue
else:
return SomeControlledInstance(s_real_obj, controller=self)
def ctrl_new_ex(self, bookkeeper, *args_s, **kwds_s):
return self.ctrl_new(*args_s, **kwds_s)
def rtype_new(self, hop):
from pypy.rpython.rcontrollerentry import rtypedelegate
return rtypedelegate(self.new, hop, revealargs=[], revealresult=True)
def getattr(self, obj, attr):
return getattr(self, 'get_' + attr)(obj)
getattr._annspecialcase_ = 'specialize:arg(0, 2)'
def ctrl_getattr(self, s_obj, s_attr):
return delegate(self.getattr, s_obj, s_attr)
def rtype_getattr(self, hop):
from pypy.rpython.rcontrollerentry import rtypedelegate
return rtypedelegate(self.getattr, hop)
def setattr(self, obj, attr, value):
return getattr(self, 'set_' + attr)(obj, value)
setattr._annspecialcase_ = 'specialize:arg(0, 2)'
def ctrl_setattr(self, s_obj, s_attr, s_value):
return delegate(self.setattr, s_obj, s_attr, s_value)
def rtype_setattr(self, hop):
from pypy.rpython.rcontrollerentry import rtypedelegate
return rtypedelegate(self.setattr, hop)
def ctrl_getitem(self, s_obj, s_key):
return delegate(self.getitem, s_obj, s_key)
def rtype_getitem(self, hop):
from pypy.rpython.rcontrollerentry import rtypedelegate
return rtypedelegate(self.getitem, hop)
def ctrl_setitem(self, s_obj, s_key, s_value):
return delegate(self.setitem, s_obj, s_key, s_value)
def rtype_setitem(self, hop):
from pypy.rpython.rcontrollerentry import rtypedelegate
return rtypedelegate(self.setitem, hop)
def ctrl_is_true(self, s_obj):
return delegate(self.is_true, s_obj)
def rtype_is_true(self, hop):
from pypy.rpython.rcontrollerentry import rtypedelegate
return rtypedelegate(self.is_true, hop)
def ctrl_call(self, s_obj, *args_s):
return delegate(self.call, s_obj, *args_s)
def rtype_call(self, hop):
from pypy.rpython.rcontrollerentry import rtypedelegate
return rtypedelegate(self.call, hop)
def delegate(boundmethod, *args_s):
bk = getbookkeeper()
s_meth = bk.immutablevalue(boundmethod)
return bk.emulate_pbc_call(bk.position_key, s_meth, args_s,
callback = bk.position_key)
class BoxEntry(ExtRegistryEntry):
_about_ = controlled_instance_box
def compute_result_annotation(self, s_controller, s_real_obj):
if s_real_obj == annmodel.s_ImpossibleValue:
return annmodel.s_ImpossibleValue
else:
assert s_controller.is_constant()
controller = s_controller.const
return SomeControlledInstance(s_real_obj, controller=controller)
def specialize_call(self, hop):
from pypy.rpython.rcontrollerentry import ControlledInstanceRepr
if not isinstance(hop.r_result, ControlledInstanceRepr):
raise TyperError("box() should return ControlledInstanceRepr,\n"
"got %r" % (hop.r_result,))
hop.exception_cannot_occur()
return hop.inputarg(hop.r_result.r_real_obj, arg=1)
class UnboxEntry(ExtRegistryEntry):
_about_ = controlled_instance_unbox
def compute_result_annotation(self, s_controller, s_obj):
if s_obj == annmodel.s_ImpossibleValue:
return annmodel.s_ImpossibleValue
else:
assert isinstance(s_obj, SomeControlledInstance)
return s_obj.s_real_obj
def specialize_call(self, hop):
from pypy.rpython.rcontrollerentry import ControlledInstanceRepr
if not isinstance(hop.args_r[1], ControlledInstanceRepr):
raise TyperError("unbox() should take a ControlledInstanceRepr,\n"
"got %r" % (hop.args_r[1],))
hop.exception_cannot_occur()
v = hop.inputarg(hop.args_r[1], arg=1)
return hop.llops.convertvar(v, hop.args_r[1].r_real_obj, hop.r_result)
class IsBoxEntry(ExtRegistryEntry):
_about_ = controlled_instance_is_box
def compute_result_annotation(self, s_controller, s_obj):
if s_obj == annmodel.s_ImpossibleValue:
return annmodel.s_ImpossibleValue
else:
assert s_controller.is_constant()
controller = s_controller.const
result = (isinstance(s_obj, SomeControlledInstance) and
s_obj.controller == controller)
return self.bookkeeper.immutablevalue(result)
def specialize_call(self, hop):
from pypy.rpython.lltypesystem import lltype
assert hop.s_result.is_constant()
return hop.inputconst(lltype.Bool, hop.s_result.const)
# ____________________________________________________________
class SomeControlledInstance(annmodel.SomeObject):
def __init__(self, s_real_obj, controller):
self.s_real_obj = s_real_obj
self.controller = controller
self.knowntype = controller.knowntype
def rtyper_makerepr(self, rtyper):
from pypy.rpython.rcontrollerentry import ControlledInstanceRepr
return ControlledInstanceRepr(rtyper, self.s_real_obj, self.controller)
def rtyper_makekey_ex(self, rtyper):
real_key = rtyper.makekey(self.s_real_obj)
return self.__class__, real_key, self.controller
class __extend__(SomeControlledInstance):
def getattr(s_cin, s_attr):
assert s_attr.is_constant()
return s_cin.controller.ctrl_getattr(s_cin.s_real_obj, s_attr)
def setattr(s_cin, s_attr, s_value):
assert s_attr.is_constant()
s_cin.controller.ctrl_setattr(s_cin.s_real_obj, s_attr, s_value)
def is_true(s_cin):
return s_cin.controller.ctrl_is_true(s_cin.s_real_obj)
def simple_call(s_cin, *args_s):
return s_cin.controller.ctrl_call(s_cin.s_real_obj, *args_s)
class __extend__(pairtype(SomeControlledInstance, annmodel.SomeObject)):
def getitem((s_cin, s_key)):
return s_cin.controller.ctrl_getitem(s_cin.s_real_obj, s_key)
def setitem((s_cin, s_key), s_value):
s_cin.controller.ctrl_setitem(s_cin.s_real_obj, s_key, s_value)
class __extend__(pairtype(SomeControlledInstance, SomeControlledInstance)):
def union((s_cin1, s_cin2)):
if s_cin1.controller is not s_cin2.controller:
raise annmodel.UnionError("different controller!")
return SomeControlledInstance(annmodel.unionof(s_cin1.s_real_obj,
s_cin2.s_real_obj),
s_cin1.controller)
| Python |
from pypy.tool.staticmethods import StaticMethods
from pypy.annotation.pairtype import pairtype, pair
from pypy.annotation import model as annmodel
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import IntegerRepr, IteratorRepr
from pypy.rpython.rmodel import inputconst, Repr
from pypy.rpython.rtuple import AbstractTupleRepr
from pypy.rpython.rslice import AbstractSliceRepr
from pypy.rpython import rint
from pypy.rpython.lltypesystem.lltype import Signed, Bool, Void, UniChar
class AbstractStringRepr(Repr):
pass
class AbstractCharRepr(AbstractStringRepr):
pass
class AbstractUniCharRepr(Repr):
pass
class __extend__(annmodel.SomeString):
def rtyper_makerepr(self, rtyper):
return rtyper.type_system.rstr.string_repr
def rtyper_makekey(self):
return self.__class__,
class __extend__(annmodel.SomeChar):
def rtyper_makerepr(self, rtyper):
return rtyper.type_system.rstr.char_repr
def rtyper_makekey(self):
return self.__class__,
class __extend__(annmodel.SomeUnicodeCodePoint):
def rtyper_makerepr(self, rtyper):
return rtyper.type_system.rstr.unichar_repr
def rtyper_makekey(self):
return self.__class__,
class __extend__(AbstractStringRepr):
def get_ll_eq_function(self):
return self.ll.ll_streq
def get_ll_hash_function(self):
return self.ll.ll_strhash
def get_ll_fasthash_function(self):
return self.ll.ll_strfasthash
def rtype_len(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, = hop.inputargs(string_repr)
return hop.gendirectcall(self.ll.ll_strlen, v_str)
def rtype_is_true(self, hop):
s_str = hop.args_s[0]
if s_str.can_be_None:
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, = hop.inputargs(string_repr)
return hop.gendirectcall(self.ll.ll_str_is_true, v_str)
else:
# defaults to checking the length
return super(AbstractStringRepr, self).rtype_is_true(hop)
def rtype_ord(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, = hop.inputargs(string_repr)
c_zero = inputconst(Signed, 0)
v_chr = hop.gendirectcall(self.ll.ll_stritem_nonneg, v_str, c_zero)
return hop.genop('cast_char_to_int', [v_chr], resulttype=Signed)
def rtype_method_startswith(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, v_value = hop.inputargs(string_repr, string_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_startswith, v_str, v_value)
def rtype_method_endswith(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, v_value = hop.inputargs(string_repr, string_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_endswith, v_str, v_value)
def rtype_method_find(self, hop, reverse=False):
rstr = hop.rtyper.type_system.rstr
v_str = hop.inputarg(rstr.string_repr, arg=0)
if hop.args_r[1] == rstr.char_repr:
v_value = hop.inputarg(rstr.char_repr, arg=1)
llfn = reverse and self.ll.ll_rfind_char or self.ll.ll_find_char
else:
v_value = hop.inputarg(rstr.string_repr, arg=1)
llfn = reverse and self.ll.ll_rfind or self.ll.ll_find
if hop.nb_args > 2:
v_start = hop.inputarg(Signed, arg=2)
if not hop.args_s[2].nonneg:
raise TyperError("str.find() start must be proven non-negative")
else:
v_start = hop.inputconst(Signed, 0)
if hop.nb_args > 3:
v_end = hop.inputarg(Signed, arg=3)
if not hop.args_s[2].nonneg:
raise TyperError("str.find() end must be proven non-negative")
else:
v_end = hop.gendirectcall(self.ll.ll_strlen, v_str)
hop.exception_cannot_occur()
return hop.gendirectcall(llfn, v_str, v_value, v_start, v_end)
def rtype_method_rfind(self, hop):
return self.rtype_method_find(hop, reverse=True)
def rtype_method_count(self, hop):
rstr = hop.rtyper.type_system.rstr
v_str = hop.inputarg(rstr.string_repr, arg=0)
if hop.args_r[1] == rstr.char_repr:
v_value = hop.inputarg(rstr.char_repr, arg=1)
llfn = self.ll.ll_count_char
else:
v_value = hop.inputarg(rstr.string_repr, arg=1)
llfn = self.ll.ll_count
if hop.nb_args > 2:
v_start = hop.inputarg(Signed, arg=2)
if not hop.args_s[2].nonneg:
raise TyperError("str.count() start must be proven non-negative")
else:
v_start = hop.inputconst(Signed, 0)
if hop.nb_args > 3:
v_end = hop.inputarg(Signed, arg=3)
if not hop.args_s[2].nonneg:
raise TyperError("str.count() end must be proven non-negative")
else:
v_end = hop.gendirectcall(self.ll.ll_strlen, v_str)
hop.exception_cannot_occur()
return hop.gendirectcall(llfn, v_str, v_value, v_start, v_end)
def rtype_method_strip(self, hop, left=True, right=True):
rstr = hop.rtyper.type_system.rstr
v_str = hop.inputarg(rstr.string_repr, arg=0)
v_char = hop.inputarg(rstr.char_repr, arg=1)
v_left = hop.inputconst(Bool, left)
v_right = hop.inputconst(Bool, right)
return hop.gendirectcall(self.ll.ll_strip, v_str, v_char, v_left, v_right)
def rtype_method_lstrip(self, hop):
return self.rtype_method_strip(hop, left=True, right=False)
def rtype_method_rstrip(self, hop):
return self.rtype_method_strip(hop, left=False, right=True)
def rtype_method_upper(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, = hop.inputargs(string_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_upper, v_str)
def rtype_method_lower(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, = hop.inputargs(string_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_lower, v_str)
def _list_length_items(self, hop, v_lst, LIST):
"""Return two Variables containing the length and items of a
list. Need to be overriden because it is typesystem-specific."""
raise NotImplementedError
def rtype_method_join(self, hop):
hop.exception_cannot_occur()
rstr = hop.rtyper.type_system.rstr
if hop.s_result.is_constant():
return inputconst(rstr.string_repr, hop.s_result.const)
r_lst = hop.args_r[1]
if not isinstance(r_lst, hop.rtyper.type_system.rlist.BaseListRepr):
raise TyperError("string.join of non-list: %r" % r_lst)
v_str, v_lst = hop.inputargs(rstr.string_repr, r_lst)
v_length, v_items = self._list_length_items(hop, v_lst, r_lst.lowleveltype)
if hop.args_s[0].is_constant() and hop.args_s[0].const == '':
if r_lst.item_repr == rstr.string_repr:
llfn = self.ll.ll_join_strs
elif r_lst.item_repr == rstr.char_repr:
llfn = self.ll.ll_join_chars
else:
raise TyperError("''.join() of non-string list: %r" % r_lst)
return hop.gendirectcall(llfn, v_length, v_items)
else:
if r_lst.item_repr == rstr.string_repr:
llfn = self.ll.ll_join
else:
raise TyperError("sep.join() of non-string list: %r" % r_lst)
return hop.gendirectcall(llfn, v_str, v_length, v_items)
def rtype_method_split(self, hop):
rstr = hop.rtyper.type_system.rstr
v_str, v_chr = hop.inputargs(rstr.string_repr, rstr.char_repr)
try:
list_type = hop.r_result.lowleveltype.TO
except AttributeError:
list_type = hop.r_result.lowleveltype
cLIST = hop.inputconst(Void, list_type)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_split_chr, cLIST, v_str, v_chr)
def rtype_method_replace(self, hop):
rstr = hop.rtyper.type_system.rstr
if not (hop.args_r[1] == rstr.char_repr and hop.args_r[2] == rstr.char_repr):
raise TyperError, 'replace only works for char args'
v_str, v_c1, v_c2 = hop.inputargs(rstr.string_repr, rstr.char_repr, rstr.char_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_replace_chr_chr, v_str, v_c1, v_c2)
def rtype_int(self, hop):
hop.has_implicit_exception(ValueError) # record that we know about it
string_repr = hop.rtyper.type_system.rstr.string_repr
if hop.nb_args == 1:
v_str, = hop.inputargs(string_repr)
c_base = inputconst(Signed, 10)
hop.exception_is_here()
return hop.gendirectcall(self.ll.ll_int, v_str, c_base)
if not hop.args_r[1] == rint.signed_repr:
raise TyperError, 'base needs to be an int'
v_str, v_base= hop.inputargs(string_repr, rint.signed_repr)
hop.exception_is_here()
return hop.gendirectcall(self.ll.ll_int, v_str, v_base)
def rtype_float(self, hop):
hop.has_implicit_exception(ValueError) # record that we know about it
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, = hop.inputargs(string_repr)
hop.exception_is_here()
return hop.gendirectcall(self.ll.ll_float, v_str)
def ll_str(self, s):
return s
class __extend__(pairtype(AbstractStringRepr, Repr)):
def rtype_mod((r_str, _), hop):
# for the case where the 2nd argument is a tuple, see the
# overriding rtype_mod() below
return r_str.ll.do_stringformat(hop, [(hop.args_v[1], hop.args_r[1])])
class __extend__(pairtype(AbstractStringRepr, IntegerRepr)):
def rtype_getitem((r_str, r_int), hop, checkidx=False):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, v_index = hop.inputargs(string_repr, Signed)
if checkidx:
if hop.args_s[1].nonneg:
llfn = r_str.ll.ll_stritem_nonneg_checked
else:
llfn = r_str.ll.ll_stritem_checked
else:
if hop.args_s[1].nonneg:
llfn = r_str.ll.ll_stritem_nonneg
else:
llfn = r_str.ll.ll_stritem
if checkidx:
hop.exception_is_here()
else:
hop.exception_cannot_occur()
return hop.gendirectcall(llfn, v_str, v_index)
rtype_getitem_key = rtype_getitem
def rtype_getitem_idx((r_str, r_int), hop):
return pair(r_str, r_int).rtype_getitem(hop, checkidx=True)
rtype_getitem_idx_key = rtype_getitem_idx
class __extend__(pairtype(AbstractStringRepr, AbstractSliceRepr)):
def rtype_getitem((r_str, r_slic), hop):
rstr = hop.rtyper.type_system.rstr
rslice = hop.rtyper.type_system.rslice
if r_slic == rslice.startonly_slice_repr:
v_str, v_start = hop.inputargs(rstr.string_repr, rslice.startonly_slice_repr)
return hop.gendirectcall(r_str.ll.ll_stringslice_startonly, v_str, v_start)
if r_slic == rslice.startstop_slice_repr:
v_str, v_slice = hop.inputargs(rstr.string_repr, rslice.startstop_slice_repr)
return hop.gendirectcall(r_str.ll.ll_stringslice, v_str, v_slice)
if r_slic == rslice.minusone_slice_repr:
v_str, v_ignored = hop.inputargs(rstr.string_repr, rslice.minusone_slice_repr)
return hop.gendirectcall(r_str.ll.ll_stringslice_minusone, v_str)
raise TyperError(r_slic)
class __extend__(pairtype(AbstractStringRepr, AbstractStringRepr)):
def rtype_add((r_str1, r_str2), hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
if hop.s_result.is_constant():
return hop.inputconst(string_repr, hop.s_result.const)
v_str1, v_str2 = hop.inputargs(string_repr, string_repr)
return hop.gendirectcall(r_str1.ll.ll_strconcat, v_str1, v_str2)
rtype_inplace_add = rtype_add
def rtype_eq((r_str1, r_str2), hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str1, v_str2 = hop.inputargs(string_repr, string_repr)
return hop.gendirectcall(r_str1.ll.ll_streq, v_str1, v_str2)
def rtype_ne((r_str1, r_str2), hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str1, v_str2 = hop.inputargs(string_repr, string_repr)
vres = hop.gendirectcall(r_str1.ll.ll_streq, v_str1, v_str2)
return hop.genop('bool_not', [vres], resulttype=Bool)
def rtype_lt((r_str1, r_str2), hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str1, v_str2 = hop.inputargs(string_repr, string_repr)
vres = hop.gendirectcall(r_str1.ll.ll_strcmp, v_str1, v_str2)
return hop.genop('int_lt', [vres, hop.inputconst(Signed, 0)],
resulttype=Bool)
def rtype_le((r_str1, r_str2), hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str1, v_str2 = hop.inputargs(string_repr, string_repr)
vres = hop.gendirectcall(r_str1.ll.ll_strcmp, v_str1, v_str2)
return hop.genop('int_le', [vres, hop.inputconst(Signed, 0)],
resulttype=Bool)
def rtype_ge((r_str1, r_str2), hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str1, v_str2 = hop.inputargs(string_repr, string_repr)
vres = hop.gendirectcall(r_str1.ll.ll_strcmp, v_str1, v_str2)
return hop.genop('int_ge', [vres, hop.inputconst(Signed, 0)],
resulttype=Bool)
def rtype_gt((r_str1, r_str2), hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str1, v_str2 = hop.inputargs(string_repr, string_repr)
vres = hop.gendirectcall(r_str1.ll.ll_strcmp, v_str1, v_str2)
return hop.genop('int_gt', [vres, hop.inputconst(Signed, 0)],
resulttype=Bool)
class __extend__(pairtype(AbstractStringRepr, AbstractCharRepr)):
def rtype_contains((r_str, r_chr), hop):
rstr = hop.rtyper.type_system.rstr
v_str, v_chr = hop.inputargs(rstr.string_repr, rstr.char_repr)
return hop.gendirectcall(r_str.ll.ll_contains, v_str, v_chr)
class __extend__(pairtype(AbstractStringRepr, AbstractTupleRepr)):
def rtype_mod((r_str, r_tuple), hop):
r_tuple = hop.args_r[1]
v_tuple = hop.args_v[1]
sourcevars = []
for i, r_arg in enumerate(r_tuple.external_items_r):
v_item = r_tuple.getitem(hop.llops, v_tuple, i)
sourcevars.append((v_item, r_arg))
return r_str.ll.do_stringformat(hop, sourcevars)
class __extend__(AbstractCharRepr):
def convert_const(self, value):
if not isinstance(value, str) or len(value) != 1:
raise TyperError("not a character: %r" % (value,))
return value
def get_ll_eq_function(self):
return None
def get_ll_hash_function(self):
return self.ll.ll_char_hash
get_ll_fasthash_function = get_ll_hash_function
def ll_str(self, ch):
return self.ll.ll_chr2str(ch)
def rtype_len(_, hop):
return hop.inputconst(Signed, 1)
def rtype_is_true(_, hop):
assert not hop.args_s[0].can_be_None
return hop.inputconst(Bool, True)
def rtype_ord(_, hop):
rstr = hop.rtyper.type_system.rstr
vlist = hop.inputargs(rstr.char_repr)
return hop.genop('cast_char_to_int', vlist, resulttype=Signed)
def _rtype_method_isxxx(_, llfn, hop):
rstr = hop.rtyper.type_system.rstr
vlist = hop.inputargs(rstr.char_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(llfn, vlist[0])
def rtype_method_isspace(self, hop):
return self._rtype_method_isxxx(self.ll.ll_char_isspace, hop)
def rtype_method_isdigit(self, hop):
return self._rtype_method_isxxx(self.ll.ll_char_isdigit, hop)
def rtype_method_isalpha(self, hop):
return self._rtype_method_isxxx(self.ll.ll_char_isalpha, hop)
def rtype_method_isalnum(self, hop):
return self._rtype_method_isxxx(self.ll.ll_char_isalnum, hop)
def rtype_method_isupper(self, hop):
return self._rtype_method_isxxx(self.ll.ll_char_isupper, hop)
def rtype_method_islower(self, hop):
return self._rtype_method_isxxx(self.ll.ll_char_islower, hop)
class __extend__(pairtype(AbstractCharRepr, IntegerRepr)):
def rtype_mul((r_chr, r_int), hop):
rstr = hop.rtyper.type_system.rstr
v_char, v_int = hop.inputargs(rstr.char_repr, Signed)
return hop.gendirectcall(r_chr.ll.ll_char_mul, v_char, v_int)
rtype_inplace_mul = rtype_mul
class __extend__(pairtype(IntegerRepr, AbstractCharRepr)):
def rtype_mul((r_int, r_chr), hop):
rstr = hop.rtyper.type_system.rstr
v_int, v_char = hop.inputargs(Signed, rstr.char_repr)
return hop.gendirectcall(r_chr.ll.ll_char_mul, v_char, v_int)
rtype_inplace_mul = rtype_mul
class __extend__(pairtype(AbstractCharRepr, AbstractCharRepr)):
def rtype_eq(_, hop): return _rtype_compare_template(hop, 'eq')
def rtype_ne(_, hop): return _rtype_compare_template(hop, 'ne')
def rtype_lt(_, hop): return _rtype_compare_template(hop, 'lt')
def rtype_le(_, hop): return _rtype_compare_template(hop, 'le')
def rtype_gt(_, hop): return _rtype_compare_template(hop, 'gt')
def rtype_ge(_, hop): return _rtype_compare_template(hop, 'ge')
#Helper functions for comparisons
def _rtype_compare_template(hop, func):
rstr = hop.rtyper.type_system.rstr
vlist = hop.inputargs(rstr.char_repr, rstr.char_repr)
return hop.genop('char_'+func, vlist, resulttype=Bool)
class __extend__(AbstractUniCharRepr):
def convert_const(self, value):
if isinstance(value, str):
value = unicode(value)
if not isinstance(value, unicode) or len(value) != 1:
raise TyperError("not a unicode character: %r" % (value,))
return value
def get_ll_eq_function(self):
return None
def get_ll_hash_function(self):
return self.ll.ll_unichar_hash
get_ll_fasthash_function = get_ll_hash_function
## def rtype_len(_, hop):
## return hop.inputconst(Signed, 1)
##
## def rtype_is_true(_, hop):
## assert not hop.args_s[0].can_be_None
## return hop.inputconst(Bool, True)
def rtype_ord(_, hop):
rstr = hop.rtyper.type_system.rstr
vlist = hop.inputargs(rstr.unichar_repr)
return hop.genop('cast_unichar_to_int', vlist, resulttype=Signed)
class __extend__(pairtype(AbstractUniCharRepr, AbstractUniCharRepr),
pairtype(AbstractCharRepr, AbstractUniCharRepr),
pairtype(AbstractUniCharRepr, AbstractCharRepr)):
def rtype_eq(_, hop): return _rtype_unchr_compare_template(hop, 'eq')
def rtype_ne(_, hop): return _rtype_unchr_compare_template(hop, 'ne')
## def rtype_lt(_, hop): return _rtype_unchr_compare_template(hop, 'lt')
## def rtype_le(_, hop): return _rtype_unchr_compare_template(hop, 'le')
## def rtype_gt(_, hop): return _rtype_unchr_compare_template(hop, 'gt')
## def rtype_ge(_, hop): return _rtype_unchr_compare_template(hop, 'ge')
#Helper functions for comparisons
def _rtype_unchr_compare_template(hop, func):
rstr = hop.rtyper.type_system.rstr
vlist = hop.inputargs(rstr.unichar_repr, rstr.unichar_repr)
return hop.genop('unichar_'+func, vlist, resulttype=Bool)
#
# _________________________ Conversions _________________________
class __extend__(pairtype(AbstractCharRepr, AbstractStringRepr)):
def convert_from_to((r_from, r_to), v, llops):
rstr = llops.rtyper.type_system.rstr
if r_from == rstr.char_repr and r_to == rstr.string_repr:
return llops.gendirectcall(r_from.ll.ll_chr2str, v)
return NotImplemented
class __extend__(pairtype(AbstractStringRepr, AbstractCharRepr)):
def convert_from_to((r_from, r_to), v, llops):
rstr = llops.rtyper.type_system.rstr
if r_from == rstr.string_repr and r_to == rstr.char_repr:
c_zero = inputconst(Signed, 0)
return llops.gendirectcall(r_from.ll.ll_stritem_nonneg, v, c_zero)
return NotImplemented
class __extend__(pairtype(AbstractCharRepr, AbstractUniCharRepr)):
def convert_from_to((r_from, r_to), v, llops):
v2 = llops.genop('cast_char_to_int', [v], resulttype=Signed)
return llops.genop('cast_int_to_unichar', [v2], resulttype=UniChar)
# ____________________________________________________________
#
# Iteration.
class AbstractStringIteratorRepr(IteratorRepr):
def newiter(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
v_str, = hop.inputargs(string_repr)
return hop.gendirectcall(self.ll_striter, v_str)
def rtype_next(self, hop):
v_iter, = hop.inputargs(self)
hop.has_implicit_exception(StopIteration) # record that we know about it
hop.exception_is_here()
return hop.gendirectcall(self.ll_strnext, v_iter)
# ____________________________________________________________
#
# Low-level methods. These can be run for testing, but are meant to
# be direct_call'ed from rtyped flow graphs, which means that they will
# get flowed and annotated, mostly with SomePtr.
#
# this class contains low level helpers used both by lltypesystem and
# ootypesystem; each typesystem should subclass it and add its own
# primitives.
class AbstractLLHelpers:
__metaclass__ = StaticMethods
def ll_char_isspace(ch):
c = ord(ch)
return c == 32 or (c <= 13 and c >= 9) # c in (9, 10, 11, 12, 13, 32)
def ll_char_isdigit(ch):
c = ord(ch)
return c <= 57 and c >= 48
def ll_char_isalpha(ch):
c = ord(ch)
if c >= 97:
return c <= 122
else:
return 65 <= c <= 90
def ll_char_isalnum(ch):
c = ord(ch)
if c >= 65:
if c >= 97:
return c <= 122
else:
return c <= 90
else:
return 48 <= c <= 57
def ll_char_isupper(ch):
c = ord(ch)
return 65 <= c <= 90
def ll_char_islower(ch):
c = ord(ch)
return 97 <= c <= 122
def ll_char_hash(ch):
return ord(ch)
def ll_unichar_hash(ch):
return ord(ch)
def ll_str_is_true(cls, s):
# check if a string is True, allowing for None
return bool(s) and cls.ll_strlen(s) != 0
ll_str_is_true = classmethod(ll_str_is_true)
def ll_stritem_nonneg_checked(cls, s, i):
if i >= cls.ll_strlen(s):
raise IndexError
return cls.ll_stritem_nonneg(s, i)
ll_stritem_nonneg_checked = classmethod(ll_stritem_nonneg_checked)
def ll_stritem(cls, s, i):
if i < 0:
i += cls.ll_strlen(s)
return cls.ll_stritem_nonneg(s, i)
ll_stritem = classmethod(ll_stritem)
def ll_stritem_checked(cls, s, i):
length = cls.ll_strlen(s)
if i < 0:
i += length
if i >= length or i < 0:
raise IndexError
return cls.ll_stritem_nonneg(s, i)
ll_stritem_checked = classmethod(ll_stritem_checked)
def parse_fmt_string(fmt):
# we support x, d, s, f, [r]
it = iter(fmt)
r = []
curstr = ''
for c in it:
if c == '%':
f = it.next()
if f == '%':
curstr += '%'
continue
if curstr:
r.append(curstr)
curstr = ''
if f not in 'xdosrf':
raise TyperError("Unsupported formatting specifier: %r in %r" % (f, fmt))
r.append((f,))
else:
curstr += c
if curstr:
r.append(curstr)
return r
def ll_float(ll_str):
from pypy.rpython.annlowlevel import hlstr
from pypy.rlib.rarithmetic import break_up_float, parts_to_float
s = hlstr(ll_str)
assert s is not None
n = len(s)
beg = 0
while beg < n:
if s[beg] == ' ':
beg += 1
else:
break
if beg == n:
raise ValueError
end = n-1
while end >= 0:
if s[end] == ' ':
end -= 1
else:
break
assert end >= 0
sign, before_point, after_point, exponent = break_up_float(s[beg:end+1])
if not before_point and not after_point:
raise ValueError
return parts_to_float(sign, before_point, after_point, exponent)
| Python |
"""
information table about external functions for annotation/rtyping and backends
"""
import os
import time
import types
from pypy.rlib.rarithmetic import r_longlong
class ExtFuncInfo:
def __init__(self, func, annotation, ll_function_path, ll_annotable, backend_functiontemplate):
self.func = func
self.ll_function_path = ll_function_path
self.annotation = annotation
self.ll_annotable = ll_annotable
self.backend_functiontemplate = backend_functiontemplate
def get_ll_function(self, type_system):
"""Get the ll_*() function implementing the given high-level 'func'."""
modulename, tail = self.ll_function_path.split('/')
if '.' not in modulename:
modulename = 'pypy.rpython.module.%s' % modulename
mod = self.import_module(modulename)
lastmodulename = modulename[modulename.rfind('.')+1:]
ll_function_name = '%s_%s' % (lastmodulename, tail)
try:
ll_function = getattr(mod, ll_function_name)
except AttributeError:
mod = self.import_module("pypy.rpython.%s.module.%s"
% (type_system.name, lastmodulename))
ll_function = getattr(mod.Implementation, ll_function_name)
return ll_function
def import_module(self, module_name):
ll_module = ImportMe(module_name)
return ll_module.load()
class ExtTypeInfo:
def __init__(self, typ, tag, methods,
needs_container=True, needs_gc=False):
self.typ = typ
self.tag = tag
self._TYPE = None
self.methods = methods # {'name': ExtFuncInfo()}
self.needs_container = needs_container
self.needs_gc = needs_gc
def get_annotation(self, methodname):
return self.methods[methodname].annotation
def get_annotations(self):
return dict([(name, self.get_annotation(name))
for name in self.methods])
def get_func_infos(self):
for extfuncinfo in self.methods.itervalues():
if extfuncinfo.func is not None:
yield (extfuncinfo.func, extfuncinfo)
def get_lltype(self):
if self._TYPE is None:
from pypy.rpython.lltypesystem import lltype
if self.needs_gc:
OPAQUE = lltype.GcOpaqueType(self.tag)
else:
OPAQUE = lltype.OpaqueType(self.tag)
OPAQUE._exttypeinfo = self
if self.needs_container:
STRUCT = lltype.GcStruct(self.tag, ('obj', OPAQUE))
self._TYPE = STRUCT
else:
self._TYPE = OPAQUE
return self._TYPE
def set_lltype(self, TYPE):
self._TYPE = TYPE
class ImportMe:
"Lazily imported module, for circular imports :-/"
def __init__(self, modulename):
self.modulename = modulename
self._mod = None
def load(self):
if self._mod is None:
self._mod = __import__(self.modulename, None, None, ['__doc__'])
return self._mod
table_callbacks = [] # to track declare() that occur after 'table' is read
table = {}
def declare(func, annotation, ll_function, ll_annotable=True, backend_functiontemplate=None):
# annotation can be a function computing the annotation
# or a simple python type from which an annotation will be constructed
global table
if not isinstance(annotation, types.FunctionType):
typ = annotation
def annotation(*args_s):
from pypy.annotation import bookkeeper
return bookkeeper.getbookkeeper().valueoftype(typ)
info = ExtFuncInfo(func, annotation, ll_function, ll_annotable, backend_functiontemplate)
if func is not None:
table[func] = info
for callback in table_callbacks:
callback()
return info
typetable = {}
def declaretype1(typ, tag, methodsdecl, needs_container, needs_gc=False):
assert isinstance(typ, type)
methods = {}
for name, args in methodsdecl.items():
# try to get the method object from the typ
for cls in typ.__mro__:
if name in typ.__dict__:
func = typ.__dict__[name]
break
else:
func = None # failed (typical for old-style C types), ignore it
methods[name] = declare(func, *args)
info = ExtTypeInfo(typ, tag, methods, needs_container, needs_gc)
typetable[typ] = info
for callback in table_callbacks:
callback()
return info
def declaretype(typ, tag, **methodsdecl):
return declaretype1(typ, tag, methodsdecl, needs_container=True)
def declareptrtype(typ, tag, **methodsdecl):
return declaretype1(typ, tag, methodsdecl, needs_container=False)
def declaregcptrtype(typ, tag, **methodsdecl):
return declaretype1(typ, tag, methodsdecl, needs_container=False,
needs_gc=True)
# _____________________________________________________________
def record_call(func, args_s, symbol):
from pypy.annotation import bookkeeper
bk = bookkeeper.getbookkeeper()
# this would be nice!
#bk.pbc_call(bk.immutablevalue(func),
# bk.build_args("simple_call", args_s),
# emulated=True)
bk.annotator.translator._implicitly_called_by_externals.append(
(func, args_s, symbol))
def noneannotation(*args):
return None
def posannotation(*args):
from pypy.annotation.model import SomeInteger
return SomeInteger(nonneg=True)
def statannotation(*args):
from pypy.rpython.lltypesystem.module.ll_os import Implementation
from pypy.annotation.model import SomeInteger, SomeTuple
record_call(Implementation.ll_stat_result, [SomeInteger()]*10, 'OS_STAT')
return SomeTuple((SomeInteger(),)*10)
def pipeannotation(*args):
from pypy.rpython.lltypesystem.module.ll_os import Implementation
from pypy.annotation.model import SomeInteger, SomeTuple
record_call(Implementation.ll_pipe_result, [SomeInteger()]*2, 'OS_PIPE')
return SomeTuple((SomeInteger(),)*2)
def waitpidannotation(*args):
from pypy.rpython.lltypesystem.module.ll_os import Implementation
from pypy.annotation.model import SomeInteger, SomeTuple
record_call(Implementation.ll_waitpid_result, [SomeInteger()]*2,
'OS_WAITPID')
return SomeTuple((SomeInteger(),)*2)
def strnullannotation(*args):
from pypy.annotation.model import SomeString
return SomeString(can_be_None=True)
# external function declarations
posix = __import__(os.name)
declare(os.read , str , 'll_os/read')
declare(os.write , posannotation , 'll_os/write')
declare(os.close , noneannotation, 'll_os/close')
declare(os.access , int , 'll_os/access')
declare(os.lseek , r_longlong , 'll_os/lseek')
declare(os.isatty , bool , 'll_os/isatty')
if hasattr(posix, 'ftruncate'):
declare(os.ftruncate, noneannotation, 'll_os/ftruncate')
declare(os.fstat , statannotation, 'll_os/fstat')
declare(os.stat , statannotation, 'll_os/stat')
declare(os.lstat , statannotation, 'll_os/lstat')
declare(os.system , int , 'll_os/system')
declare(os.strerror , str , 'll_os/strerror')
declare(os.unlink , noneannotation, 'll_os/unlink')
declare(os.getcwd , str , 'll_os/getcwd')
declare(os.chdir , noneannotation, 'll_os/chdir')
declare(os.mkdir , noneannotation, 'll_os/mkdir')
declare(os.rmdir , noneannotation, 'll_os/rmdir')
if hasattr(posix, 'unsetenv'): # note: faked in os
declare(os.unsetenv , noneannotation, 'll_os/unsetenv')
declare(os.pipe , pipeannotation, 'll_os/pipe')
declare(os.chmod , noneannotation, 'll_os/chmod')
declare(os.rename , noneannotation, 'll_os/rename')
declare(os.umask , int , 'll_os/umask')
declare(os._exit , noneannotation, 'll_os/_exit')
if hasattr(os, 'kill'):
declare(os.kill , noneannotation, 'll_os/kill')
if hasattr(os, 'getpid'):
declare(os.getpid , int, 'll_os/getpid')
if hasattr(os, 'link'):
declare(os.link , noneannotation, 'll_os/link')
if hasattr(os, 'symlink'):
declare(os.symlink , noneannotation, 'll_os/symlink')
if hasattr(os, 'readlink'):
declare(os.readlink , str, 'll_os/readlink')
if hasattr(os, 'fork'):
declare(os.fork , int, 'll_os/fork')
if hasattr(os, 'spawnv'):
declare(os.spawnv, int, 'll_os/spawnv')
if hasattr(os, 'waitpid'):
declare(os.waitpid , waitpidannotation, 'll_os/waitpid')
#if hasattr(os, 'execv'):
# declare(os.execv, noneannotation, 'll_os/execv')
# declare(os.execve, noneannotation, 'll_os/execve')
declare(os.path.exists, bool , 'll_os_path/exists')
declare(os.path.isdir, bool , 'll_os_path/isdir')
declare(time.time , float , 'll_time/time')
declare(time.clock , float , 'll_time/clock')
declare(time.sleep , noneannotation, 'll_time/sleep')
# ___________________________________________________________
# win/NT hack: patch ntpath.isabs() to be RPythonic
import ntpath
def isabs(s):
"""Test whether a path is absolute"""
s = ntpath.splitdrive(s)[1]
return s != '' and s[0] in '/\\'
ntpath.isabs = isabs
# ___________________________________________________________
# string->float helper
from pypy.rlib import rarithmetic
declare(rarithmetic.parts_to_float, float, 'll_strtod/parts_to_float')
# float->string helper
declare(rarithmetic.formatd, str, 'll_strtod/formatd')
# ___________________________________________________________
# special helpers for os with no equivalent
from pypy.rlib import ros
declare(ros.putenv, noneannotation, 'll_os/putenv')
declare(ros.environ, strnullannotation, 'll_os/environ')
declare(ros.opendir, ros.DIR, 'll_os/opendir')
declareptrtype(ros.DIR, "DIR",
readdir = (strnullannotation, 'll_os/readdir'),
closedir = (noneannotation, 'll_os/closedir'))
# ___________________________________________________________
# stackless
from pypy.rlib import rstack
declare(rstack.stack_frames_depth, int, 'll_stackless/stack_frames_depth')
declare(rstack.stack_too_big, bool, 'll_stack/too_big')
declare(rstack.stack_check, noneannotation, 'll_stack/check')
declare(rstack.stack_unwind, noneannotation, 'll_stack/unwind')
declare(rstack.stack_capture, rstack.frame_stack_top, 'll_stack/capture')
frametop_type_info = declaregcptrtype(rstack.frame_stack_top,'frame_stack_top',
switch = (rstack.frame_stack_top,
'll_stackless/switch'))
# ___________________________________________________________
# the exceptions that can be implicitely raised by some operations
standardexceptions = {
TypeError : True,
OverflowError : True,
ValueError : True,
ZeroDivisionError: True,
MemoryError : True,
IOError : True,
OSError : True,
StopIteration : True,
KeyError : True,
IndexError : True,
AssertionError : True,
RuntimeError : True,
}
| Python |
from pypy.annotation import model as annmodel
from pypy.rpython.rmodel import Repr
from pypy.rpython.rpbc import AbstractFunctionsPBCRepr,\
AbstractMethodsPBCRepr
from pypy.annotation.pairtype import pairtype
from pypy.rpython.lltypesystem import lltype
class AbstractGenericCallableRepr(Repr):
def __init__(self, rtyper, s_generic):
self.rtyper = rtyper
self.s_generic = s_generic
self.args_r = [self.rtyper.getrepr(arg) for arg in s_generic.args_s]
self.r_result = self.rtyper.getrepr(s_generic.s_result)
self.lowleveltype = self.create_low_leveltype()
def rtype_simple_call(self, hop):
return self.call('simple_call', hop)
def rtype_call_args(self, hop):
return self.call('call_args', hop)
def call(self, opname, hop):
bk = self.rtyper.annotator.bookkeeper
vlist = hop.inputargs(self, *self.args_r) + [hop.inputconst(lltype.Void, None)]
hop.exception_is_here()
v_result = hop.genop('indirect_call', vlist, resulttype=self.r_result)
return v_result
def convert_const(self, value):
bookkeeper = self.rtyper.annotator.bookkeeper
if value is None:
return self.rtyper.type_system.null_callable(self.lowleveltype)
r_func = self.rtyper.getrepr(bookkeeper.immutablevalue(value))
return r_func.get_unique_llfn().value
def _setup_repr(self):
for r in self.args_r:
r.setup()
self.r_result.setup()
class __extend__(annmodel.SomeGenericCallable):
def rtyper_makerepr(self, rtyper):
return rtyper.type_system.rgeneric.GenericCallableRepr(rtyper, self)
def rtyper_makekey(self):
return self.__class__, tuple([i.rtyper_makekey() for i in self.args_s]),\
self.s_result.rtyper_makekey(), tuple(self.descriptions.keys())
class __extend__(pairtype(AbstractFunctionsPBCRepr, AbstractGenericCallableRepr)):
def convert_from_to((pbcrepr, gencallrepr), v, llops):
if pbcrepr.lowleveltype is lltype.Void:
r = gencallrepr.convert_const(pbcrepr.s_pbc.const)
r.setup()
return r
if pbcrepr.lowleveltype == gencallrepr.lowleveltype:
return v
return NotImplemented
| Python |
# rtyping of memory address operations
from pypy.annotation.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.rpython.memory.lladdress import _address
from pypy.rpython.lltypesystem.llmemory import NULL, Address, \
cast_adr_to_int, WeakGcAddress
from pypy.rpython.rmodel import Repr, IntegerRepr
from pypy.rpython.rptr import PtrRepr
from pypy.rpython.lltypesystem import lltype
from pypy.rlib.rarithmetic import r_uint
class __extend__(annmodel.SomeAddress):
def rtyper_makerepr(self, rtyper):
return address_repr
def rtyper_makekey(self):
return self.__class__,
class __extend__(annmodel.SomeWeakGcAddress):
def rtyper_makerepr(self, rtyper):
return WeakGcAddressRepr(rtyper)
def rtyper_makekey(self):
return self.__class__,
class __extend__(annmodel.SomeTypedAddressAccess):
def rtyper_makerepr(self, rtyper):
return TypedAddressAccessRepr(self.type)
def rtyper_makekey(self):
return self.__class__, self.type
class AddressRepr(Repr):
lowleveltype = Address
def convert_const(self, value):
assert not isinstance(value, _address)
return value
def ll_str(self, a):
from pypy.rpython.lltypesystem.rstr import ll_str
id = cast_adr_to_int(a)
return ll_str.ll_int2hex(r_uint(id), True)
def rtype_getattr(self, hop):
v_access = hop.inputarg(address_repr, 0)
return v_access
def rtype_is_true(self, hop):
v_addr, = hop.inputargs(address_repr)
c_null = hop.inputconst(address_repr, NULL)
return hop.genop('adr_ne', [v_addr, c_null],
resulttype=lltype.Bool)
def get_ll_eq_function(self):
return None
def get_ll_hash_function(self):
return ll_addrhash
get_ll_fasthash_function = get_ll_hash_function
def ll_addrhash(addr1):
return cast_adr_to_int(addr1)
address_repr = AddressRepr()
class TypedAddressAccessRepr(Repr):
lowleveltype = Address
def __init__(self, typ):
self.type = typ
class __extend__(pairtype(TypedAddressAccessRepr, IntegerRepr)):
def rtype_getitem((r_acc, r_int), hop):
c_type = hop.inputconst(lltype.Void, r_acc.type)
v_addr, v_offs = hop.inputargs(hop.args_r[0], lltype.Signed)
return hop.genop('raw_load', [v_addr, c_type, v_offs],
resulttype = r_acc.type)
def rtype_setitem((r_acc, r_int), hop):
c_type = hop.inputconst(lltype.Void, r_acc.type)
v_addr, v_offs, v_value = hop.inputargs(hop.args_r[0], lltype.Signed, r_acc.type)
return hop.genop('raw_store', [v_addr, c_type, v_offs, v_value])
class __extend__(pairtype(AddressRepr, IntegerRepr)):
def rtype_add((r_addr, r_int), hop):
if r_int.lowleveltype == lltype.Signed:
v_addr, v_offs = hop.inputargs(Address, lltype.Signed)
return hop.genop('adr_add', [v_addr, v_offs], resulttype=Address)
return NotImplemented
rtype_inplace_add = rtype_add
def rtype_sub((r_addr, r_int), hop):
if r_int.lowleveltype == lltype.Signed:
v_addr, v_offs = hop.inputargs(Address, lltype.Signed)
return hop.genop('adr_sub', [v_addr, v_offs], resulttype=Address)
return NotImplemented
rtype_inplace_sub = rtype_sub
class __extend__(pairtype(AddressRepr, AddressRepr)):
def rtype_sub((r_addr1, r_addr2), hop):
v_addr1, v_addr2 = hop.inputargs(Address, Address)
return hop.genop('adr_delta', [v_addr1, v_addr2], resulttype=lltype.Signed)
def rtype_eq((r_addr1, r_addr2), hop):
v_addr1, v_addr2 = hop.inputargs(Address, Address)
return hop.genop('adr_eq', [v_addr1, v_addr2], resulttype=lltype.Bool)
def rtype_ne((r_addr1, r_addr2), hop):
v_addr1, v_addr2 = hop.inputargs(Address, Address)
return hop.genop('adr_ne', [v_addr1, v_addr2], resulttype=lltype.Bool)
def rtype_lt((r_addr1, r_addr2), hop):
v_addr1, v_addr2 = hop.inputargs(Address, Address)
return hop.genop('adr_lt', [v_addr1, v_addr2], resulttype=lltype.Bool)
def rtype_le((r_addr1, r_addr2), hop):
v_addr1, v_addr2 = hop.inputargs(Address, Address)
return hop.genop('adr_le', [v_addr1, v_addr2], resulttype=lltype.Bool)
def rtype_gt((r_addr1, r_addr2), hop):
v_addr1, v_addr2 = hop.inputargs(Address, Address)
return hop.genop('adr_gt', [v_addr1, v_addr2], resulttype=lltype.Bool)
def rtype_ge((r_addr1, r_addr2), hop):
v_addr1, v_addr2 = hop.inputargs(Address, Address)
return hop.genop('adr_ge', [v_addr1, v_addr2], resulttype=lltype.Bool)
# conversions
class __extend__(pairtype(PtrRepr, AddressRepr)):
def convert_from_to((r_ptr, r_addr), v, llops):
return llops.genop('cast_ptr_to_adr', [v], resulttype=Address)
class WeakGcAddressRepr(Repr):
lowleveltype = WeakGcAddress
def __init__(self, rtyper):
self.rtyper = rtyper
def convert_const(self, value):
from pypy.rpython.lltypesystem import llmemory
from pypy.rlib.objectmodel import cast_object_to_weakgcaddress
from pypy.objspace.flow.model import Constant
assert isinstance(value, llmemory.fakeweakaddress)
if value.ref is None:
return value
ob = value.ref()
assert ob is not None
bk = self.rtyper.annotator.bookkeeper
# obscure! if the annotator hasn't seen this object before,
# we don't want to look at it now (confusion tends to result).
if bk.have_seen(ob):
repr = self.rtyper.bindingrepr(Constant(ob))
newob = repr.convert_const(ob)
return cast_object_to_weakgcaddress(newob)
else:
return llmemory.fakeweakaddress(None)
| Python |
# generic
def simple1():
return 1
def simple2():
return False
def not1(n):
return not n
def not2(n):
t = not n
if not n:
t += 1
return t
# bools
def bool1(n):
if n:
return 3
return 5
def bool_cast1(n):
n += bool(False)
n += bool(True)
n += bool(0)
n += bool(1)
n += bool(6)
n += bool(7.8)
n += bool(n)
return n
#ints
def int1(n):
i = 0
i += n<<3
i <<= 3
i += n>>3
i >>= 3
i += n%3
i %= n
i += n^3
i ^= n
i += n&3
i &= n
i += n^3
i ^= n
i += n|3
i |= n
i += ~n
n += False
n += True
n += bool(False)
n += bool(True)
i += abs(i)
i &= 255
#i **= n
#i += n**3
i += -n
i += +n
i += not n
if n < 12.5:
n += 666
while n:
i = i + n
n = n - 1
return i
def int_cast1(n):
n += int(False)
n += int(True)
n += int(0)
n += int(1)
n += int(8)
n += int(5.7)
n += int(n)
return n
# floats
def float1(n):
i = 0
n += False
n += True
n += bool(False)
n += bool(True)
i += abs(i)
i &= 255
i **= n
i += n**3
i += -n
i += +n
i += not n
if n < 12.5:
n += 666
while n >= 0:
i = i + n
n = n - 1
return i
def float_cast1(n):
n += float(False)
n += float(True)
n += float(0)
n += float(1)
n += float(6)
n += float(7.8)
n += float(n)
return n
def main(args=[]):
b = True
i = 23
f = 45.6
b1 = bool1(b)
i1 = int1(i)
f1 = float1(f)
return 0
if __name__ == '__main__':
main()
| Python |
#
| Python |
import py
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.lltypesystem import lltype
from pypy.rpython.test.test_llinterp import gengraph, interpret, interpret_raises
class BaseRtypingTest(object):
def gengraph(self, func, argtypes=[], viewbefore='auto', policy=None,
backendopt=False, config=None):
return gengraph(func, argtypes, viewbefore, policy, type_system=self.type_system,
backendopt=backendopt, config=config)
def interpret(self, fn, args, **kwds):
return interpret(fn, args, type_system=self.type_system, **kwds)
def interpret_raises(self, exc, fn, args, **kwds):
return interpret_raises(exc, fn, args, type_system=self.type_system, **kwds)
def float_eq(self, x, y):
return x == y
def is_of_type(self, x, type_):
return type(x) is type_
def _skip_oo(self, reason):
if self.type_system == 'ootype':
py.test.skip("ootypesystem doesn't support %s, yet" % reason)
class LLRtypeMixin(object):
type_system = 'lltype'
def ll_to_string(self, s):
return ''.join(s.chars)
def string_to_ll(self, s):
from pypy.rpython.module.support import LLSupport
return LLSupport.to_rstr(s)
def ll_to_list(self, l):
r = []
items = l.ll_items()
for i in range(l.ll_length()):
r.append(items[i])
return r
def ll_unpack_tuple(self, t, length):
return tuple([getattr(t, 'item%d' % i) for i in range(length)])
def get_callable(self, fnptr):
return fnptr._obj._callable
def class_name(self, value):
return "".join(value.super.typeptr.name)[:-1]
def read_attr(self, value, attr_name):
value = value._obj
while value is not None:
attr = getattr(value, "inst_" + attr_name, None)
if attr is None:
value = value._parentstructure()
else:
return attr
raise AttributeError()
def is_of_instance_type(self, val):
T = lltype.typeOf(val)
return isinstance(T, lltype.Ptr) and isinstance(T.TO, lltype.GcStruct)
class OORtypeMixin(object):
type_system = 'ootype'
def ll_to_string(self, s):
return s._str
def string_to_ll(self, s):
from pypy.rpython.module.support import OOSupport
return OOSupport.to_rstr(s)
def ll_to_list(self, l):
return l._list[:]
def ll_unpack_tuple(self, t, length):
return tuple([getattr(t, 'item%d' % i) for i in range(length)])
def get_callable(self, sm):
return sm._callable
def class_name(self, value):
return ootype.dynamicType(value)._name.split(".")[-1]
def read_attr(self, value, attr):
value = ootype.oodowncast(ootype.dynamicType(value), value)
return getattr(value, "o" + attr)
def is_of_instance_type(self, val):
T = lltype.typeOf(val)
return isinstance(T, ootype.Instance)
| Python |
import py, sys, os
from py.__.test.outcome import Failed
from pypy.interpreter.gateway import app2interp_temp
from pypy.interpreter.error import OperationError
from pypy.tool.pytest import appsupport
from pypy.tool.option import make_config, make_objspace
from inspect import isclass, getmro
from pypy.tool.udir import udir
from pypy.tool.autopath import pypydir
rootdir = py.magic.autopath().dirpath()
# distributed testing settings
dist_rsync_roots = ['.', '../lib-python', '../py', '../demo']
dist_rsync_ignore = ['_cache']
#
# PyPy's command line extra options (these are added
# to py.test's standard options)
#
Option = py.test.config.Option
option = py.test.config.addoptions("pypy options",
Option('--view', action="store_true", dest="view", default=False,
help="view translation tests' flow graphs with Pygame"),
Option('-A', '--runappdirect', action="store_true",
default=False, dest="runappdirect",
help="run applevel tests directly on python interpreter (not through PyPy)"),
Option('--direct', action="store_true",
default=False, dest="rundirect",
help="run pexpect tests directly")
)
_SPACECACHE={}
def gettestobjspace(name=None, **kwds):
""" helper for instantiating and caching space's for testing.
"""
config = make_config(option, objspace=name, **kwds)
key = config.getkey()
try:
return _SPACECACHE[key]
except KeyError:
if option.runappdirect:
if name not in (None, 'std'):
myname = getattr(sys, 'pypy_objspaceclass', '')
if not myname.lower().startswith(name):
py.test.skip("cannot runappdirect test: "
"%s objspace required" % (name,))
return TinyObjSpace(**kwds)
space = maketestobjspace(config)
_SPACECACHE[key] = space
return space
def maketestobjspace(config=None):
if config is None:
config = make_config(option)
try:
space = make_objspace(config)
except OperationError, e:
check_keyboard_interrupt(e)
if option.verbose:
import traceback
traceback.print_exc()
py.test.fail("fatal: cannot initialize objspace: %r" %
(config.objspace.name,))
space.startup() # Initialize all builtin modules
space.setitem(space.builtin.w_dict, space.wrap('AssertionError'),
appsupport.build_pytest_assertion(space))
space.setitem(space.builtin.w_dict, space.wrap('raises'),
space.wrap(appsupport.app_raises))
space.setitem(space.builtin.w_dict, space.wrap('skip'),
space.wrap(appsupport.app_skip))
space.raises_w = appsupport.raises_w.__get__(space)
space.eq_w = appsupport.eq_w.__get__(space)
return space
class TinyObjSpace(object):
def __init__(self, **kwds):
import sys
info = getattr(sys, 'pypy_translation_info', None)
for key, value in kwds.iteritems():
if key == 'usemodules':
if info is not None:
for modname in value:
ok = info.get('objspace.usemodules.%s' % modname,
False)
if not ok:
py.test.skip("cannot runappdirect test: "
"module %r required" % (modname,))
continue
if info is None:
py.test.skip("cannot runappdirect this test on top of CPython")
has = info.get(key, None)
if has != value:
#print sys.pypy_translation_info
py.test.skip("cannot runappdirect test: space needs %s = %s, "\
"while pypy-c was built with %s" % (key, value, has))
def appexec(self, args, body):
body = body.lstrip()
assert body.startswith('(')
src = py.code.Source("def anonymous" + body)
d = {}
exec src.compile() in d
return d['anonymous'](*args)
def wrap(self, obj):
return obj
def unpackiterable(self, itr):
return list(itr)
def is_true(self, obj):
return bool(obj)
def newdict(self):
return {}
def newtuple(self, iterable):
return tuple(iterable)
def newlist(self, iterable):
return list(iterable)
def call_function(self, func, *args, **kwds):
return func(*args, **kwds)
def translation_test_so_skip_if_appdirect():
if option.runappdirect:
py.test.skip("translation test, skipped for appdirect")
class OpErrKeyboardInterrupt(KeyboardInterrupt):
pass
def check_keyboard_interrupt(e):
# we cannot easily convert w_KeyboardInterrupt to KeyboardInterrupt
# in general without a space -- here is an approximation
try:
if e.w_type.name == 'KeyboardInterrupt':
tb = sys.exc_info()[2]
raise OpErrKeyboardInterrupt, OpErrKeyboardInterrupt(), tb
except AttributeError:
pass
#
# Interfacing/Integrating with py.test's collection process
#
#
def ensure_pytest_builtin_helpers(helpers='skip raises'.split()):
""" hack (py.test.) raises and skip into builtins, needed
for applevel tests to run directly on cpython but
apparently earlier on "raises" was already added
to module's globals.
"""
import __builtin__
for helper in helpers:
if not hasattr(__builtin__, helper):
setattr(__builtin__, helper, getattr(py.test, helper))
class Module(py.test.collect.Module):
""" we take care of collecting classes both at app level
and at interp-level (because we need to stick a space
at the class) ourselves.
"""
def __init__(self, *args, **kwargs):
if hasattr(sys, 'pypy_objspaceclass'):
option.conf_iocapture = "sys" # pypy cannot do FD-based
super(Module, self).__init__(*args, **kwargs)
def accept_regular_test(self):
if option.runappdirect:
# only collect regular tests if we are in an 'app_test' directory
return "app_test" in self.listnames()
else:
return True
def funcnamefilter(self, name):
if name.startswith('test_'):
return self.accept_regular_test()
if name.startswith('app_test_'):
return True
return False
def classnamefilter(self, name):
if name.startswith('Test'):
return self.accept_regular_test()
if name.startswith('AppTest'):
return True
if name.startswith('ExpectTest'):
return True
#XXX todo
#if name.startswith('AppExpectTest'):
# return True
return False
def setup(self):
# stick py.test raise in module globals -- carefully
ensure_pytest_builtin_helpers()
super(Module, self).setup()
# if hasattr(mod, 'objspacename'):
# mod.space = getttestobjspace(mod.objspacename)
def join(self, name):
obj = getattr(self.obj, name)
if isclass(obj):
if name.startswith('AppTest'):
return AppClassCollector(name, parent=self)
elif name.startswith('ExpectTest'):
if option.rundirect:
return py.test.collect.Class(name, parent=self)
return ExpectClassCollector(name, parent=self)
# XXX todo
#elif name.startswith('AppExpectTest'):
# if option.rundirect:
# return AppClassCollector(name, parent=self)
# return AppExpectClassCollector(name, parent=self)
else:
return IntClassCollector(name, parent=self)
elif hasattr(obj, 'func_code'):
if name.startswith('app_test_'):
assert not obj.func_code.co_flags & 32, \
"generator app level functions? you must be joking"
return AppTestFunction(name, parent=self)
elif obj.func_code.co_flags & 32: # generator function
return self.Generator(name, parent=self)
else:
return IntTestFunction(name, parent=self)
def skip_on_missing_buildoption(**ropts):
__tracebackhide__ = True
import sys
options = getattr(sys, 'pypy_translation_info', None)
if options is None:
py.test.skip("not running on translated pypy "
"(btw, i would need options: %s)" %
(ropts,))
for opt in ropts:
if not options.has_key(opt) or options[opt] != ropts[opt]:
break
else:
return
py.test.skip("need translated pypy with: %s, got %s"
%(ropts,options))
def getwithoutbinding(x, name):
try:
return x.__dict__[name]
except (AttributeError, KeyError):
for cls in getmro(x.__class__):
if name in cls.__dict__:
return cls.__dict__[name]
# uh? not found anywhere, fall back (which might raise AttributeError)
return getattr(x, name)
class LazyObjSpaceGetter(object):
def __get__(self, obj, cls=None):
space = gettestobjspace()
if cls:
cls.space = space
return space
class PyPyTestFunction(py.test.collect.Function):
# All PyPy test items catch and display OperationErrors specially.
#
def execute_appex(self, space, target, *args):
try:
target(*args)
except OperationError, e:
if e.match(space, space.w_KeyboardInterrupt):
tb = sys.exc_info()[2]
raise OpErrKeyboardInterrupt, OpErrKeyboardInterrupt(), tb
appexcinfo = appsupport.AppExceptionInfo(space, e)
if appexcinfo.traceback:
raise Failed(excinfo=appsupport.AppExceptionInfo(space, e))
raise
_pygame_imported = False
class IntTestFunction(PyPyTestFunction):
def _haskeyword(self, keyword):
if keyword == 'interplevel':
return True
return super(IntTestFunction, self)._haskeyword(keyword)
def execute(self, target, *args):
co = target.func_code
try:
if 'space' in co.co_varnames[:co.co_argcount]:
space = gettestobjspace()
target(space, *args)
else:
target(*args)
except OperationError, e:
check_keyboard_interrupt(e)
raise
except Exception, e:
cls = e.__class__
while cls is not Exception:
if cls.__name__ == 'DistutilsPlatformError':
from distutils.errors import DistutilsPlatformError
if isinstance(e, DistutilsPlatformError):
py.test.skip('%s: %s' % (e.__class__.__name__, e))
cls = cls.__bases__[0]
raise
if 'pygame' in sys.modules:
global _pygame_imported
if not _pygame_imported:
_pygame_imported = True
assert option.view, ("should not invoke Pygame "
"if conftest.option.view is False")
class AppTestFunction(PyPyTestFunction):
def _haskeyword(self, keyword):
return keyword == 'applevel' or super(AppTestFunction, self)._haskeyword(keyword)
def execute(self, target, *args):
assert not args
if option.runappdirect:
return target(*args)
space = gettestobjspace()
func = app2interp_temp(target)
print "executing", func
self.execute_appex(space, func, space)
class AppTestMethod(AppTestFunction):
def setup(self):
super(AppTestMethod, self).setup()
instance = self.parent.obj
w_instance = self.parent.w_instance
space = instance.space
for name in dir(instance):
if name.startswith('w_'):
if option.runappdirect:
# if the value is a function living on the class,
# don't turn it into a bound method here
obj = getwithoutbinding(instance, name)
setattr(w_instance, name[2:], obj)
else:
space.setattr(w_instance, space.wrap(name[2:]),
getattr(instance, name))
def execute(self, target, *args):
assert not args
if option.runappdirect:
return target(*args)
space = target.im_self.space
func = app2interp_temp(target.im_func)
w_instance = self.parent.w_instance
self.execute_appex(space, func, space, w_instance)
class PyPyClassCollector(py.test.collect.Class):
def setup(self):
cls = self.obj
cls.space = LazyObjSpaceGetter()
super(PyPyClassCollector, self).setup()
class IntClassCollector(PyPyClassCollector):
Function = IntTestFunction
def _haskeyword(self, keyword):
return keyword == 'interplevel' or \
super(IntClassCollector, self)._haskeyword(keyword)
class AppClassInstance(py.test.collect.Instance):
Function = AppTestMethod
def setup(self):
super(AppClassInstance, self).setup()
instance = self.obj
space = instance.space
w_class = self.parent.w_class
if option.runappdirect:
self.w_instance = instance
else:
self.w_instance = space.call_function(w_class)
class AppClassCollector(PyPyClassCollector):
Instance = AppClassInstance
def _haskeyword(self, keyword):
return keyword == 'applevel' or \
super(AppClassCollector, self)._haskeyword(keyword)
def setup(self):
super(AppClassCollector, self).setup()
cls = self.obj
space = cls.space
clsname = cls.__name__
if option.runappdirect:
w_class = cls
else:
w_class = space.call_function(space.w_type,
space.wrap(clsname),
space.newtuple([]),
space.newdict())
self.w_class = w_class
class ExpectTestMethod(py.test.collect.Function):
def safe_name(target):
s = "_".join(target)
s = s.replace("()", "paren")
s = s.replace(".py", "")
s = s.replace(".", "_")
return s
safe_name = staticmethod(safe_name)
def safe_filename(self):
name = self.safe_name(self.listnames())
num = 0
while udir.join(name + '.py').check():
num += 1
name = self.safe_name(self.listnames()) + "_" + str(num)
return name + '.py'
def _spawn(self, *args, **kwds):
import pexpect
child = pexpect.spawn(*args, **kwds)
child.logfile = sys.stdout
return child
def spawn(self, argv):
return self._spawn(sys.executable, argv)
def execute(self, target, *args):
assert not args
import pexpect
source = py.code.Source(target)[1:].deindent()
filename = self.safe_filename()
source.lines = ['import sys',
'sys.path.insert(0, %s)' % repr(os.path.dirname(pypydir))
] + source.lines
source.lines.append('print "%s ok!"' % filename)
f = udir.join(filename)
f.write(source)
# run target in the guarded environment
child = self.spawn([str(f)])
import re
child.expect(re.escape(filename + " ok!"))
class ExpectClassInstance(py.test.collect.Instance):
Function = ExpectTestMethod
class ExpectClassCollector(py.test.collect.Class):
Instance = ExpectClassInstance
def setup(self):
super(ExpectClassCollector, self).setup()
try:
import pexpect
except ImportError:
py.test.skip("pexpect not found")
| Python |
import os
import py
from pypy.tool.udir import udir
from pypy.translator.translator import TranslationContext
from pypy.translator.lisp.gencl import GenCL
from pypy.translator.lisp.clrepr import clrepr
from pypy import conftest
from pypy.translator.lisp import conftest as clconftest
global_cl = None
def is_on_path(name):
if py.path.local.sysfind(name) is None:
return False
else:
return True
def cl_detect():
cl = os.getenv("PYPY_CL")
if cl:
return cl
if is_on_path("openmcl"):
if is_on_path("openmclinvoke.sh"):
return "openmclinvoke.sh"
if is_on_path("clisp"):
return "clisp"
if is_on_path("lisp"):
if is_on_path("cmuclinvoke.sh"):
return "cmuclinvoke.sh"
if is_on_path("sbcl"):
if is_on_path("sbclinvoke.sh"):
return "sbclinvoke.sh"
return None
def readlisp(s):
# Return bool/char/str/int/float or give up
lines = s.splitlines()
lines = [ line for line in lines if line and not line.startswith(';') ]
assert len(lines) == 1
s = lines[0]
s = s.strip()
if s == "T":
return True
elif s == "NIL":
return False
elif s.startswith("#\\"):
return s[2:]
elif s[0] == '"':
return s[1:-1]
elif s.isdigit():
return int(s)
try:
return float(s)
except ValueError:
pass
raise NotImplementedError("cannot read %s" % (s,))
def make_cl_func(func, argtypes=[]):
global global_cl
if global_cl is None:
global_cl = cl_detect()
if not global_cl:
py.test.skip("Common Lisp neither configured nor detected.")
return _make_cl_func(func, global_cl, udir, argtypes)
pretty_printer = """
(let* ((filename "%s")
(content (with-open-file (f filename)
(loop for sexp = (read f nil) while sexp collect sexp))))
(with-open-file (out filename
:direction :output :if-does-not-exist :create :if-exists :supersede)
(loop for sexp in content do (pprint sexp out))))
"""
def _make_cl_func(func, cl, path, argtypes=[]):
gen = build_generator(func, argtypes)
fname = gen.entry_name
fpath = gen.emitfile()
if clconftest.option.prettyprint:
printer = path.join(".printer.lisp")
code = pretty_printer % (fpath,)
printer.write(code)
py.process.cmdexec("%s %s" % (cl, printer))
def wrapper(*args):
loader = path.join(".loader.lisp")
fp = loader.open("w")
fp.write('(load "%s")\n' % (fpath,))
if args:
args = " ".join(map(clrepr, args))
fp.write("(write (%s %s))\n" % (fname, args))
else:
fp.write("(write (%s))\n" % (fname,))
fp.close()
output = py.process.cmdexec("%s %s" % (cl, loader))
return readlisp(output)
return wrapper
def generate_cl_code(func, argtypes=[]):
gen = build_generator(func, argtypes)
code = gen.emitcode()
return code
def build_generator(func, argtypes=[]):
context = TranslationContext()
context.buildannotator().build_types(func, argtypes)
context.buildrtyper(type_system="ootype").specialize()
if conftest.option.view:
context.view()
gen = GenCL(context, func)
return gen
| Python |
import types
from pypy.tool.udir import udir
from pypy.objspace.flow.model import Constant, c_last_exception, FunctionGraph
from pypy.translator.translator import graphof
from pypy.rpython.ootypesystem.ootype import dynamicType, oodowncast, null, Record, Instance, _class, _static_meth, _meth, ROOT
from pypy.rpython.ootypesystem.rclass import OBJECT
from pypy.translator.lisp.clrepr import clrepr
from pypy.translator.lisp.opformatter import OpFormatter
class InsertionOrderedDict(dict):
def __init__(self):
super(InsertionOrderedDict, self).__init__()
self.ordered_keys = []
def __setitem__(self, key, val):
super(InsertionOrderedDict, self).__setitem__(key, val)
if key not in self.ordered_keys:
self.ordered_keys.append(key)
def values(self):
return [self[key] for key in self.ordered_keys]
class GenCL:
def __init__(self, context, funobj):
self.context = context
self.entry_point = funobj
self.entry_name = clrepr(funobj.func_name, symbol=True)
self.pendinggraphs = [funobj]
self.declarations = InsertionOrderedDict()
self.constcount = 0
self.structcount = 0
def is_exception_instance(self, INST):
exceptiondata = self.context.rtyper.exceptiondata
return exceptiondata.is_exception_instance(INST)
def check_declaration(self, arg):
if isinstance(arg, Constant):
if isinstance(arg.concretetype, (Record, Instance)):
if arg.value is null(arg.concretetype):
return "nil"
if isinstance(arg.concretetype, Instance):
return self.declare_constant_instance(arg)
return clrepr(arg)
def declare_any(self, cls):
if isinstance(cls, Record):
return self.declare_struct(cls)
if isinstance(cls, Instance):
if self.is_exception_instance(cls):
return self.declare_exception(cls)
else:
return self.declare_class(cls)
raise NotImplementedError("cannot declare %s" % (cls,))
def declare_struct(self, cls):
assert isinstance(cls, Record)
if cls in self.declarations:
return self.declarations[cls][0]
name = "struct" + str(self.structcount)
field_declaration = cls._fields.keys()
field_declaration = " ".join(field_declaration)
struct_declaration = "(defstruct %s %s)" % (name, field_declaration)
self.declarations[cls] = (name, struct_declaration)
self.structcount += 1
return name
def declare_dict_iter(self):
name = 'pypy-dict-iter'
if name in self.declarations:
return self.declarations[name][0]
definition = """\
(defun %s (hash)
(let ((current-index -1)
(keys (loop for keys being the hash-keys in hash collect keys)))
(list (lambda ()
(let ((more (<= (incf current-index) (1- (length keys)))))
(if more
(let* ((key (nth current-index keys))
(val (gethash key hash)))
(values more key val))
(values nil nil nil))))
(lambda ()
(nth current-index keys))
(lambda ()
(gethash (nth current-index keys) hash)))))""" % (name)
self.declarations[name] = (name, definition)
return name
def declare_class(self, cls):
assert isinstance(cls, Instance)
assert not self.is_exception_instance(cls)
if cls in self.declarations:
return self.declarations[cls][0]
name = clrepr(cls._name, symbol=True)
field_declaration = []
for field in cls._fields:
field = clrepr(field, True)
field_declaration.append('('+field+' :accessor '+field+')')
field_declaration = " ".join(field_declaration)
if cls._superclass is ROOT:
class_declaration = "(defclass %s () (%s))" % (name, field_declaration)
else:
self.declare_class(cls._superclass)
supername = clrepr(cls._superclass._name, symbol=True)
class_declaration = "(defclass %s (%s) (%s))" % (name, supername, field_declaration)
self.declarations[cls] = (name, class_declaration)
for method in cls._methods:
methodobj = cls._methods[method]
methodobj._method_name = method
self.pendinggraphs.append(methodobj)
return name
def declare_exception(self, cls):
assert isinstance(cls, Instance)
assert self.is_exception_instance(cls)
if cls in self.declarations:
return self.declarations[cls][0]
name = clrepr(cls._name, symbol=True)
if cls._superclass is OBJECT:
exception_declaration = "(define-condition %s () ((meta :accessor meta)))" % (name)
else:
supername = self.declare_exception(cls._superclass)
exception_declaration = "(define-condition %s (%s) ())" % (name, supername)
self.declarations[cls] = (name, exception_declaration)
return name
def declare_constant_instance(self, const):
# const.concretetype is Instance
if const in self.declarations:
return self.declarations[const][0]
name = "+const" + str(self.constcount) + "+"
INST = dynamicType(const.value)
self.declare_class(INST)
inst = oodowncast(INST, const.value)
cls = clrepr(INST)
const_declaration = []
const_declaration.append("(defvar %s nil)" % clrepr(name, True))
const_declaration.append("(setf %s (make-instance %s))" % (clrepr(name, True),
clrepr(cls, True)))
fields = INST._allfields()
for fieldname in fields:
fieldvalue = getattr(inst, fieldname)
if isinstance(fieldvalue, _class):
self.declare_any(fieldvalue._INSTANCE)
fieldvaluerepr = clrepr(getattr(inst, fieldname))
### XXX
const_declaration.append("(setf (slot-value %s '%s) %s)" % (clrepr(name, True),
clrepr(fieldname, True),
clrepr(fieldvaluerepr, True)))
const_declaration = "\n".join(const_declaration)
self.declarations[const] = (name, const_declaration)
self.constcount += 1
return name
def emitfile(self):
name = self.entry_name
path = udir.join("%s.lisp" % (name,))
code = self.emitcode()
path.write(code)
return str(path)
def emitcode(self):
lines = list(self.emit())
declarations = "\n".join([d[1] for d in self.declarations.values()])
code = "\n".join(lines)
if declarations:
return declarations + "\n" + code + "\n"
else:
return code + "\n"
def emit(self):
while self.pendinggraphs:
obj = self.pendinggraphs.pop()
if isinstance(obj, types.FunctionType):
graph = graphof(self.context, obj)
for line in self.emit_defun(graph):
yield line
elif isinstance(obj, _static_meth):
graph = obj.graph
for line in self.emit_defun(graph):
yield line
elif isinstance(obj, _meth):
graph = obj.graph
name = obj._method_name # XXX
for line in self.emit_defmethod(graph, name):
yield line
elif isinstance(obj, FunctionGraph):
graph = obj
for line in self.emit_defun(graph):
yield line
def emit_defun(self, fun):
yield "(defun " + clrepr(fun.name, symbol=True)
arglist = fun.getargs()
args = " ".join(map(lambda item: clrepr(item, True), arglist))
yield "(%s)" % (args,)
for line in self.emit_body(fun, arglist):
yield line
def emit_defmethod(self, fun, name):
yield "(defmethod %s" % (clrepr(name, symbol=True))
arglist = fun.getargs()
selfvar = clrepr(arglist[0], True)
clsname = clrepr(arglist[0].concretetype._name, symbol=True)
args = " ".join(map(lambda item: clrepr(item, True), arglist[1:]))
if args:
yield "((%s %s) %s)" % (clrepr(selfvar, True),
clrepr(clsname, True),
clrepr(args, True))
else:
yield "((%s %s))" % (clrepr(selfvar, True),
clrepr(clsname, True))
for line in self.emit_body(fun, arglist):
yield line
def emit_body(self, fun, arglist):
yield "(prog"
blocklist = list(fun.iterblocks())
vardict = {}
self.blockref = {}
for block in blocklist:
tag = len(self.blockref)
self.blockref[block] = tag
for var in block.getvariables():
# In the future, we could assign type information here
vardict[var] = None
varnames = []
for var in vardict:
varname = clrepr(var)
if var in arglist:
varnames.append("(%s %s)" % (clrepr(varname, True),
clrepr(varname, True)))
else:
varnames.append(clrepr(varname, True))
varnames = " ".join(varnames)
yield "(%s)" % (varnames,)
for block in blocklist:
for line in self.emit_block(block):
yield line
yield "))"
def emit_block(self, block):
tag = self.blockref[block]
yield "tag" + clrepr(str(tag), True)
handle_exc = block.exitswitch == c_last_exception
if handle_exc:
yield "(handler-case (progn"
for op in block.operations:
emit_op = OpFormatter(self, op)
for line in emit_op:
yield line
exits = block.exits
if len(exits) == 0:
if len(block.inputargs) == 2:
exc_value = clrepr(block.inputargs[1])
yield "(error %s)" % (exc_value,)
else:
retval = clrepr(block.inputargs[0])
yield "(return %s)" % (retval,)
elif len(exits) == 1:
for line in self.emit_link(exits[0]):
yield line
elif handle_exc:
body = None
exceptions = {}
for exit in exits:
if exit.exitcase is None:
body = exit
else:
cls = exit.llexitcase.class_._INSTANCE
exception = self.declare_exception(cls)
exceptions[exception] = exit
for line in self.emit_link(body):
yield line
yield ")" # closes the progn for the handler-case
for exception in exceptions:
yield "(%s ()" % (exception,)
for line in self.emit_link(exceptions[exception]):
yield line
yield ")"
elif len(exits) == 2:
assert exits[0].exitcase == False
assert exits[1].exitcase == True
yield "(if %s" % (clrepr(block.exitswitch),)
yield "(progn"
for line in self.emit_link(exits[1]):
yield line
yield ") ; else"
yield "(progn"
for line in self.emit_link(exits[0]):
yield line
yield "))"
else:
yield "(case %s" % (clrepr(block.exitswitch),)
for exit in exits:
yield "(%s" % (clrepr(exit.exitcase),)
for line in self.emit_link(exit):
yield line
yield ")"
yield ")"
if handle_exc:
yield ")"
def format_jump(self, block):
tag = self.blockref[block]
return "(go tag" + clrepr(str(tag), True) + ")"
def emit_link(self, link):
source = map(self.check_declaration, link.args)
target = map(clrepr, link.target.inputargs)
couples = ["%s %s" % (t, s) for (s, t) in zip(source, target)]
if couples:
couples = " ".join(couples)
yield "(setf %s)" % (couples,)
yield self.format_jump(link.target)
| Python |
import py
Option = py.test.config.Option
option = py.test.config.addoptions('pypy-cl options',
Option('--prettyprint', action='store_true', dest='prettyprint',
default=False, help='pretty-print Common Lisp source'))
| Python |
from pypy.rpython.ootypesystem.ootype import List, Dict, Record, Instance
from pypy.rpython.ootypesystem.ootype import DictItemsIterator
from pypy.translator.lisp.clrepr import clrepr
class OpFormatter:
def __init__(self, gen, op):
self.gen = gen
self.op = op
self.opname = op.opname
self.args = op.args
self.result = op.result
def __iter__(self):
method = getattr(self, "op_" + self.opname)
result = clrepr(self.result)
args = map(self.gen.check_declaration, self.args)
for line in method(result, *args):
yield line
def nop(self, result, arg):
yield "(setf %s %s)" % (result, arg)
def op_debug_assert(self, result, *args):
return []
op_same_as = nop
op_ooupcast = nop
op_oodowncast = nop
def make_unary_op(cl_op):
def unary_op(self, result, arg):
yield "(setf %s (%s %s))" % (result, cl_op, arg)
return unary_op
op_bool_not = make_unary_op("not")
op_cast_char_to_int = make_unary_op("char-code")
op_cast_int_to_char = make_unary_op("code-char")
op_cast_float_to_int = make_unary_op("truncate")
op_cast_int_to_float = make_unary_op("float")
op_int_neg = make_unary_op("not")
def make_binary_op(cl_op):
def binary_op(self, result, arg1, arg2):
yield "(setf %s (%s %s %s))" % (result, cl_op, arg1, arg2)
return binary_op
op_int_add = make_binary_op("+")
op_int_sub = make_binary_op("-")
op_int_mul = make_binary_op("*")
op_int_floordiv = make_binary_op("truncate")
op_int_eq = make_binary_op("=")
op_int_gt = make_binary_op(">")
op_int_ge = make_binary_op(">=")
op_int_ne = make_binary_op("/=")
op_int_lt = make_binary_op("<")
op_int_le = make_binary_op("<=")
op_int_and = make_binary_op("logand")
op_int_mod = make_binary_op("mod")
op_float_sub = make_binary_op("-")
op_float_truediv = make_binary_op("/")
op_char_eq = make_binary_op("char=")
op_char_le = make_binary_op("char<=")
op_char_ne = make_binary_op("char/=")
def op_int_is_true(self, result, arg):
yield "(setf %s (not (zerop %s)))" % (clrepr(result, True),
clrepr(arg, True))
def op_direct_call(self, result, _, *args):
funobj = self.args[0].value
self.gen.pendinggraphs.append(funobj)
fun = clrepr(funobj._name, symbol=True)
funcall = " ".join((fun,) + args)
yield "(setf %s (%s))" % (result, funcall)
def op_indirect_call(self, result, fun, *args):
graphs = self.args[-1].value
self.gen.pendinggraphs.extend(graphs)
args = args[:-1]
funcall = " ".join((fun,) + args)
yield "(setf %s (funcall %s))" % (result, funcall)
def op_new(self, result, _):
cls = self.args[0].value
if isinstance(cls, List):
yield "(setf %s (make-array 0 :adjustable t))" % (result,)
elif isinstance(cls, Dict):
yield "(setf %s (make-hash-table))" % (result,)
elif isinstance(cls, Record):
clsname = self.gen.declare_struct(cls)
yield "(setf %s (make-%s))" % (result, clsname)
elif isinstance(cls, Instance):
if self.gen.is_exception_instance(cls):
clsname = self.gen.declare_exception(cls)
yield "(setf %s (make-condition '%s))" % (result, clsname)
else:
clsname = self.gen.declare_class(cls)
yield "(setf %s (make-instance '%s))" % (result, clsname)
else:
raise NotImplementedError("op_new on %s" % (cls,))
def op_runtimenew(self, result, arg):
yield "(setf %s (make-instance %s))" % (clrepr(result, True),
clrepr(arg, True))
def op_instanceof(self, result, arg, clsname):
clsname = clrepr(self.args[1].value)
yield "(setf %s (typep %s %s))" % (clrepr(result, True),
clrepr(arg, True),
clrepr(clsname, True))
def op_oosend(self, result, _, selfvar, *args):
method = self.args[0].value
cls = self.args[1].concretetype
if isinstance(cls, List):
impl = ListImpl(selfvar)
code = getattr(impl, method)(*args)
yield "(setf %s %s)" % (result, code)
elif isinstance(cls, Dict):
impl = DictImpl(selfvar, self.gen)
code = getattr(impl, method)(*args)
yield "(setf %s %s)" % (result, code)
elif isinstance(cls, DictItemsIterator):
impl = DictItemsIteratorImpl(selfvar)
code = getattr(impl, method)(*args)
yield "(setf %s %s)" % (result, code)
elif isinstance(cls, Instance):
name = clrepr(method, symbol=True)
funcall = " ".join((name, selfvar) + args)
yield "(setf %s (%s))" % (result, funcall)
else:
raise NotImplementedError("op_oosend on %s" % (cls,))
def op_oogetfield(self, result, obj, _):
fieldname = self.args[1].value
if isinstance(self.args[0].concretetype, Record):
yield "(setf %s (slot-value %s '%s))" % (clrepr(result, True),
clrepr(obj, True),
clrepr(fieldname, True))
else:
yield "(setf %s (%s %s))" % (clrepr(result, True),
clrepr(fieldname, True),
clrepr(obj, True))
def op_oosetfield(self, result, obj, _, value):
fieldname = self.args[1].value
if isinstance(self.args[0].concretetype, Record):
yield "(setf (slot-value %s '%s) %s)" % (clrepr(obj, True),
clrepr(fieldname, True),
clrepr(value, True))
else:
yield "(setf (%s %s) %s)" % (clrepr(fieldname, True),
clrepr(obj, True),
clrepr(value, True))
def op_ooidentityhash(self, result, arg):
yield "(setf %s (sxhash %s))" % (clrepr(result, True),
clrepr(arg, True))
def op_oononnull(self, result, arg):
yield "(setf %s (not (null %s)))" % (clrepr(result, True),
clrepr(arg, True))
class ListImpl:
def __init__(self, obj):
self.obj = obj
def ll_length(self):
return "(length %s)" % (self.obj,)
def ll_getitem_fast(self, index):
return "(aref %s %s)" % (self.obj, index)
def ll_setitem_fast(self, index, value):
return "(setf (aref %s %s) %s)" % (self.obj, index, value)
def _ll_resize_le(self, size):
return "(adjust-array %s %s)" % (self.obj, size)
def _ll_resize_ge(self, size):
return "(adjust-array %s %s)" % (self.obj, size)
def _ll_resize(self, size):
return "(adjust-array %s %s)" % (self.obj, size)
class DictImpl:
def __init__(self, obj, gen):
self.obj = obj
self.gen = gen
def ll_length(self):
return "(hash-table-count %s)" % (self.obj,)
def ll_contains(self, key):
return "(nth-value 1 (gethash %s %s))" % (key, self.obj)
def ll_get(self, key):
return "(gethash %s %s)" % (key, self.obj)
def ll_set(self, key, value):
return "(setf (gethash %s %s) %s)" % (key, self.obj, value)
def ll_get_items_iterator(self):
# This is explicitly unspecified by the specification.
# Should think of a better way to do this.
name = self.gen.declare_dict_iter()
return "(%s %s)" % (name, self.obj)
class DictItemsIteratorImpl:
def __init__(self, obj):
self.obj = obj
def ll_go_next(self):
return """\
(multiple-value-bind (more key value)
(funcall (first %s))
more)""" % (self.obj,)
def ll_current_key(self):
return "(funcall (second %s))" % (self.obj,)
def ll_current_value(self):
return "(funcall (third %s))" % (self.obj,)
| Python |
from pypy.objspace.flow.model import Constant, Variable, Atom
from pypy.rpython.ootypesystem.ootype import List, Record, Instance
from pypy.rpython.ootypesystem.ootype import Signed, Unsigned, Float, Char
from pypy.rpython.ootypesystem.ootype import Bool, Void, UniChar, Class
from pypy.rpython.ootypesystem.ootype import StaticMethod, Meth, typeOf
def clrepr(item, symbol=False):
""" This is the main repr function and is the only one that should be
used to represent python values in lisp.
"""
if item is None:
return "nil"
fun = bltn_dispatch.get(type(item), None)
if fun is not None:
return fun(item, symbol)
if typeOf(item) is Class:
return "'" + item._INSTANCE._name
return repr_unknown(item)
def repr_const(item):
fun = dispatch.get(type(item.concretetype), None)
if fun is not None:
return fun(item)
fun = dispatch.get(item.concretetype, None)
if fun is not None:
return fun(item)
if item.value is None:
return "nil"
return repr_unknown(item)
def repr_bltn_str(item, symbol):
if symbol:
return item.replace('_', '-')
if len(item) == 1:
return "#\\%c" % (item,)
return '"%s"' % (item,)
def repr_bltn_bool(item, _):
if item:
return "t"
else:
return "nil"
def repr_bltn_number(item, _):
return str(item)
def repr_bltn_seq(item, _):
return "'(" + ' '.join(item) + ")"
def repr_Variable(item, _):
return clrepr(item.name, symbol=True)
def repr_Constant(item, _):
return repr_const(item)
def repr_Instance(item, _):
return "'" + clrepr(item._name, symbol=True)
bltn_dispatch = {
str: repr_bltn_str,
bool: repr_bltn_bool,
int: repr_bltn_number,
long: repr_bltn_number,
float: repr_bltn_number,
list: repr_bltn_seq,
tuple: repr_bltn_seq,
Variable: repr_Variable,
Constant: repr_Constant,
Instance: repr_Instance
}
def repr_atom(atom):
return "'" + clrepr(str(atom), symbol=True)
def repr_class(item):
return clrepr(item.value._INSTANCE._name, symbol=True)
def repr_void(item):
return "nil"
def repr_bool(item):
if item.value:
return "t"
else:
return "nil"
def repr_int(item):
return str(item.value)
def repr_float(item):
return str(item.value)
def repr_list(item):
val = map(clrepr, item.value)
return "'(%s)" % ' '.join(val)
def repr_record(item):
val = map(clrepr, item.value)
return "#(%s)" % ' '.join(val)
def repr_instance(item):
return "'" + repr_class(item)
def repr_static_method(item):
return "'" + clrepr(item.value._name, symbol=True)
dispatch = {
Class: repr_class,
Void: repr_void,
Bool: repr_bool,
Signed: repr_int,
Unsigned: repr_int,
Float: repr_float,
Atom: repr_atom,
List: repr_list,
Record: repr_record,
Instance: repr_instance,
StaticMethod: repr_static_method
}
def repr_unknown(obj):
name = obj.__class__.__name__
raise NotImplementedError("cannot represent %s" % (name,))
| Python |
# empty
| 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 |
import py
from pypy.tool.ansi_print import ansi_log
log = py.log.Producer("oosupport")
py.log.setconsumer("oosupport", ansi_log)
from pypy.objspace.flow import model as flowmodel
from pypy.rpython.ootypesystem import ootype
from pypy.translator.oosupport.treebuilder import SubOperation
from pypy.translator.oosupport.metavm import InstructionList, StoreResult
class Function(object):
def __init__(self, db, graph, name = None, is_method = False, is_entrypoint = False):
self.db = db
self.cts = db.genoo.TypeSystem(db)
self.graph = graph
self.name = self.cts.escape_name(name or graph.name)
self.is_method = is_method
self.is_entrypoint = is_entrypoint
self.generator = None # set in render()
self.label_counters = {}
# If you want to enumerate args/locals before processing, then
# add these functions into your __init__() [they are defined below]
# self._set_args()
# self._set_locals()
def current_label(self, prefix='label'):
current = self.label_counters.get(prefix, 0)
return '__%s_%d' % (prefix, current)
def next_label(self, prefix='label'):
current = self.label_counters.get(prefix, 0)
self.label_counters[prefix] = current+1
return self.current_label(prefix)
def get_name(self):
return self.name
def __repr__(self):
return '<Function %s>' % self.name
def __hash__(self):
return hash(self.graph)
def __eq__(self, other):
return self.graph == other.graph
def __ne__(self, other):
return not self == other
def _is_return_block(self, block):
return (not block.exits) and len(block.inputargs) == 1
def _is_raise_block(self, block):
return (not block.exits) and len(block.inputargs) == 2
def _is_exc_handling_block(self, block):
return block.exitswitch == flowmodel.c_last_exception
def begin_render(self):
raise NotImplementedError
def render_return_block(self, block):
raise NotImplementedError
def render_raise_block(self, block):
raise NotImplementedError
def begin_try(self):
""" Begins a try block; end_try will be called exactly once, then
some number of begin_ and end_catch pairs """
raise NotImplementedError
def end_try(self, target_label):
""" Ends the try block, and branchs to the given target_label if
no exception occurred """
raise NotImplementedError
def begin_catch(self, llexitcase):
""" Begins a catch block for the exception type specified in
llexitcase"""
raise NotImplementedError
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 """
raise NotImplementedError
def render(self, ilasm):
if self.db.graph_name(self.graph) is not None and not self.is_method:
return # already rendered
if getattr(self.graph.func, 'suggested_primitive', False):
assert False, 'Cannot render a suggested_primitive'
self.ilasm = ilasm
self.generator = self._create_generator(self.ilasm)
graph = self.graph
self.begin_render()
self.return_block = None
self.raise_block = None
for block in graph.iterblocks():
if self._is_return_block(block):
self.return_block = block
elif self._is_raise_block(block):
self.raise_block = block
else:
self.set_label(self._get_block_name(block))
if self._is_exc_handling_block(block):
self.render_exc_handling_block(block)
else:
self.render_normal_block(block)
# render return blocks at the end just to please the .NET
# runtime that seems to need a return statement at the end of
# the function
self.before_last_blocks()
if self.raise_block:
self.set_label(self._get_block_name(self.raise_block))
self.render_raise_block(self.raise_block)
if self.return_block:
self.set_label(self._get_block_name(self.return_block))
self.render_return_block(self.return_block)
self.end_render()
if not self.is_method:
self.db.record_function(self.graph, self.name)
def before_last_blocks(self):
pass
def render_exc_handling_block(self, block):
# renders all ops but the last one
for op in block.operations[:-1]:
self._render_op(op)
# render the last one (if any!) and prepend a .try
if block.operations:
self.begin_try()
self._render_op(block.operations[-1])
# search for the "default" block to be executed when no
# exception is raised
for link in block.exits:
if link.exitcase is None:
self._setup_link(link)
self.end_try(self._get_block_name(link.target))
break
else:
assert False, "No non-exceptional case from exc_handling block"
# catch the exception and dispatch to the appropriate block
for link in block.exits:
if link.exitcase is None:
continue # see above
assert issubclass(link.exitcase, py.builtin.BaseException)
ll_meta_exc = link.llexitcase
self.record_ll_meta_exc(ll_meta_exc)
self.begin_catch(link.llexitcase)
self.store_exception_and_link(link)
target_label = self._get_block_name(link.target)
self.end_catch(target_label)
self.after_except_block()
def after_except_block(self):
pass
def record_ll_meta_exc(self, ll_meta_exc):
self.db.constant_generator.record_const(ll_meta_exc)
def store_exception_and_link(self, link):
raise NotImplementedError
def render_normal_block(self, block):
for op in block.operations:
self._render_op(op)
if block.exitswitch is None:
assert len(block.exits) == 1
link = block.exits[0]
target_label = self._get_block_name(link.target)
self._setup_link(link)
self.generator.branch_unconditionally(target_label)
elif block.exitswitch.concretetype is ootype.Bool:
self.render_bool_switch(block)
elif block.exitswitch.concretetype in (ootype.Signed, ootype.SignedLongLong,
ootype.Unsigned, ootype.UnsignedLongLong,
ootype.Char, ootype.UniChar):
self.render_numeric_switch(block)
else:
assert False, 'Unknonw exitswitch type: %s' % block.exitswitch.concretetype
# XXX: soon or later we should use the implementation in
# cli/function.py, but at the moment jvm and js fail with it.
def render_bool_switch(self, block):
for link in block.exits:
self._setup_link(link)
target_label = self._get_block_name(link.target)
if link is block.exits[-1]:
self.generator.branch_unconditionally(target_label)
else:
assert type(link.exitcase) is bool
assert block.exitswitch is not None
self.generator.load(block.exitswitch)
self.generator.branch_conditionally(link.exitcase, target_label)
def render_numeric_switch(self, block):
log.WARNING("The default version of render_numeric_switch is *slow*: please override it in the backend")
self.render_numeric_switch_naive(block)
def render_numeric_switch_naive(self, block):
for link in block.exits:
target_label = self._get_block_name(link.target)
self._setup_link(link)
if link.exitcase == 'default':
self.generator.branch_unconditionally(target_label)
else:
self.generator.push_primitive_constant(block.exitswitch.concretetype, link.exitcase)
self.generator.load(block.exitswitch)
self.generator.branch_if_equal(target_label)
def _follow_link(self, link):
target_label = self._get_block_name(link.target)
self._setup_link(link)
self.generator.branch_unconditionally(target_label)
def _setup_link(self, link):
target = link.target
for to_load, to_store in zip(link.args, target.inputargs):
if isinstance(to_load, flowmodel.Variable) and to_load.name == to_store.name:
continue
if to_load.concretetype is ootype.Void:
continue
self.generator.add_comment("%r --> %r" % (to_load, to_store))
self.generator.load(to_load)
self.generator.store(to_store)
def _render_op(self, op):
instr_list = self.db.genoo.opcodes.get(op.opname, None)
assert instr_list is not None, 'Unknown opcode: %s ' % op
assert isinstance(instr_list, InstructionList)
instr_list.render(self.generator, op)
def _render_sub_op(self, sub_op):
op = sub_op.op
instr_list = self.db.genoo.opcodes.get(op.opname, None)
assert instr_list is not None, 'Unknown opcode: %s ' % op
assert isinstance(instr_list, InstructionList)
assert instr_list[-1] is StoreResult, "Cannot inline an operation that doesn't store the result"
# record that we know about the type of result and args
self.cts.lltype_to_cts(op.result.concretetype)
for v in op.args:
self.cts.lltype_to_cts(v.concretetype)
instr_list = InstructionList(instr_list[:-1]) # leave the value on the stack if this is a sub-op
instr_list.render(self.generator, op)
# now the value is on the stack
# ---------------------------------------------------------#
# These methods are quite backend independent, but not #
# used in all backends. Invoke them from your __init__ if #
# desired. #
# ---------------------------------------------------------#
def _get_block_name(self, block):
# Note: this implementation requires that self._set_locals() be
# called to gather the blocknum's
return 'block%s' % self.blocknum[block]
def _set_locals(self):
# this code is partly borrowed from
# pypy.translator.c.funcgen.FunctionCodeGenerator
# TODO: refactoring to avoid code duplication
self.blocknum = {}
graph = self.graph
mix = [graph.getreturnvar()]
for block in graph.iterblocks():
self.blocknum[block] = len(self.blocknum)
mix.extend(block.inputargs)
for op in block.operations:
mix.extend(op.args)
mix.append(op.result)
if getattr(op, "cleanup", None) is not None:
cleanup_finally, cleanup_except = op.cleanup
for cleanupop in cleanup_finally + cleanup_except:
mix.extend(cleanupop.args)
mix.append(cleanupop.result)
for link in block.exits:
mix.extend(link.getextravars())
mix.extend(link.args)
# filter only locals variables, i.e.:
# - must be variables
# - must appear only once
# - must not be function parameters
# - must not have 'void' type
args = {}
for ctstype, name in self.args:
args[name] = True
locals = []
seen = {}
for v in mix:
is_var = isinstance(v, flowmodel.Variable)
if id(v) not in seen and is_var and v.name not in args and v.concretetype is not ootype.Void:
locals.append(self.cts.llvar_to_cts(v))
seen[id(v)] = True
self.locals = locals
def _set_args(self):
args = [arg for arg in self.graph.getargs() if arg.concretetype is not ootype.Void]
self.args = map(self.cts.llvar_to_cts, args)
self.argset = set([argname for argtype, argname in self.args])
| Python |
from pypy.rpython.lltypesystem.lloperation import LLOp, LL_OPERATIONS as LL_OPS
from pypy.rpython.ootypesystem import ootype
from pypy.objspace.flow import model as flowmodel
LL_OPERATIONS = {
'clibox': LLOp(oo=True, canfold=True),
'cliunbox': LLOp(oo=True, canfold=True),
'cli_newarray': LLOp(oo=True, canfold=True),
'cli_getelem': LLOp(oo=True, sideeffects=False),
'cli_setelem': LLOp(oo=True),
'cli_typeof': LLOp(oo=True, canfold=True),
'cli_arraylength': LLOp(oo=True, canfold=True),
}
LL_OPERATIONS.update(LL_OPS)
class SubOperation(object):
def __init__(self, op):
self.op = op
self.concretetype = op.result.concretetype
def __repr__(self):
return "[%s(%s)]" % (self.op.opname,
", ".join(map(repr, self.op.args)))
def is_mutable(TYPE):
return isinstance(TYPE, (ootype.Instance,
ootype.Record,
ootype.List,
ootype.Dict,
ootype.StringBuilder.__class__,
ootype.CustomDict,
ootype.DictItemsIterator))
# TODO: analyze graphs to determine which functions calls could have
# side effects and which can be inlined safely.
def can_be_inlined(op):
try:
llop = LL_OPERATIONS[op.opname]
return llop.canfold
except KeyError:
return False
def build_op_map(block):
var_count = {}
var_to_op = {}
def inc(v):
if isinstance(v, flowmodel.Variable):
var_count[v] = var_count.get(v, 0) + 1
for i, op in enumerate(block.operations):
var_to_op[op.result] = i, op
for v in op.args:
inc(v)
for link in block.exits:
for v in link.args:
inc(v)
return var_count, var_to_op
def build_trees_for_block(block):
var_count, var_to_op = build_op_map(block)
for op in block.operations:
for i, v in enumerate(op.args):
if var_count.get(v, None) == 1 and v not in block.inputargs: # "inline" the operation
sub_i, sub_op = var_to_op[v]
if can_be_inlined(sub_op):
op.args[i] = SubOperation(sub_op)
block.operations[sub_i] = None
if block.operations != ():
block.operations = [op for op in block.operations if op is not None]
def build_trees(graph):
if not getattr(graph, 'tree_built', False):
for block in graph.iterblocks():
build_trees_for_block(block)
graph.tree_built = True
| Python |
"""
Varius microopcodes for different ootypesystem based backends
These microopcodes are used to translate from the ootype operations to
the operations of a particular backend. For an example, see
cli/opcodes.py which maps from ootype opcodes to sets of metavm
instructions.
See the MicroInstruction class for discussion on the methods of a
micro-op.
"""
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.ootypesystem.bltregistry import ExternalType
from pypy.rpython.extfunc import ExtFuncEntry, is_external
class Generator(object):
def add_comment(self, text):
"""
Called w/in a function w/ a text string that could be
usefully added to the output.
"""
pass
def add_section(self, text):
"""
Prints a distinguished comment
"""
self.add_comment("_" * 70)
self.add_comment(text)
def pop(self, TYPE):
""" Pops a value off the top of the stack, which is of the
given TYPE.
Stack: val, ... -> ..."""
raise NotImplementedError
def dup(self, TYPE):
""" Duplicates the top of the stack, which is of the given TYPE.
Stack: val, ... -> val, val, ..."""
raise NotImplementedError
def emit(self, instr, *args):
"""
Invoked by InstructionList.render() when we encounter a
non-MicroInstruction in the list of instructions. This is
typically used to encode small single operands as strings.
"""
pass
def load(self, v):
"""
Loads an item 'v' onto the stack
Stack: ... -> v, ...
"""
pass
def store(self, v):
"""
Stores an item from the stack into 'v'
Stack: value, ... -> ...
"""
pass
def set_field(self, CONCRETETYPE, fieldname):
"""
Stores a value into a field.
'CONCRETETYPE' should be the type of the class that has the field
'fieldname' is a string with the name of the field
Stack: value, item, ... -> ...
"""
raise NotImplementedError
def get_field(self, CONCRETETYPE, fieldname):
"""
Gets a value from a specified field.
'CONCRETETYPE' should be the type of the class that has the field
'fieldname' is the name of the field
Stack: item, ... -> ...
"""
raise NotImplementedError
def downcast(self, TYPE):
"""
Casts the object on the top of the stack to be of the specified
ootype. Assumed to raise an exception on failure.
Stack: obj, ... -> obj, ...
"""
raise NotImplementedError
def getclassobject(self, OOINSTANCE):
"""
Gets the class object for the OOINSTANCE. The type of the class
object will depend on the backend, of course; for example in JVM
it is java.lang.Class.
"""
raise NotImplementedError
def instantiate(self):
"""
Instantiates an instance of the Class object that is on top of
the stack. Class objects refers to an object representing a
class. Used to implement RuntimeNew.
Stack: class_obj, ... -> instance_obj, ...
"""
raise NotImplementedError
def instanceof(self, TYPE):
"""
Determines whether the object on the top of the stack is an
instance of TYPE (an ootype).
Stack: obj, ... -> boolean, ...
"""
pass
def branch_unconditionally(self, target_label):
""" Branches to target_label unconditionally """
raise NotImplementedError
def branch_conditionally(self, iftrue, target_label):
""" Branches to target_label depending on the value on the top of
the stack. If iftrue is True, then the branch occurs if the value
on top of the stack is true; if iftrue is false, then the branch
occurs if the value on the top of the stack is false
Stack: cond, ... -> ... """
raise NotImplementedError
def branch_if_equal(self, target_label):
"""
Pops two values from the stack and branches to target_label if
they are equal.
Stack: obj1, obj2, ... -> ...
"""
raise NotImplementedError
def call_graph(self, graph):
""" Invokes the function corresponding to the given graph. The
arguments to the graph have already been pushed in order
(i.e., first argument pushed first, etc). Pushes the return
value.
Stack: argN...arg2, arg1, arg0, ... -> ret, ... """
raise NotImplementedError
def prepare_generic_argument(self, ITEMTYPE):
"""
Invoked after a generic argument has been pushed onto the stack.
May not need to do anything, but some backends, *cough*Java*cough*,
require boxing etc.
"""
return # by default do nothing
def call_method(self, OOCLASS, method_name):
""" Invokes the given method on the object on the stack. The
this ptr and all arguments have already been pushed.
Stack: argN, arg2, arg1, this, ... -> ret, ... """
raise NotImplementedError
def call_primitive(self, graph):
""" Like call_graph, but it has been suggested that the method be
rendered as a primitive.
Stack: argN...arg2, arg1, arg0, ... -> ret, ... """
raise NotImplementedError
def new(self, TYPE):
""" Creates a new object of the given type.
Stack: ... -> newobj, ... """
raise NotImplementedError
def push_null(self, TYPE):
""" Push a NULL value onto the stack (the NULL value represents
a pointer to an instance of OOType TYPE, if it matters to you). """
raise NotImplementedError
def push_primitive_constant(self, TYPE, value):
""" Push an instance of TYPE onto the stack with the given
value. TYPE will be one of the types enumerated in
oosupport.constant.PRIMITIVE_TYPES. value will be its
corresponding ootype implementation. """
raise NotImplementedError
class InstructionList(list):
def render(self, generator, op):
for instr in self:
if isinstance(instr, MicroInstruction):
instr.render(generator, op)
else:
generator.emit(instr)
def __call__(self, *args):
return self.render(*args)
class MicroInstruction(object):
def render(self, generator, op):
"""
Generic method which emits code to perform this microinstruction.
'generator' -> the class which generates actual code emitted
'op' -> the instruction from the FlowIR
"""
pass
def __str__(self):
return self.__class__.__name__
def __call__(self, *args):
return self.render(*args)
class _DoNothing(MicroInstruction):
def render(self, generator, op):
pass
class PushArg(MicroInstruction):
""" Pushes a given operand onto the stack. """
def __init__(self, n):
self.n = n
def render(self, generator, op):
generator.load(op.args[self.n])
class _PushAllArgs(MicroInstruction):
""" Pushes all arguments of the instruction onto the stack in order. """
def __init__(self, slice=None):
""" Eventually slice args
"""
self.slice = slice
def render(self, generator, op):
if self.slice is not None:
args = op.args[self.slice]
else:
args = op.args
for arg in args:
generator.load(arg)
class PushPrimitive(MicroInstruction):
def __init__(self, TYPE, value):
self.TYPE = TYPE
self.value = value
def render(self, generator, op):
generator.push_primitive_constant(self.TYPE, self.value)
class _StoreResult(MicroInstruction):
def render(self, generator, op):
generator.store(op.result)
class _SetField(MicroInstruction):
def render(self, generator, op):
this, field, value = op.args
## if field.value == 'meta':
## return # TODO
if value.concretetype is ootype.Void:
return
generator.load(this)
generator.load(value)
generator.set_field(this.concretetype, field.value)
class _GetField(MicroInstruction):
def render(self, generator, op):
# OOType produces void values on occassion that can safely be ignored
if op.result.concretetype is ootype.Void:
return
this, field = op.args
generator.load(this)
generator.get_field(this.concretetype, field.value)
class _DownCast(MicroInstruction):
""" Push the argument op.args[0] and cast it to the desired type, leaving
result on top of the stack. """
def render(self, generator, op):
RESULTTYPE = op.result.concretetype
generator.load(op.args[0])
generator.downcast(RESULTTYPE)
class _InstanceOf(MicroInstruction):
""" Push the argument op.args[0] and cast it to the desired type, leaving
result on top of the stack. """
def render(self, generator, op):
RESULTTYPE = op.result.concretetype
generator.load(op.args[0])
generator.instanceof(RESULTTYPE)
# There are three distinct possibilities where we need to map call differently:
# 1. Object is marked with rpython_hints as a builtin, so every attribut access
# and function call goes as builtin
# 2. Function called is a builtin, so it might be mapped to attribute access, builtin function call
# or even method call
# 3. Object on which method is called is primitive object and method is mapped to some
# method/function/attribute access
class _GeneralDispatcher(MicroInstruction):
def __init__(self, builtins, class_map):
self.builtins = builtins
self.class_map = class_map
def render(self, generator, op):
raise NotImplementedError("pure virtual class")
def check_builtin(self, this):
if not isinstance(this, ootype.Instance):
return False
return this._hints.get('_suggested_external')
def check_external(self, this):
if isinstance(this, ExternalType):
return True
return False
class _MethodDispatcher(_GeneralDispatcher):
def render(self, generator, op):
method = op.args[0].value
this = op.args[1].concretetype
if self.check_external(this):
return self.class_map['CallExternalObject'].render(generator, op)
if self.check_builtin(this):
return self.class_map['CallBuiltinObject'].render(generator, op)
try:
self.builtins.builtin_obj_map[this.__class__][method](generator, op)
except KeyError:
return self.class_map['CallMethod'].render(generator, op)
class _CallDispatcher(_GeneralDispatcher):
def render(self, generator, op):
func = op.args[0]
# XXX we need to sort out stuff here at some point
if is_external(func):
func_name = func.value._name.split("__")[0]
try:
return self.builtins.builtin_map[func_name](generator, op)
except KeyError:
return self.class_map['CallBuiltin'](func_name)(generator, op)
return self.class_map['Call'].render(generator, op)
class _GetFieldDispatcher(_GeneralDispatcher):
def render(self, generator, op):
if self.check_builtin(op.args[0].concretetype):
return self.class_map['GetBuiltinField'].render(generator, op)
else:
return self.class_map['GetField'].render(generator, op)
class _SetFieldDispatcher(_GeneralDispatcher):
def render(self, generator, op):
if self.check_external(op.args[0].concretetype):
return self.class_map['SetExternalField'].render(generator, op)
elif self.check_builtin(op.args[0].concretetype):
return self.class_map['SetBuiltinField'].render(generator, op)
else:
return self.class_map['SetField'].render(generator, op)
class _New(MicroInstruction):
def render(self, generator, op):
try:
op.args[0].value._hints['_suggested_external']
generator.ilasm.new(op.args[0].value._name.split('.')[-1])
except (KeyError, AttributeError):
if op.args[0].value is ootype.Void:
return
generator.new(op.args[0].value)
class BranchUnconditionally(MicroInstruction):
def __init__(self, label):
self.label = label
def render(self, generator, op):
generator.branch_unconditionally(self.label)
class BranchIfTrue(MicroInstruction):
def __init__(self, label):
self.label = label
def render(self, generator, op):
generator.branch_conditionally(True, self.label)
class BranchIfFalse(MicroInstruction):
def __init__(self, label):
self.label = label
def render(self, generator, op):
generator.branch_conditionally(False, self.label)
class _Call(MicroInstruction):
def render(self, generator, op):
callee = op.args[0].value
graph = callee.graph
method_name = None # XXX oopspec.get_method_name(graph, op)
for arg in op.args[1:]:
generator.load(arg)
if method_name is None:
if getattr(graph.func, 'suggested_primitive', False):
generator.call_primitive(graph)
else:
generator.call_graph(graph)
else:
this = op.args[1]
generator.call_method(this.concretetype, method_name)
class _CallMethod(MicroInstruction):
def render(self, generator, op):
method = op.args[0] # a FlowConstant string...
this = op.args[1]
for arg in op.args[1:]:
generator.load(arg)
generator.call_method(this.concretetype, method.value)
class _RuntimeNew(MicroInstruction):
def render(self, generator, op):
generator.load(op.args[0])
generator.instantiate()
generator.downcast(op.result.concretetype)
class _OOString(MicroInstruction):
def render(self, generator, op):
ARGTYPE = op.args[0].concretetype
generator.load(op.args[0])
generator.load(op.args[1])
generator.call_oostring(ARGTYPE)
class _CastTo(MicroInstruction):
def render(self, generator, op):
generator.load(op.args[0])
INSTANCE = op.args[1].value
class_name = generator.db.pending_class(INSTANCE)
generator.isinstance(class_name)
New = _New()
PushAllArgs = _PushAllArgs()
StoreResult = _StoreResult()
SetField = _SetField()
GetField = _GetField()
DownCast = _DownCast()
DoNothing = _DoNothing()
Call = _Call()
CallMethod = _CallMethod()
RuntimeNew = _RuntimeNew()
OOString = _OOString()
CastTo = _CastTo()
| Python |
"""
This module contains code and tests that can be shared between
the various ootypesystem based backends.
"""
| Python |
""" basic oogenerator
"""
from pypy.translator.oosupport import constant as ooconst
class GenOO(object):
TypeSystem = None
Function = None
Database = None
opcodes = None
log = None
# Defines the subclasses used to represent complex constants by
# _create_complex_const:
ConstantGenerator = None
NullConst = ooconst.NullConst
InstanceConst = ooconst.InstanceConst
RecordConst = ooconst.RecordConst
ClassConst = ooconst.ClassConst
ListConst = ooconst.ListConst
StaticMethodConst = ooconst.StaticMethodConst
CustomDictConst = ooconst.CustomDictConst
DictConst = ooconst.DictConst
WeakRefConst = ooconst.WeakRefConst
def __init__(self, tmpdir, translator, entrypoint, config=None):
self.tmpdir = tmpdir
self.translator = translator
self.entrypoint = entrypoint
self.db = self.Database(self)
if config is None:
from pypy.config.pypyoption import get_pypy_config
config = get_pypy_config(translating=True)
self.config = config
def generate_source(self):
self.ilasm = self.create_assembler()
self.fix_names()
self.gen_entrypoint()
self.gen_pendings()
self.db.gen_constants(self.ilasm)
self.ilasm.close()
def gen_entrypoint(self):
if self.entrypoint:
self.entrypoint.set_db(self.db)
self.db.pending_node(self.entrypoint)
else:
self.db.pending_function(self.translator.graphs[0])
def gen_pendings(self):
n = 0
while self.db._pending_nodes:
node = self.db._pending_nodes.pop()
node.render(self.ilasm)
self.db._rendered_nodes.add(node)
n+=1
if (n%100) == 0:
total = len(self.db._pending_nodes) + n
self.log.graphs('Rendered %d/%d (approx. %.2f%%)' %\
(n, total, n*100.0/total))
def fix_names(self):
# it could happen that two distinct graph have the same name;
# here we assign an unique name to each graph.
names = set()
for graph in self.translator.graphs:
base_name = graph.name
i = 0
while graph.name in names:
graph.name = '%s_%d' % (base_name, i)
i+=1
names.add(graph.name)
def create_assembler(self):
raise NotImplementedError
| Python |
from pypy.translator.oosupport.constant import is_primitive
from pypy.rpython.ootypesystem import ootype
class Database(object):
def __init__(self, genoo):
self.genoo = genoo
self.cts = genoo.TypeSystem(self)
self._pending_nodes = set()
self._rendered_nodes = set()
self._unique_counter = 0
self.constant_generator = genoo.ConstantGenerator(self)
self.locked = False # new pending nodes are not allowed here
# ____________________________________________________________
# Miscellaneous
def unique(self):
""" Every time it is called, returns a unique integer. Used in
various places. """
self._unique_counter+=1
return self._unique_counter-1
def class_name(self, OOINSTANCE):
""" Returns the backend class name of the type corresponding
to OOINSTANCE"""
raise NotImplementedError
# ____________________________________________________________
# Generation phases
def gen_constants(self, ilasm):
""" Renders the constants uncovered during the graph walk"""
self.locked = True # new pending nodes are not allowed here
self.constant_generator.gen_constants(ilasm)
self.locked = False
# ____________________________________________________________
# Generation phases
def record_delegate(self, OOTYPE):
""" Returns a backend-specific type for a delegate class...
details currently undefined. """
raise NotImplementedError
# ____________________________________________________________
# Node creation
#
# Creates nodes for various kinds of things.
def pending_class(self, INSTANCE):
""" Returns a Node representing the ootype.Instance provided """
raise NotImplementedError
def pending_function(self, graph):
""" Returns a Node representing the graph, which is being used as
a static function """
raise NotImplementedError
# ____________________________________________________________
# Basic Worklist Manipulation
def pending_node(self, node):
""" Adds a node to the worklist, so long as it is not already there
and has not already been rendered. """
assert not self.locked # sanity check
if node in self._pending_nodes or node in self._rendered_nodes:
return
self._pending_nodes.add(node)
node.dependencies()
def len_pending(self):
return len(self._pending_nodes)
def pop(self):
return self._pending_nodes.pop()
| Python |
"""
___________________________________________________________________________
Constants
Complex code for representing constants. For each complex constant,
we create an object and record it in the database. These objects
contain the knowledge about how to access the value of the constant,
as well as the how to initialize it. The constants are initialized in
two phases so that interdependencies do not prevent a problem.
The initialization process works in two phases:
1. create_pointer(): this creates uninitialized pointers, so that
circular references can be handled.
2. initialize_data(): initializes everything else. The constants are
first sorted by PRIORITY so that CustomDicts are initialized last.
These two methods will be invoked by the ConstantGenerator's gen_constants()
routine.
A backend will typically create its own version of each kind of Const class,
adding at minimum a push() and store() method. A custom variant of
BaseConstantGenerator is also needed. These classes can also be chosen
by the genoo.py subclass of the backend
"""
from pypy.rpython.lltypesystem import llmemory
from pypy.rpython.ootypesystem import ootype
import operator
MAX_CONST_PER_STEP = 100
PRIMITIVE_TYPES = set([ootype.Void, ootype.Bool, ootype.Char, ootype.UniChar,
ootype.Float, ootype.Signed, ootype.Unsigned,
ootype.String, ootype.SignedLongLong,
ootype.UnsignedLongLong])
def is_primitive(TYPE):
return TYPE in PRIMITIVE_TYPES
def push_constant(db, TYPE, value, gen):
""" General method that pushes the value of the specified constant
onto the stack. Use this when you want to load a constant value.
May or may not create an abstract constant object.
db --- a Database
TYPE --- the ootype of the constant
value --- the ootype instance (ootype._list, int, etc)
gen --- a metavm.Generator
"""
constgen = db.constant_generator
if is_primitive(TYPE):
return constgen.push_primitive_constant(gen, TYPE, value)
const = constgen.record_const(value)
if const.is_inline():
const.push_inline(gen, TYPE)
else:
constgen.push_constant(gen, const)
if TYPE is not const.OOTYPE():
constgen.downcast_constant(gen, value, TYPE)
# ______________________________________________________________________
# Constant generator
#
# The back-end can specify which constant generator to use by setting
# genoo.ConstantGenerator to the appropriate class. The
# ConstantGenerator handles invoking the constant's initialization
# routines, as well as loading and storing them.
#
# For the most part, no code needs to interact with the constant
# generator --- the rest of the code base should always invoke
# push_constant(), which may delegate to the constant generator if
# needed.
class BaseConstantGenerator(object):
def __init__(self, db):
self.db = db
self.genoo = db.genoo
self.cache = {}
# _________________________________________________________________
# Constant Operations
#
# Methods for loading and storing the value of constants. Clearly,
# storing the value of a constant is only done internally. These
# must be overloaded by the specific backend. Note that there
# are some more specific variants below that do not have to be overloaded
# but may be.
def push_constant(self, gen, const):
"""
gen --- a generator
const --- an AbstractConst object
Loads the constant onto the stack. Can be invoked at any time.
"""
raise NotImplementedError
def _store_constant(self, gen, const):
"""
gen --- a generator
const --- an AbstractConst object
stores the constant from the stack
"""
raise NotImplementedError
# _________________________________________________________________
# Optional Constant Operations
#
# These allow various hooks at convenient times. All of them are
# already implemented and you don't need to overload them.
def push_primitive_constant(self, gen, TYPE, value):
""" Invoked when an attempt is made to push a primitive
constant. Normally just passes the call onto the code
generator. """
gen.push_primitive_constant(TYPE, value)
def downcast_constant(self, gen, const, EXPECTED_TYPE):
""" Invoked when the expected type of a const does not match
const.OOTYPE(). The constant has been pushed. Normally just
invokes gen.downcast. When it finishes, constant should still
be on the stack. """
gen.downcast(EXPECTED_TYPE)
def _init_constant(self, const):
"""
const --- a freshly created AbstractConst object
Gives the generator a chance to set any fields it wants on the
constant just after the object is first created. Not invoked
while generating constant initialization code, but before.
"""
pass
def _push_constant_during_init(self, gen, const):
"""
gen --- a generator
const --- an AbstractConst object
Just like push_constant, but only invoked during
initialization. By default simply invokes push_constant().
"""
return self.push_constant(gen, const)
def _pre_store_constant(self, gen, const):
"""
gen --- a generator
const --- an AbstractConst object
invoked before the constant's create_pointer() routine is
called, to prepare the stack in any way needed. Typically
does nothing, but sometimes pushes the 'this' pointer if the
constant will be stored in the field of a singleton object.
"""
pass
# _________________________________________________________________
# Constant Object Creation
#
# Code that deals with creating AbstractConst objects and recording
# them. You should not need to change anything here.
def record_const(self, value):
""" Returns an object representing the constant, remembering
also any details needed to initialize the constant. value
should be an ootype constant value. Not generally called
directly, but it can be if desired. """
assert not is_primitive(value)
if value in self.cache:
return self.cache[value]
const = self._create_complex_const(value)
self.cache[value] = const
self._init_constant(const)
const.record_dependencies()
return const
def _create_complex_const(self, value):
""" A helper method which creates a Constant wrapper object for
the given value. Uses the types defined in the sub-class. """
# Determine if the static type differs from the dynamic type.
if isinstance(value, ootype._view):
static_type = value._TYPE
value = value._inst
else:
static_type = None
# Find the appropriate kind of Const object.
genoo = self.genoo
uniq = self.db.unique()
if isinstance(value, ootype._instance):
return genoo.InstanceConst(self.db, value, static_type, uniq)
elif isinstance(value, ootype._record):
return genoo.RecordConst(self.db, value, uniq)
elif isinstance(value, ootype._class):
return genoo.ClassConst(self.db, value, uniq)
elif isinstance(value, ootype._list):
return genoo.ListConst(self.db, value, uniq)
elif isinstance(value, ootype._static_meth):
return genoo.StaticMethodConst(self.db, value, uniq)
elif isinstance(value, ootype._custom_dict):
return genoo.CustomDictConst(self.db, value, uniq)
elif isinstance(value, ootype._dict):
return genoo.DictConst(self.db, value, uniq)
elif isinstance(value, llmemory.fakeweakaddress):
return genoo.WeakRefConst(self.db, value, uniq)
elif value is ootype.null(value._TYPE):
# for NULL values, we can just use "NULL" const. This is
# a fallback since we sometimes have constants of
# unhandled types which are equal to NULL.
return genoo.NullConst(self.db, value, uniq)
else:
assert False, 'Unknown constant: %s' % value
# _________________________________________________________________
# Constant Generation
#
# You will not generally need to overload any of the functions
# in this section.
def gen_constants(self, ilasm):
# Sort constants by priority. Don't bother with inline
# constants.
all_constants = [c for c in self.cache.values() if not c.is_inline()]
all_constants.sort(key=lambda c: (c.PRIORITY, c.count))
# Counters to track how many steps we have emitted so far, etc.
# See _consider_step() for more information.
self._step_counter = 0
self._all_counter = 0
# Now, emit the initialization code:
gen = self._begin_gen_constants(ilasm, all_constants)
for const in all_constants:
self._declare_const(gen, const)
self._create_pointers(gen, all_constants)
self._initialize_data(gen, all_constants)
self._end_step(gen)
self._end_gen_constants(gen, self._step_counter)
def _create_pointers(self, gen, all_constants):
""" Iterates through each constant, creating the pointer for it
and storing it. """
gen.add_section("Create Pointer Phase")
for const in all_constants:
gen.add_comment("Constant: %s" % const.name)
self._pre_store_constant(gen, const)
self._consider_step(gen)
const.create_pointer(gen)
self._store_constant(gen, const)
def _initialize_data(self, gen, all_constants):
""" Iterates through each constant, initializing its data. """
gen.add_section("Initialize Data Phase")
for const in all_constants:
self._consider_step(gen)
gen.add_comment("Constant: %s" % const.name)
self._push_constant_during_init(gen, const)
if not const.initialize_data(gen):
gen.pop(const.OOTYPE())
def _consider_step(self, gen):
""" Considers whether to start a new step at this point. We
start a new step every so often to ensure the initialization
functions don't get too large and upset mono or the JVM or
what have you. """
if (self._all_counter % MAX_CONST_PER_STEP) == 0:
self._end_step(gen)
self._declare_step(gen, self._step_counter) # open the next step
self._all_counter += 1
def _end_step(self, gen):
""" Ends the current step if one has begun. """
if self._all_counter != 0:
self._close_step(gen, self._step_counter) # close previous step
self._step_counter += 1
# _________________________________________________________________
# Abstract functions you must overload
def _begin_gen_constants(self, ilasm, all_constants):
""" Invoked with the assembler and sorted list of constants
before anything else. Expected to return a generator that will
be passed around after that (the parameter named 'gen'). """
raise NotImplementedError
def _declare_const(self, gen, const):
""" Invoked once for each constant before any steps are created. """
raise NotImplementedError
def _declare_step(self, gen, stepnum):
""" Invoked to begin step #stepnum. stepnum starts with 0 (!)
and proceeds monotonically. If _declare_step() is invoked,
there will always be a corresponding call to _close_step(). """
raise NotImplementedError
def _close_step(self, gen, stepnum):
""" Invoked to end step #stepnum. Never invoked without a
corresponding call from _declare_step() first. """
raise NotImplementedError
def _end_gen_constants(self, gen, numsteps):
""" Invoked as the very last thing. numsteps is the total number
of steps that were created. """
raise NotImplementedError
# ______________________________________________________________________
# Constant base class
class AbstractConst(object):
PRIORITY = 0
def __init__(self, db, value, count):
self.db = db
self.cts = db.genoo.TypeSystem(db)
self.value = value
self.count = count
# ____________________________________________________________
# Hashing, equality comparison, and repr()
#
# Overloaded so that two AbstactConst objects representing
# the same OOValue are equal. Provide a sensible repr()
def __hash__(self):
return hash(self.value)
def __eq__(self, other):
return self.value == other.value
def __ne__(self, other):
return not self == other
def __repr__(self):
return '<Const %s %s>' % (self.name, self.value)
# ____________________________________________________________
# Simple query routines
def OOTYPE(self):
return self.value._TYPE
def get_name(self):
pass
def is_null(self):
return self.value is ootype.null(self.value._TYPE)
def is_inline(self):
"""
Inline constants are not stored as static fields in the
Constant class, but they are newly created on the stack every
time they are used. Classes overriding is_inline should
override push_inline too. By default only NULL constants are
inlined.
"""
return self.is_null()
def push_inline(self, gen, EXPECTED_TYPE):
"""
Invoked by push_constant() when is_inline() returns true.
By default, just pushes NULL as only NULL constants are inlined.
If you overload this, overload is_inline() too.
"""
assert self.is_inline() and self.is_null()
return gen.push_null(EXPECTED_TYPE)
# ____________________________________________________________
# Initializing the constant
def record_dependencies(self):
"""
Ensures that all dependent objects are added to the database,
and any classes that are used are loaded. Called when the
constant object is created.
"""
raise NotImplementedException
def create_pointer(self, gen):
"""
Creates the pointer representing this object, but does not
initialize its fields. First phase of initialization.
"""
assert not self.is_null()
gen.new(self.value._TYPE)
def initialize_data(self, gen):
"""
Initializes the internal data. Begins with a pointer to
the constant on the stack. Normally returns something
false (like, say, None) --- but returns True if it consumes
the pointer from the stack in the process; otherwise, a pop
is automatically inserted afterwards.
"""
raise NotImplementedException
# ____________________________________________________________
# Internal helpers
def _record_const_if_complex(self, TYPE, value):
if not is_primitive(TYPE):
self.db.constant_generator.record_const(value)
# ______________________________________________________________________
# Null Values
#
# NULL constants of types for which we have no better class use this
# class. For example, dict item iterators and the like.
class NullConst(AbstractConst):
def __init__(self, db, value, count):
AbstractConst.__init__(self, db, value, count)
self.name = 'NULL__%d' % count
assert self.is_null() and self.is_inline()
def record_dependencies(self):
return
# ______________________________________________________________________
# Records
class RecordConst(AbstractConst):
def __init__(self, db, record, count):
AbstractConst.__init__(self, db, record, count)
self.name = 'RECORD__%d' % count
def record_dependencies(self):
if self.value is ootype.null(self.value._TYPE):
return
for f_name, (FIELD_TYPE, f_default) in self.value._TYPE._fields.iteritems():
value = self.value._items[f_name]
self._record_const_if_complex(FIELD_TYPE, value)
def initialize_data(self, gen):
assert not self.is_null()
SELFTYPE = self.value._TYPE
for f_name, (FIELD_TYPE, f_default) in self.value._TYPE._fields.iteritems():
if FIELD_TYPE is not ootype.Void:
gen.dup(SELFTYPE)
value = self.value._items[f_name]
push_constant(self.db, FIELD_TYPE, value, gen)
gen.set_field(SELFTYPE, f_name)
# ______________________________________________________________________
# Instances
class InstanceConst(AbstractConst):
def __init__(self, db, obj, static_type, count):
AbstractConst.__init__(self, db, obj, count)
if static_type is None:
self.static_type = obj._TYPE
else:
self.static_type = static_type
db.genoo.TypeSystem(db).lltype_to_cts(
obj._TYPE) # force scheduling of obj's class
class_name = db.class_name(obj._TYPE).replace('.', '_')
self.name = '%s__%d' % (class_name, count)
def record_dependencies(self):
if not self.value:
return
INSTANCE = self.value._TYPE
while INSTANCE is not None:
for name, (TYPE, default) in INSTANCE._fields.iteritems():
if TYPE is ootype.Void:
continue
type_ = self.cts.lltype_to_cts(TYPE) # record type
value = getattr(self.value, name) # record value
self._record_const_if_complex(TYPE, value)
INSTANCE = INSTANCE._superclass
def is_null(self):
return not self.value
def _sorted_const_list(self):
# XXX, horrible hack: first collect all consts, then render
# CustomDicts at last because their ll_set could need other
# fields already initialized. We should really think a more
# general way to handle such things.
const_list = []
INSTANCE = self.value._TYPE
while INSTANCE is not None:
for name, (TYPE, default) in INSTANCE._fields.iteritems():
if TYPE is ootype.Void:
continue
value = getattr(self.value, name)
const_list.append((TYPE, INSTANCE, name, value))
INSTANCE = INSTANCE._superclass
def mycmp(x, y):
if isinstance(x[0], ootype.CustomDict) and not isinstance(y[0], ootype.CustomDict):
return 1 # a CustomDict is always greater than non-CustomDicts
elif isinstance(y[0], ootype.CustomDict) and not isinstance(x[0], ootype.CustomDict):
return -1 # a non-CustomDict is always less than CustomDicts
else:
return cmp(x, y)
const_list.sort(mycmp)
return const_list
def initialize_data(self, gen):
assert not self.is_null()
# Get a list of all the constants we'll need to initialize.
# I am not clear on why this needs to be sorted, actually,
# but we sort it.
const_list = self._sorted_const_list()
# Push ourself on the stack, and cast to our actual type if it
# is not the same as our static type
SELFTYPE = self.value._TYPE
if SELFTYPE is not self.static_type:
gen.downcast(SELFTYPE)
# Store each of our fields in the sorted order
for FIELD_TYPE, INSTANCE, name, value in const_list:
gen.dup(SELFTYPE)
push_constant(self.db, FIELD_TYPE, value, gen)
gen.set_field(INSTANCE, name)
# ______________________________________________________________________
# Class constants
class ClassConst(AbstractConst):
def __init__(self, db, class_, count):
AbstractConst.__init__(self, db, class_, count)
self.name = 'CLASS__%d' % count
def record_dependencies(self):
INSTANCE = self.value._INSTANCE
if INSTANCE is not None:
self.cts.lltype_to_cts(INSTANCE) # force scheduling class generation
def is_null(self):
return self.value._INSTANCE is None
def create_pointer(self, gen):
assert not self.is_null()
INSTANCE = self.value._INSTANCE
gen.getclassobject(INSTANCE)
def initialize_data(self, gen):
pass
# ______________________________________________________________________
# List constants
class ListConst(AbstractConst):
def __init__(self, db, list, count):
AbstractConst.__init__(self, db, list, count)
self.name = 'LIST__%d' % count
def record_dependencies(self):
if not self.value:
return
for item in self.value._list:
self._record_const_if_complex(self.value._TYPE._ITEMTYPE, item)
def create_pointer(self, gen):
assert not self.is_null()
SELFTYPE = self.value._TYPE
# XXX --- should we add something special to the generator for
# this? I want it to look exactly like it would in normal
# opcodes...but of course under current system I can't know
# what normal opcodes would look like as they fall under the
# perview of each backend rather than oosupport
# Create the list
gen.new(SELFTYPE)
# And then resize it to the correct size
gen.dup(SELFTYPE)
push_constant(self.db, ootype.Signed, len(self.value._list), gen)
gen.call_method(SELFTYPE, '_ll_resize')
def _do_not_initialize(self):
""" Returns True if the list should not be initialized; this
can be overloaded by the backend if your conditions are wider.
The default is not to initialize if the list is a list of
Void. """
return self.value._TYPE._ITEMTYPE is ootype.Void
try:
return self.value._list == [0] * len(self.value._list)
except:
return False
def initialize_data(self, gen):
assert not self.is_null()
SELFTYPE = self.value._TYPE
ITEMTYPE = self.value._TYPE._ITEMTYPE
# check for special cases and avoid initialization
if self._do_not_initialize():
return
# set each item in the list using the OOTYPE methods
for idx, item in enumerate(self.value._list):
gen.dup(SELFTYPE)
push_constant(self.db, ootype.Signed, idx, gen)
push_constant(self.db, ITEMTYPE, item, gen)
gen.prepare_generic_argument(ITEMTYPE)
gen.call_method(SELFTYPE, 'll_setitem_fast')
# ______________________________________________________________________
# Dictionary constants
class DictConst(AbstractConst):
PRIORITY = 90
def __init__(self, db, dict, count):
AbstractConst.__init__(self, db, dict, count)
self.name = 'DICT__%d' % count
def record_dependencies(self):
if not self.value:
return
for key, value in self.value._dict.iteritems():
self._record_const_if_complex(self.value._TYPE._KEYTYPE, key)
self._record_const_if_complex(self.value._TYPE._VALUETYPE, value)
def initialize_data(self, gen):
assert not self.is_null()
SELFTYPE = self.value._TYPE
KEYTYPE = self.value._TYPE._KEYTYPE
VALUETYPE = self.value._TYPE._VALUETYPE
gen.add_comment('Initializing dictionary constant')
if KEYTYPE is ootype.Void:
assert VALUETYPE is ootype.Void
return
for key, value in self.value._dict.iteritems():
gen.dup(SELFTYPE)
gen.add_comment(' key=%r value=%r' % (key,value))
push_constant(self.db, KEYTYPE, key, gen)
gen.prepare_generic_argument(KEYTYPE)
if VALUETYPE is ootype.Void:
# special case dict of Void; for now store the key as value?
gen.dup(KEYTYPE)
else:
push_constant(self.db, VALUETYPE, value, gen)
gen.prepare_generic_argument(VALUETYPE)
gen.call_method(SELFTYPE, 'll_set')
class CustomDictConst(DictConst):
PRIORITY = 100
# ______________________________________________________________________
# Static method constants
class StaticMethodConst(AbstractConst):
def __init__(self, db, sm, count):
AbstractConst.__init__(self, db, sm, count)
self.name = 'DELEGATE__%d' % count
def record_dependencies(self):
if self.value is ootype.null(self.value._TYPE):
return
self.db.pending_function(self.value.graph)
self.delegate_type = self.db.record_delegate(self.value._TYPE)
def initialize_data(self, ilasm):
raise NotImplementedError
# ______________________________________________________________________
# Weak Reference constants
class WeakRefConst(AbstractConst):
def __init__(self, db, fakeaddr, count):
AbstractConst.__init__(self, db, fakeaddr.get(), count)
self.name = 'WEAKREF__%d' % count
def OOTYPE(self):
# Not sure what goes here...?
return None
def is_null(self):
return False
def record_dependencies(self):
if self.value is not None:
self.db.constant_generator.record_const(self.value)
| 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 |
"""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 |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.