code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
import autopath
from py import path
import py
import os
import sys
from subprocess import *
pwd = path.local(__file__)
shell = pwd.dirpath('test', 'ecma', 'shell.js')
exclusionlist = ['shell.js', 'browser.js']
def filter(filename):
if filename.basename in exclusionlist or not filename.basename.endswith('.js'):
return False
else:
return True
if py.path.local.sysfind("js") is None:
print "js interpreter not found in path"
sys.exit()
results = open('results.txt', 'w')
for f in pwd.dirpath('test', 'ecma').visit(filter):
print f.basename
cmd = './js_interactive.py -n -f %s -f %s'%(shell, f)
p = Popen(cmd, shell=True, stdout=PIPE)
passed = 0
total = 0
for line in p.stdout.readlines():
if "PASSED!" in line:
passed += 1
total += 1
elif "FAILED!" in line:
total += 1
results.write('%s passed %s of %s tests\n'%(f.basename, passed, total))
results.flush()
| Python |
from pypy.rlib.parsing.ebnfparse import parse_ebnf, make_parse_function
from pypy.rlib.parsing.parsing import ParseError, Rule
import py
GFILE = py.magic.autopath().dirpath().join("jsgrammar.txt")
try:
t = GFILE.read(mode='U')
regexs, rules, ToAST = parse_ebnf(t)
except ParseError,e:
print e.nice_error_message(filename=str(GFILE),source=t)
raise
parsef = make_parse_function(regexs, rules, eof=True)
def parse(code):
t = parsef(code)
return ToAST().transform(t)
| Python |
#
| Python |
from pypy.rlib.parsing.ebnfparse import parse_ebnf, make_parse_function
from pypy.rlib.parsing.parsing import ParseError, Rule
from pypy.rlib.parsing.tree import RPythonVisitor, Symbol
from pypy.lang.js.jsobj import W_Number
from pypy.lang.js import operations
import sys
##try:
## t = open("jsgrammar.txt").read()
## regexs, rules, ToAST = parse_ebnf(t)
##except ParseError,e:
## print e.nice_error_message(filename="jsgrammar.txt",source=t)
## sys.exit(1)
##
##def setstartrule(rules, start):
## "takes the rule start and put it on the beginning of the rules"
## oldpos = 0
## newrules = [Rule("hacked_first_symbol", [[start, "EOF"]])] + rules
## return newrules
##
##if len(sys.argv) == 1:
## parse = make_parse_function(regexs, rules, eof=True)
##else:
## parse = make_parse_function(regexs, setstartrule(rules,sys.argv[1]), eof=True)
##
##print rules[2].nonterminal
##source = raw_input()
##while source != "":
## t = parse(source).children[0].visit(ToAST())[0]
## print t
## t.view()
## source = raw_input()
class EvalTreeBuilder(RPythonVisitor):
BINOP_TO_CLS = {
'+': operations.Plus,
'-': operations.Minus,
'*': operations.Mult,
'/': operations.Div,
'%': operations.Mod,
}
UNOP_TO_CLS = {
'+': operations.UPlus,
'-': operations.UMinus,
'++': operations.Increment,
'--': operations.Decrement,
}
def get_instance(self, symbol, cls):
assert isinstance(symbol, Symbol)
source_pos = symbol.token.source_pos
# XXX some of the source positions are not perfect
return cls(None, "no clue what self.type is used for",
symbol.additional_info,
source_pos.lineno,
source_pos.columnno,
source_pos.columnno + len(symbol.additional_info))
def visit_DECIMALLITERAL(self, node):
result = self.get_instance(node, operations.Number)
result.num = float(node.additional_info)
return result
def string(self,node):
print node.additional_info
result = self.get_instance(node, operations.String)
result.strval = node.additional_info[1:-1] #XXX should do unquoting
return result
visit_DOUBLESTRING = string
visit_SINGLESTRING = string
def binaryop(self, node):
left = self.dispatch(node.children[0])
for i in range((len(node.children) - 1) // 2):
op = node.children[i * 2 + 1]
result = self.get_instance(
op, self.BINOP_TO_CLS[op.additional_info])
right = self.dispatch(node.children[i * 2 + 2])
result.left = left
result.right = right
left = result
return left
visit_additiveexpression = binaryop
visit_multiplicativeexpression = binaryop
def visit_unaryexpression(self, node):
op = node.children[0]
result = self.get_instance(
op, self.UNOP_TO_CLS[op.additional_info])
child = self.dispatch(node.children[1])
result.expr = child
result.postfix = False
return result
| Python |
# encoding: utf-8
from pypy.rlib.rarithmetic import r_uint, intmask
class SeePage(NotImplementedError):
pass
class JsBaseExcept(Exception): pass
class ExecutionReturned(JsBaseExcept):
def __init__(self, type='normal', value=None, identifier=None):
self.type = type
self.value = value
self.identifier = identifier
class ThrowException(JsBaseExcept):
def __init__(self, exception):
self.exception = exception
self.args = [exception]
class JsTypeError(JsBaseExcept):
pass
class RangeError(JsBaseExcept): pass
Infinity = 1e300 * 1e300
NaN = Infinity/Infinity
class Property(object):
def __init__(self, name, value, dd=False,
ro=False, de=False, it=False):
self.name = name
self.value = value
self.dd = dd
self.ro = ro
self.de = de
self.it = it
def __repr__(self):
return "|%s %d%d%d|"%(self.value, self.dd,
self.ro, self.de)
def internal_property(name, value):
"""return a internal property with the right attributes"""
return Property(name, value, True, True, True, True)
class W_Root(object):
def GetValue(self):
return self
def ToBoolean(self):
return False
def ToPrimitive(self, ctx, hint=""):
return self
def ToString(self, ctx):
return ''
def ToObject(self, ctx):
# XXX should raise not implemented
return self
def ToNumber(self):
return NaN
def ToInt32(self):
return 0
def ToUInt32(self):
return r_uint(0)
def Get(self, P):
print P
raise NotImplementedError
def Put(self, P, V, dd=False,
ro=False, de=False, it=False):
raise NotImplementedError
def PutValue(self, w, ctx):
pass
def Call(self, ctx, args=[], this=None):
raise NotImplementedError
def __str__(self):
return self.ToString(ctx=None)
def type(self):
raise NotImplementedError
def GetPropertyName(self):
raise NotImplementedError
class W_Undefined(W_Root):
def __str__(self):
return "w_undefined"
def ToNumber(self):
return NaN
def ToBoolean(self):
return False
def ToString(self, ctx = None):
return "undefined"
def type(self):
return 'undefined'
class W_Null(W_Root):
def __str__(self):
return "null"
def ToBoolean(self):
return False
def type(self):
return 'null'
w_Undefined = W_Undefined()
w_Null = W_Null()
class W_Primitive(W_Root):
"""unifying parent for primitives"""
def ToPrimitive(self, ctx, hint=""):
return self
class W_PrimitiveObject(W_Root):
def __init__(self, ctx=None, Prototype=None, Class='Object',
Value=w_Undefined, callfunc=None):
self.propdict = {}
self.Prototype = Prototype
if Prototype is None:
Prototype = w_Undefined
self.propdict['prototype'] = Property('prototype', Prototype,
dd=True, de=True)
self.Class = Class
self.callfunc = callfunc
if callfunc is not None:
self.Scope = ctx.scope[:]
else:
self.Scope = None
self.Value = Value
def Call(self, ctx, args=[], this=None):
if self.callfunc is None: # XXX Not sure if I should raise it here
raise JsTypeError('not a function')
act = ActivationObject()
paramn = len(self.callfunc.params)
for i in range(paramn):
paramname = self.callfunc.params[i]
try:
value = args[i]
except IndexError:
value = w_Undefined
act.Put(paramname, value)
act.Put('this', this)
w_Arguments = W_Arguments(self, args)
act.Put('arguments', w_Arguments)
newctx = function_context(self.Scope, act, this)
val = self.callfunc.body.execute(ctx=newctx)
return val
def Construct(self, ctx, args=[]):
obj = W_Object(Class='Object')
prot = self.Get('prototype')
if isinstance(prot, W_PrimitiveObject):
obj.Prototype = prot
else: # would love to test this
#but I fail to find a case that falls into this
obj.Prototype = ctx.get_global().Get('Object').Get('prototype')
try: #this is a hack to be compatible to spidermonkey
self.Call(ctx, args, this=obj)
return obj
except ExecutionReturned, e:
return e.value
def Get(self, P):
if P in self.propdict: return self.propdict[P].value
if self.Prototype is None: return w_Undefined
return self.Prototype.Get(P) # go down the prototype chain
def CanPut(self, P):
if P in self.propdict:
if self.propdict[P].ro: return False
return True
if self.Prototype is None: return True
return self.Prototype.CanPut(P)
def Put(self, P, V, dd=False,
ro=False, de=False, it=False):
if not self.CanPut(P):
return
if P in self.propdict:
self.propdict[P].value = V
else:
self.propdict[P] = Property(P, V,
dd = dd, ro = ro, it = it)
def HasProperty(self, P):
if P in self.propdict: return True
if self.Prototype is None: return False
return self.Prototype.HasProperty(P)
def Delete(self, P):
if P in self.propdict:
if self.propdict[P].dd: return False
del self.propdict[P]
return True
return True
def internal_def_value(self, ctx, tryone, trytwo):
t1 = self.Get(tryone)
if isinstance(t1, W_PrimitiveObject):
val = t1.Call(ctx, this=self)
if isinstance(val, W_Primitive):
return val
t2 = self.Get(trytwo)
if isinstance(t2, W_PrimitiveObject):
val = t2.Call(ctx, this=self)
if isinstance(val, W_Primitive):
return val
raise JsTypeError
def DefaultValue(self, ctx, hint=""):
if hint == "String":
return self.internal_def_value(ctx, "toString", "valueOf")
else: # hint can only be empty, String or Number
return self.internal_def_value(ctx, "valueOf", "toString")
ToPrimitive = DefaultValue
def ToString(self, ctx):
try:
res = self.ToPrimitive(ctx, 'String')
except JsTypeError:
return "[object %s]"%(self.Class,)
return res.ToString(ctx)
def __str__(self):
return "<Object class: %s>" % self.Class
def type(self):
if self.callfunc is not None:
return 'function'
else:
return 'object'
def str_builtin(ctx, args, this):
return W_String(this.ToString(ctx))
class W_Object(W_PrimitiveObject):
def __init__(self, ctx=None, Prototype=None, Class='Object',
Value=w_Undefined, callfunc=None):
W_PrimitiveObject.__init__(self, ctx, Prototype,
Class, Value, callfunc)
class W_NewBuiltin(W_PrimitiveObject):
def __init__(self, ctx, Prototype=None, Class='function',
Value=w_Undefined, callfunc=None):
if Prototype is None:
proto = ctx.get_global().Get('Function').Get('prototype')
Prototype = proto
W_PrimitiveObject.__init__(self, ctx, Prototype, Class, Value, callfunc)
def Call(self, ctx, args=[], this = None):
raise NotImplementedError
def type(self):
return 'builtin'
class W_Builtin(W_PrimitiveObject):
def __init__(self, builtin=None, ctx=None, Prototype=None, Class='function',
Value=w_Undefined, callfunc=None):
W_PrimitiveObject.__init__(self, ctx, Prototype, Class, Value, callfunc)
self.set_builtin_call(builtin)
def set_builtin_call(self, callfuncbi):
self.callfuncbi = callfuncbi
def Call(self, ctx, args=[], this = None):
return self.callfuncbi(ctx, args, this)
def Construct(self, ctx, args=[]):
return self.callfuncbi(ctx, args, None)
def type(self):
return 'builtin'
class W_ListObject(W_PrimitiveObject):
def tolist(self):
l = []
for i in range(self.length):
l.append(self.propdict[str(i)].value)
return l
class W_Arguments(W_ListObject):
def __init__(self, callee, args):
W_PrimitiveObject.__init__(self, Class='Arguments')
del self.propdict["prototype"]
self.Put('callee', callee)
self.Put('length', W_Number(len(args)))
for i in range(len(args)):
self.Put(str(i), args[i])
self.length = len(args)
class ActivationObject(W_PrimitiveObject):
"""The object used on function calls to hold arguments and this"""
def __init__(self):
W_PrimitiveObject.__init__(self, Class='Activation')
del self.propdict["prototype"]
def __repr__(self):
return str(self.propdict)
class W_Array(W_ListObject):
def __init__(self, ctx=None, Prototype=None, Class='Array',
Value=w_Undefined, callfunc=None):
W_PrimitiveObject.__init__(self, ctx, Prototype, Class, Value, callfunc)
self.Put('length', W_Number(0))
self.length = r_uint(0)
def Put(self, P, V, dd=False,
ro=False, de=False, it=False):
if not self.CanPut(P): return
if P in self.propdict:
if P == 'length':
try:
res = V.ToUInt32()
if V.ToNumber() < 0:
raise RangeError()
self.propdict['length'].value = W_Number(res)
self.length = res
return
except ValueError:
raise RangeError('invalid array length')
else:
self.propdict[P].value = V
else:
self.propdict[P] = Property(P, V,
dd = dd, ro = ro, it = it)
try:
index = r_uint(float(P))
except ValueError:
return
if index < self.length:
return
self.length = index+1
self.propdict['length'].value = W_Number(index+1)
return
class W_Boolean(W_Primitive):
def __init__(self, boolval):
self.boolval = bool(boolval)
def ToObject(self, ctx):
return create_object(ctx, 'Boolean', Value=self)
def ToString(self, ctx=None):
if self.boolval == True:
return "true"
return "false"
def ToNumber(self):
if self.boolval:
return 1.0
return 0.0
def ToBoolean(self):
return self.boolval
def type(self):
return 'boolean'
def __repr__(self):
return "<W_Bool "+str(self.boolval)+" >"
class W_String(W_Primitive):
def __init__(self, strval):
self.strval = strval
def __str__(self):
return self.strval+"W"
def ToObject(self, ctx):
return create_object(ctx, 'String', Value=self)
def ToString(self, ctx=None):
return self.strval
def ToBoolean(self):
return bool(self.strval)
def type(self):
return 'string'
def GetPropertyName(self):
return self.ToString()
class W_Number(W_Primitive):
def __init__(self, floatval):
try:
self.floatval = float(floatval)
except OverflowError:
# XXX this should not be happening, there is an error somewhere else
#an ecma test to stress this is GlobalObject/15.1.2.2-2.js
self.floatval = Infinity
def __str__(self):
return str(self.floatval)+"W"
def ToObject(self, ctx):
return create_object(ctx, 'Number', Value=self)
def ToString(self, ctx = None):
floatstr = str(self.floatval)
if floatstr == str(NaN):
return 'NaN'
if floatstr == str(Infinity):
return 'Infinity'
if floatstr == str(-Infinity):
return '-Infinity'
try:
if float(int(self.floatval)) == self.floatval:
return str(int(self.floatval))
except OverflowError, e:
pass
return floatstr
def ToBoolean(self):
if self.floatval == 0.0 or str(self.floatval) == str(NaN):
return False
return bool(self.floatval)
def ToNumber(self):
return self.floatval
def Get(self, name):
return w_Undefined
def type(self):
return 'number'
def ToInt32(self):
strval = str(self.floatval)
if strval == str(NaN) or \
strval == str(Infinity) or \
strval == str(-Infinity):
return 0
return int(self.floatval)
def ToUInt32(self):
strval = str(self.floatval)
if strval == str(NaN) or \
strval == str(Infinity) or \
strval == str(-Infinity):
return r_uint(0)
return r_uint(self.floatval)
def GetPropertyName(self):
return self.ToString()
class W_List(W_Root):
def __init__(self, list_w):
self.list_w = list_w
def ToString(self, ctx = None):
raise SeePage(42)
def ToBoolean(self):
return bool(self.list_w)
def get_args(self):
return self.list_w
def __str__(self):
return str(self.list_w)
class ExecutionContext(object):
def __init__(self, scope, this=None, variable=None,
debug=False, jsproperty=None):
assert scope is not None
self.scope = scope
if this is None:
self.this = scope[-1]
else:
self.this = this
if variable is None:
self.variable = self.scope[0]
else:
self.variable = variable
self.debug = debug
if jsproperty is None:
#Attribute flags for new vars
self.property = Property('',w_Undefined)
else:
self.property = jsproperty
def __str__(self):
return "<ExCtx %s, var: %s>"%(self.scope, self.variable)
def assign(self, name, value):
pass
def get_global(self):
return self.scope[-1]
def push_object(self, obj):
"""push object into scope stack"""
assert isinstance(obj, W_PrimitiveObject)
self.scope.insert(0, obj)
self.variable = obj
def pop_object(self):
"""remove the last pushed object"""
return self.scope.pop(0)
def resolve_identifier(self, identifier):
for obj in self.scope:
assert isinstance(obj, W_PrimitiveObject)
if obj.HasProperty(identifier):
return W_Reference(identifier, obj)
return W_Reference(identifier)
def global_context(w_global):
assert isinstance(w_global, W_PrimitiveObject)
ctx = ExecutionContext([w_global],
this = w_global,
variable = w_global,
jsproperty = Property('', w_Undefined, dd=True))
return ctx
def function_context(scope, activation, this=None):
newscope = scope[:]
ctx = ExecutionContext(newscope,
this = this,
jsproperty = Property('', w_Undefined, dd=True))
ctx.push_object(activation)
return ctx
def eval_context(calling_context):
ctx = ExecutionContext(calling_context.scope[:],
this = calling_context.this,
variable = calling_context.variable,
jsproperty = Property('', w_Undefined))
return ctx
def empty_context():
obj = W_Object()
ctx = ExecutionContext([obj],
this = obj,
variable = obj,
jsproperty = Property('', w_Undefined))
return ctx
class W_Reference(W_Root):
"""Reference Type"""
def __init__(self, property_name, base=None):
self.base = base
self.property_name = property_name
def GetValue(self):
if self.base is None:
exception = "ReferenceError: %s is not defined"%(self.property_name,)
raise ThrowException(W_String(exception))
return self.base.Get(self.property_name)
def PutValue(self, w, ctx):
base = self.base
if base is None:
base = ctx.scope[-1]
base.Put(self.property_name, w)
return w
def GetBase(self):
return self.base
def GetPropertyName(self):
return self.property_name
def __str__(self):
return "<" + str(self.base) + " -> " + str(self.property_name) + ">"
def create_object(ctx, prototypename, callfunc=None, Value=w_Undefined):
proto = ctx.get_global().Get(prototypename).Get('prototype')
obj = W_Object(ctx, callfunc = callfunc,Prototype=proto,
Class = proto.Class, Value = Value)
return obj
def isnull_or_undefined(obj):
if isinstance(obj, W_Undefined) or isinstance(obj, W_Null):
return True
else:
return False
| Python |
#!/usr/bin/env python
# encoding: utf-8
"""
js_interactive.py
"""
import autopath
import sys
import getopt
from pypy.lang.js.interpreter import load_source, Interpreter, load_file
from pypy.lang.js.jsparser import parse, ParseError
from pypy.lang.js.jsobj import W_Builtin, W_String, ThrowException, w_Undefined
from pypy.rlib.streamio import open_file_as_stream
import code
sys.ps1 = 'js> '
sys.ps2 = '... '
try:
# Setup Readline
import readline
import os
histfile = os.path.join(os.environ["HOME"], ".jspypyhist")
try:
getattr(readline, "clear_history", lambda : None)()
readline.read_history_file(histfile)
except IOError:
pass
import atexit
atexit.register(readline.write_history_file, histfile)
except ImportError:
pass
def loadjs(ctx, args, this):
filename = args[0].ToString()
t = load_file(filename)
return t.execute(ctx)
def tracejs(ctx, args, this):
arguments = args
import pdb
pdb.set_trace()
def quitjs(ctx, args, this):
sys.exit(0)
class JSInterpreter(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>"):
code.InteractiveConsole.__init__(self, locals, filename)
self.interpreter = Interpreter()
self.interpreter.w_Global.Put('quit', W_Builtin(quitjs))
self.interpreter.w_Global.Put('load', W_Builtin(loadjs))
self.interpreter.w_Global.Put('trace', W_Builtin(tracejs))
def runcodefromfile(self, filename):
f = open_file_as_stream(filename)
self.runsource(f.readall())
f.close()
def runcode(self, ast):
"""Run the javascript code in the AST. All exceptions raised
by javascript code must be caught and handled here. When an
exception occurs, self.showtraceback() is called to display a
traceback.
"""
try:
res = self.interpreter.run(ast)
if res not in (None, w_Undefined):
try:
print res.GetValue().ToString(self.interpreter.w_Global)
except ThrowException, exc:
print exc.exception.ToString(self.interpreter.w_Global)
except SystemExit:
raise
except ThrowException, exc:
self.showtraceback(exc)
else:
if code.softspace(sys.stdout, 0):
print
def runsource(self, source, filename="<input>"):
"""Parse and run source in the interpreter.
One of these cases can happen:
1) The input is incorrect. Prints a nice syntax error message.
2) The input in incomplete. More input is required. Returns None.
3) The input is complete. Executes the source code.
"""
try:
ast = load_source(source)
except ParseError, exc:
if exc.source_pos.i == len(source):
# Case 2
return True # True means that more input is needed
else:
# Case 1
self.showsyntaxerror(filename, exc)
return False
# Case 3
self.runcode(ast)
return False
def showtraceback(self, exc):
# XXX format exceptions nicier
print exc.exception.ToString()
def showsyntaxerror(self, filename, exc):
# XXX format syntax errors nicier
print ' '*4 + \
' '*exc.source_pos.columnno + \
'^'
print 'Syntax Error'
def interact(self, banner=None):
if banner is None:
banner = 'PyPy JavaScript Interpreter'
code.InteractiveConsole.interact(self, banner)
def main(inspect=False, files=[]):
jsi = JSInterpreter()
for filename in files:
jsi.runcodefromfile(filename)
if (not files) or inspect:
jsi.interact()
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser(usage='%prog [options] [files] ...',
description='PyPy JavaScript Interpreter')
parser.add_option('-i', dest='inspect',
action='store_true', default=False,
help='inspect interactively after running script')
# ... (add other options)
opts, args = parser.parse_args()
if args:
main(inspect=opts.inspect, files=args)
else:
main(inspect=opts.inspect)
sys.exit(0)
| Python |
import py
from pypy.lang.js.interpreter import *
from pypy.lang.js.jsobj import W_Array, JsBaseExcept
from pypy.rlib.parsing.parsing import ParseError
from py.__.test.outcome import Failed, ExceptionFailure
import pypy.lang.js as js
from pypy.lang.js import interpreter
interpreter.TEST = True
rootdir = py.magic.autopath().dirpath()
exclusionlist = ['shell.js', 'browser.js']
class JSDirectory(py.test.collect.Directory):
def filefilter(self, path):
if not py.test.config.option.ecma:
return False
if path.check(file=1):
return (path.basename not in exclusionlist) and (path.ext == '.js')
def join(self, name):
if not name.endswith('.js'):
return super(Directory, self).join(name)
p = self.fspath.join(name)
if p.check(file=1):
return JSTestFile(p, parent=self)
class JSTestFile(py.test.collect.Module):
def init_interp(cls):
if hasattr(cls, 'interp'):
cls.testcases.PutValue(W_Array(), cls.interp.global_context)
cls.tc.PutValue(W_Number(0), cls.interp.global_context)
cls.interp = Interpreter()
ctx = cls.interp.global_context
shellpath = rootdir/'shell.js'
t = load_file(str(shellpath))
t.execute(ctx)
cls.testcases = cls.interp.global_context.resolve_identifier('testcases')
cls.tc = cls.interp.global_context.resolve_identifier('tc')
init_interp = classmethod(init_interp)
def __init__(self, fspath, parent=None):
super(JSTestFile, self).__init__(fspath, parent)
self.name = fspath.purebasename
self.fspath = fspath
def run(self):
if not py.test.config.option.ecma:
py.test.skip("ECMA tests disabled, run with --ecma")
if py.test.config.option.collectonly:
return
self.init_interp()
#actually run the file :)
t = load_file(str(self.fspath))
try:
t.execute(self.interp.global_context)
except ParseError, e:
raise Failed(msg=e.nice_error_message(filename=str(self.fspath)), excinfo=None)
except JsBaseExcept:
raise Failed(msg="Javascript Error", excinfo=py.code.ExceptionInfo())
except:
raise Failed(excinfo=py.code.ExceptionInfo())
testcases = self.interp.global_context.resolve_identifier('testcases')
self.tc = self.interp.global_context.resolve_identifier('tc')
testcount = testcases.GetValue().Get('length').GetValue().ToInt32()
self.testcases = testcases
return range(testcount)
def join(self, number):
return JSTestItem(number, parent = self)
class JSTestItem(py.test.collect.Item):
def __init__(self, number, parent=None):
super(JSTestItem, self).__init__(str(number), parent)
self.number = number
def run(self):
ctx = JSTestFile.interp.global_context
r3 = ctx.resolve_identifier('run_test').GetValue()
w_test_number = W_Number(self.number)
result = r3.Call(ctx=ctx, args=[w_test_number,]).GetValue().ToString()
if result != "passed":
raise Failed(msg=result)
elif result == -1:
py.test.skip()
_handling_traceback = False
def _getpathlineno(self):
return self.parent.parent.fspath, 0
Directory = JSDirectory
| Python |
" a very stripped down version of cfbolz's algorithm/automaton module "
from pypy.rlib.jit import hint
from pypy.rpython.lltypesystem.lltype import GcArray, Signed, malloc
class DFA(object):
def __init__(self, num_states=0, transitions=None, final_states=None):
self.num_states = 0
self.transitions = {}
self.final_states = {}
def add_state(self, final=False):
state = self.num_states
self.num_states += 1
if final:
self.final_states[state] = None
return self.num_states - 1
def add_transition(self, state, input, next_state):
self.transitions[state, input] = next_state
def get_transition(self, state, input):
return self.transitions[state, input]
def get_language(self):
all_chars = {}
for state, input in self.transitions:
all_chars[input] = None
return all_chars
def __repr__(self):
from pprint import pformat
return "DFA%s" % (pformat(
(self.num_states, self.transitions, self.final_states)))
def getautomaton():
" simple example of handcrafted dfa "
a = DFA()
s0 = a.add_state()
s1 = a.add_state()
s2 = a.add_state(final=True)
a.add_transition(s0, "a", s0)
a.add_transition(s0, "c", s1)
a.add_transition(s0, "b", s2)
a.add_transition(s1, "b", s2)
return a
def recognize(automaton, s):
" a simple recognizer "
state = 0
try:
for char in s:
state = automaton.get_transition(state, char)
except KeyError:
return False
return state in automaton.final_states
def convertdfa(automaton):
""" converts the dfa transitions into a table, represented as a big string.
this is just to make the code more amenable to current state of the JIT. Returns
a two tuple of dfa as table, and final states"""
size = automaton.num_states * 256
dfatable = [chr(255)] * size
for (s, c), r in automaton.transitions.items():
dfatable[s * 256 + ord(c)] = chr(r)
dfatable = "".join(dfatable)
final_states = "".join([chr(fs) for fs in automaton.final_states])
return dfatable, final_states
def recognizetable(dfatable, s, finalstates):
state = 0
indx = 0
while True:
hint(None, global_merge_point=True)
if indx >= len(s):
break
c = s[indx]
c = hint(c, promote=True)
state = ord(dfatable[state * 256 + ord(c)])
hint(state, concrete=True)
if state == 255:
break
indx += 1
# more strange code for now - check final state?
res = 0
indx = 0
while True:
if indx >= len(finalstates):
break
fs = ord(finalstates[indx])
fs = hint(fs, concrete=True)
if state == fs:
res = 1
break
indx += 1
res = hint(res, variable=True)
return res
def convertagain(automaton):
alltrans = {}
for (s, c), r in automaton.transitions.items():
statetrans = alltrans.setdefault(s, {})
statetrans[c] = r
return alltrans, automaton.final_states
def recognizeparts(alltrans, finals, s):
" a less simple recognizer "
finals = hint(finals, deepfreeze=True)
alltrans = hint(alltrans, deepfreeze=True)
state = 0
indx = 0
while indx < len(s):
hint(None, global_merge_point=True)
char = s[indx]
indx += 1
char = hint(char, promote=True)
statetrans = alltrans.get(state, None)
state = statetrans.get(char, -1)
hint(state, concrete=True)
if state == -1:
return False
res = state in finals
res = hint(res, concrete=True)
res = hint(res, variable=True)
return res
# a version of recognize() full of hints, but otherwise not too modified
def recognize3(automaton, s):
automaton = hint(automaton, deepfreeze=True)
hint(automaton, concrete=True)
state = 0
index = 0
while index < len(s):
hint(None, global_merge_point=True)
char = s[index]
index += 1
char = hint(char, promote=True)
try:
state = automaton.get_transition(state, char)
except KeyError:
return False
state = hint(state, promote=True)
return state in automaton.final_states
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# type verifications
def impl_nonvar(engine, var):
if isinstance(var, term.Var):
raise error.UnificationFailed()
expose_builtin(impl_nonvar, "nonvar", unwrap_spec=["obj"])
def impl_var(engine, var):
if not isinstance(var, term.Var):
raise error.UnificationFailed()
expose_builtin(impl_var, "var", unwrap_spec=["obj"])
def impl_integer(engine, var):
if isinstance(var, term.Var) or not isinstance(var, term.Number):
raise error.UnificationFailed()
expose_builtin(impl_integer, "integer", unwrap_spec=["obj"])
def impl_float(engine, var):
if isinstance(var, term.Var) or not isinstance(var, term.Float):
raise error.UnificationFailed()
expose_builtin(impl_float, "float", unwrap_spec=["obj"])
def impl_number(engine, var):
if (isinstance(var, term.Var) or
(not isinstance(var, term.Number) and not
isinstance(var, term.Float))):
raise error.UnificationFailed()
expose_builtin(impl_number, "number", unwrap_spec=["obj"])
def impl_atom(engine, var):
if isinstance(var, term.Var) or not isinstance(var, term.Atom):
raise error.UnificationFailed()
expose_builtin(impl_atom, "atom", unwrap_spec=["obj"])
def impl_atomic(engine, var):
if helper.is_atomic(var):
return
raise error.UnificationFailed()
expose_builtin(impl_atomic, "atomic", unwrap_spec=["obj"])
def impl_compound(engine, var):
if isinstance(var, term.Var) or not isinstance(var, term.Term):
raise error.UnificationFailed()
expose_builtin(impl_compound, "compound", unwrap_spec=["obj"])
def impl_callable(engine, var):
if not helper.is_callable(var, engine):
raise error.UnificationFailed()
expose_builtin(impl_callable, "callable", unwrap_spec=["obj"])
def impl_ground(engine, var):
if isinstance(var, term.Var):
raise error.UnificationFailed()
if isinstance(var, term.Term):
for arg in var.args:
impl_ground(engine, arg)
expose_builtin(impl_ground, "ground", unwrap_spec=["concrete"])
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# operators
def impl_current_op(engine, precedence, typ, name, continuation):
for prec, allops in engine.getoperations():
for form, ops in allops:
for op in ops:
oldstate = engine.heap.branch()
try:
precedence.unify(term.Number(prec), engine.heap)
typ.unify(term.Atom.newatom(form), engine.heap)
name.unify(term.Atom(op), engine.heap)
return continuation.call(engine, choice_point=True)
except error.UnificationFailed:
engine.heap.revert(oldstate)
raise error.UnificationFailed()
expose_builtin(impl_current_op, "current_op", unwrap_spec=["obj", "obj", "obj"],
handles_continuation=True)
def impl_op(engine, precedence, typ, name):
from pypy.lang.prolog.interpreter import parsing
if engine.operations is None:
engine.operations = parsing.make_default_operations()
operations = engine.operations
precedence_to_ops = {}
for prec, allops in operations:
precedence_to_ops[prec] = allops
for form, ops in allops:
try:
index = ops.index(name)
del ops[index]
except ValueError:
pass
if precedence != 0:
if precedence in precedence_to_ops:
allops = precedence_to_ops[precedence]
for form, ops in allops:
if form == typ:
ops.append(name)
break
else:
allops.append((typ, [name]))
else:
for i in range(len(operations)):
(prec, allops) = operations[i]
if precedence > prec:
operations.insert(i, (precedence, [(typ, [name])]))
break
else:
operations.append((precedence, [(typ, [name])]))
engine.parser = parsing.make_parser_at_runtime(engine.operations)
expose_builtin(impl_op, "op", unwrap_spec=["int", "atom", "atom"])
| Python |
import py
from pypy.lang.prolog.interpreter.parsing import parse_file, TermBuilder
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# control predicates
def impl_fail(engine):
raise error.UnificationFailed()
expose_builtin(impl_fail, "fail", unwrap_spec=[])
def impl_true(engine):
return
expose_builtin(impl_true, "true", unwrap_spec=[])
def impl_repeat(engine, continuation):
while 1:
try:
return continuation.call(engine, choice_point=True)
except error.UnificationFailed:
pass
expose_builtin(impl_repeat, "repeat", unwrap_spec=[], handles_continuation=True)
def impl_cut(engine, continuation):
raise error.CutException(continuation)
expose_builtin(impl_cut, "!", unwrap_spec=[],
handles_continuation=True)
class AndContinuation(engine.Continuation):
def __init__(self, next_call, continuation):
self.next_call = next_call
self.continuation = continuation
def _call(self, engine):
next_call = self.next_call.dereference(engine.heap)
next_call = helper.ensure_callable(next_call)
return engine.call(next_call, self.continuation, choice_point=False)
def impl_and(engine, call1, call2, continuation):
if not isinstance(call2, term.Var) and not isinstance(call2, term.Callable):
error.throw_type_error('callable', call2)
and_continuation = AndContinuation(call2, continuation)
return engine.call(call1, and_continuation, choice_point=False)
expose_builtin(impl_and, ",", unwrap_spec=["callable", "raw"],
handles_continuation=True)
def impl_or(engine, call1, call2, continuation):
oldstate = engine.heap.branch()
try:
return engine.call(call1, continuation)
except error.UnificationFailed:
engine.heap.revert(oldstate)
return engine.call(call2, continuation, choice_point=False)
expose_builtin(impl_or, ";", unwrap_spec=["callable", "callable"],
handles_continuation=True)
def impl_not(engine, call):
try:
try:
engine.call(call)
except error.CutException, e:
engine.continue_after_cut(e.continuation)
except error.UnificationFailed:
return None
raise error.UnificationFailed()
expose_builtin(impl_not, ["not", "\\+"], unwrap_spec=["callable"])
def impl_if(engine, if_clause, then_clause, continuation):
oldstate = engine.heap.branch()
try:
engine.call(if_clause)
except error.UnificationFailed:
engine.heap.revert(oldstate)
raise
return engine.call(helper.ensure_callable(then_clause), continuation,
choice_point=False)
expose_builtin(impl_if, "->", unwrap_spec=["callable", "raw"],
handles_continuation=True)
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# meta-call predicates
def impl_call(engine, call, continuation):
try:
return engine.call(call, continuation)
except error.CutException, e:
return e.continuation.call(engine, choice_point=False)
expose_builtin(impl_call, "call", unwrap_spec=["callable"],
handles_continuation=True)
def impl_once(engine, clause, continuation):
engine.call(clause)
return continuation.call(engine, choice_point=False)
expose_builtin(impl_once, "once", unwrap_spec=["callable"],
handles_continuation=True)
| Python |
import py
from pypy.lang.prolog.interpreter import arithmetic
from pypy.lang.prolog.interpreter.parsing import parse_file, TermBuilder
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# comparison and unification of terms
def impl_unify(engine, obj1, obj2):
obj1.unify(obj2, engine.heap)
expose_builtin(impl_unify, "=", unwrap_spec=["raw", "raw"])
def impl_unify_with_occurs_check(engine, obj1, obj2):
obj1.unify(obj2, engine.heap, occurs_check=True)
expose_builtin(impl_unify_with_occurs_check, "unify_with_occurs_check",
unwrap_spec=["raw", "raw"])
def impl_does_not_unify(engine, obj1, obj2):
try:
branch = engine.heap.branch()
try:
obj1.unify(obj2, engine.heap)
finally:
engine.heap.revert(branch)
except error.UnificationFailed:
return
raise error.UnificationFailed()
expose_builtin(impl_does_not_unify, "\\=", unwrap_spec=["raw", "raw"])
for ext, prolog, python in [("eq", "==", "== 0"),
("ne", "\\==", "!= 0"),
("lt", "@<", "== -1"),
("le", "@=<", "!= 1"),
("gt", "@>", "== 1"),
("ge", "@>=", "!= -1")]:
exec py.code.Source("""
def impl_standard_comparison_%s(engine, obj1, obj2):
c = term.cmp_standard_order(obj1, obj2, engine.heap)
if not c %s:
raise error.UnificationFailed()""" % (ext, python)).compile()
expose_builtin(globals()["impl_standard_comparison_%s" % (ext, )], prolog,
unwrap_spec=["obj", "obj"])
| Python |
import os
import string
from pypy.lang.prolog.interpreter.term import Term, Float, Number, Var, Atom
from pypy.lang.prolog.interpreter import error, helper, parsing
from pypy.lang.prolog.builtin.register import expose_builtin
class TermFormatter(object):
def __init__(self, engine, quoted=False, max_depth=0,
ignore_ops=False):
self.engine = engine
self.quoted = quoted
self.max_depth = max_depth
self.ignore_ops = ignore_ops
self.curr_depth = 0
self._make_reverse_op_mapping()
self.var_to_number = {}
def from_option_list(engine, options):
# XXX add numbervars support
quoted = False
max_depth = 0
ignore_ops = False
number_vars = False
for option in options:
if (not isinstance(option, Term) or len(option.args) != 1):
error.throw_domain_error('write_option', option)
arg = option.args[0]
if option.name == "max_depth":
try:
max_depth = helper.unwrap_int(arg)
except error.CatchableError:
error.throw_domain_error('write_option', option)
elif (not isinstance(arg, Atom) or
(arg.name != "true" and arg.name != "false")):
error.throw_domain_error('write_option', option)
assert 0, "unreachable"
elif option.name == "quoted":
quoted = arg.name == "true"
elif option.name == "ignore_ops":
ignore_ops = arg.name == "true"
return TermFormatter(engine, quoted, max_depth, ignore_ops)
from_option_list = staticmethod(from_option_list)
def format(self, term):
self.curr_depth += 1
if self.max_depth > 0 and self.curr_depth > self.max_depth:
return "..."
if isinstance(term, Atom):
return self.format_atom(term.name)
elif isinstance(term, Number):
return self.format_number(term)
elif isinstance(term, Float):
return self.format_float(term)
elif isinstance(term, Term):
return self.format_term(term)
elif isinstance(term, Var):
return self.format_var(term)
def format_atom(self, s):
from pypy.rlib.parsing.deterministic import LexerError
if self.quoted:
try:
tokens = parsing.lexer.tokenize(s)
if (len(tokens) == 1 and tokens[0].name == 'ATOM' and
tokens[0].source == s):
return s
except LexerError:
pass
return "'%s'" % (s, )
return s
def format_number(self, num):
return str(num.num)
def format_float(self, num):
return str(num.floatval)
def format_var(self, var):
try:
num = self.var_to_number[var]
except KeyError:
num = self.var_to_number[var] = len(self.var_to_number)
return "_G%s" % (num, )
def format_term_normally(self, term):
return "%s(%s)" % (self.format_atom(term.name),
", ".join([self.format(a) for a in term.args]))
def format_term(self, term):
if self.ignore_ops:
return self.format_term_normally(term)
else:
return self.format_with_ops(term)[1]
def format_with_ops(self, term):
if not isinstance(term, Term):
return (0, self.format(term))
if term.signature == "./2":
result = ["["]
while isinstance(term, Term) and term.signature == "./2":
first = term.args[0]
second = term.args[1]
result.append(self.format(first))
result.append(", ")
term = second
if isinstance(term, Atom) and term.name == "[]":
result[-1] = "]"
else:
result[-1] = "|"
result.append(self.format(term))
result.append("]")
return (0, "".join(result))
if (len(term.args), term.name) not in self.op_mapping:
return (0, self.format_term_normally(term))
form, prec = self.op_mapping[(len(term.args), term.name)]
result = []
assert 0 <= len(term.args) <= 2
curr_index = 0
for c in form:
if c == "f":
result.append(self.format_atom(term.name))
else:
childprec, child = self.format_with_ops(term.args[curr_index])
parentheses = (c == "x" and childprec >= prec or
c == "y" and childprec > prec)
if parentheses:
result.append("(")
result.append(child)
result.append(")")
else:
result.append(child)
curr_index += 1
assert curr_index == len(term.args)
return (prec, "".join(result))
def _make_reverse_op_mapping(self):
m = {}
for prec, allops in self.engine.getoperations():
for form, ops in allops:
for op in ops:
m[len(form) - 1, op] = (form, prec)
self.op_mapping = m
def impl_write_term(engine, term, options):
f = TermFormatter.from_option_list(engine, options)
os.write(1, f.format(term)) # XXX use streams
expose_builtin(impl_write_term, "write_term", unwrap_spec=["concrete", "list"])
def impl_nl(engine):
os.write(1, "\n") # XXX use streams
expose_builtin(impl_nl, "nl", unwrap_spec=[])
def impl_write(engine, term):
impl_write_term(engine, term, [])
expose_builtin(impl_write, "write", unwrap_spec=["raw"])
| Python |
import py
from pypy.lang.prolog.interpreter.parsing import parse_file, TermBuilder
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin import builtins, builtins_list
from pypy.rlib.objectmodel import we_are_translated
class Builtin(object):
_immutable_ = True
def __init__(self, function, name, numargs, signature):
self.function = function
self.name = name
self.numargs = numargs
self.signature = signature
def call(self, engine, query, continuation):
return self.function(engine, query, continuation)
def _freeze_(self):
return True
def expose_builtin(func, name, unwrap_spec=None, handles_continuation=False,
translatable=True):
if isinstance(name, list):
expose_as = name
name = name[0]
else:
expose_as = [name]
if not name.isalnum():
name = func.func_name
funcname = "wrap_%s_%s" % (name, len(unwrap_spec))
code = ["def %s(engine, query, continuation):" % (funcname, )]
if not translatable:
code.append(" if we_are_translated():")
code.append(" raise error.UncatchableError('%s does not work in translated version')" % (name, ))
subargs = ["engine"]
if len(unwrap_spec):
code.append(" assert isinstance(query, term.Term)")
else:
code.append(" assert isinstance(query, term.Atom)")
for i, spec in enumerate(unwrap_spec):
varname = "var%s" % (i, )
subargs.append(varname)
if spec in ("obj", "callable", "int", "atom", "arithmetic"):
code.append(" %s = query.args[%s].dereference(engine.heap)" %
(varname, i))
elif spec in ("concrete", "list"):
code.append(" %s = query.args[%s].getvalue(engine.heap)" %
(varname, i))
if spec in ("int", "atom", "arithmetic", "list"):
code.append(
" if isinstance(%s, term.Var):" % (varname,))
code.append(
" error.throw_instantiation_error()")
if spec == "obj":
pass
elif spec == "concrete":
pass
elif spec == "callable":
code.append(
" if not isinstance(%s, term.Callable):" % (varname,))
code.append(
" error.throw_type_error('callable', %s)" % (varname,))
elif spec == "raw":
code.append(" %s = query.args[%s]" % (varname, i))
elif spec == "int":
code.append(" %s = helper.unwrap_int(%s)" % (varname, varname))
elif spec == "atom":
code.append(" %s = helper.unwrap_atom(%s)" % (varname, varname))
elif spec == "arithmetic":
code.append(" %s = %s.eval_arithmetic(engine)" %
(varname, varname))
elif spec == "list":
code.append(" %s = helper.unwrap_list(%s)" % (varname, varname))
else:
assert 0, "not implemented " + spec
if handles_continuation:
subargs.append("continuation")
call = " result = %s(%s)" % (func.func_name, ", ".join(subargs))
code.append(call)
if not handles_continuation:
code.append(" return continuation.call(engine, choice_point=False)")
else:
code.append(" return result")
miniglobals = globals().copy()
miniglobals[func.func_name] = func
exec py.code.Source("\n".join(code)).compile() in miniglobals
for name in expose_as:
signature = "%s/%s" % (name, len(unwrap_spec))
b = Builtin(miniglobals[funcname], funcname, len(unwrap_spec),
signature)
builtins[signature] = b
if signature in [",/2", "is/2"]:
builtins_list.insert(0, (signature, b))
else:
builtins_list.append((signature, b))
| Python |
import py
from pypy.lang.prolog.interpreter import engine as enginemod, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
from pypy.lang.prolog.builtin.type import impl_ground
# ___________________________________________________________________
# exception handling
def impl_catch(engine, goal, catcher, recover, continuation):
catching_continuation = enginemod.LimitedScopeContinuation(continuation)
old_state = engine.heap.branch()
try:
return engine.call(goal, catching_continuation)
except error.CatchableError, e:
if not catching_continuation.scope_active:
raise
exc_term = e.term.getvalue(engine.heap)
engine.heap.revert(old_state)
d = {}
exc_term = exc_term.copy(engine.heap, d)
try:
impl_ground(engine, exc_term)
except error.UnificationFailed:
raise error.UncatchableError(
"not implemented: catching of non-ground terms")
try:
catcher.unify(exc_term, engine.heap)
except error.UnificationFailed:
if isinstance(e, error.UserError):
raise error.UserError(exc_term)
if isinstance(e, error.CatchableError):
raise error.CatchableError(exc_term)
return engine.call(recover, continuation, choice_point=False)
expose_builtin(impl_catch, "catch", unwrap_spec=["callable", "obj", "callable"],
handles_continuation=True)
def impl_throw(engine, exc):
try:
impl_ground(engine, exc)
except error.UnificationFailed:
raise error.UncatchableError(
"not implemented: raising of non-ground terms")
raise error.UserError(exc)
expose_builtin(impl_throw, "throw", unwrap_spec=["obj"])
| Python |
import py
from pypy.lang.prolog.interpreter import arithmetic
from pypy.lang.prolog.interpreter.parsing import parse_file, TermBuilder
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.interpreter.error import UnificationFailed, FunctionNotFound
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# loading prolog source files
def impl_consult(engine, var):
import os
if isinstance(var, term.Atom):
try:
fd = os.open(var.name, os.O_RDONLY, 0777)
except OSError, e:
error.throw_existence_error("source_sink", var)
assert 0, "unreachable" # make the flow space happy
try:
content = []
while 1:
s = os.read(fd, 4096)
if not s:
break
content.append(s)
file_content = "".join(content)
finally:
os.close(fd)
engine.runstring(file_content)
expose_builtin(impl_consult, "consult", unwrap_spec=["obj"])
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# finding all solutions to a goal
class FindallContinuation(engine.Continuation):
def __init__(self, template):
self.found = []
self.template = template
def _call(self, engine):
clone = self.template.getvalue(engine.heap)
self.found.append(clone)
raise error.UnificationFailed()
def impl_findall(engine, template, goal, bag):
oldstate = engine.heap.branch()
collector = FindallContinuation(template)
try:
engine.call(goal, collector)
except error.UnificationFailed:
engine.heap.revert(oldstate)
result = term.Atom.newatom("[]")
for i in range(len(collector.found) - 1, -1, -1):
copy = collector.found[i]
d = {}
copy = copy.copy(engine.heap, d)
result = term.Term(".", [copy, result])
bag.unify(result, engine.heap)
expose_builtin(impl_findall, "findall", unwrap_spec=['raw', 'callable', 'raw'])
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# arithmetic
def impl_between(engine, lower, upper, varorint, continuation):
if isinstance(varorint, term.Var):
for i in range(lower, upper):
oldstate = engine.heap.branch()
try:
varorint.unify(term.Number(i), engine.heap)
return continuation.call(engine, choice_point=True)
except error.UnificationFailed:
engine.heap.revert(oldstate)
varorint.unify(term.Number(upper), engine.heap)
return continuation.call(engine, choice_point=False)
else:
integer = helper.unwrap_int(varorint)
if not (lower <= integer <= upper):
raise error.UnificationFailed
return continuation.call(engine, choice_point=False)
expose_builtin(impl_between, "between", unwrap_spec=["int", "int", "obj"],
handles_continuation=True)
def impl_is(engine, var, num):
var.unify(num, engine.heap)
impl_is._look_inside_me_ = True
expose_builtin(impl_is, "is", unwrap_spec=["raw", "arithmetic"])
for ext, prolog, python in [("eq", "=:=", "=="),
("ne", "=\\=", "!="),
("lt", "<", "<"),
("le", "=<", "<="),
("gt", ">", ">"),
("ge", ">=", ">=")]:
exec py.code.Source("""
def impl_arith_%s(engine, num1, num2):
eq = False
if isinstance(num1, term.Number):
if isinstance(num2, term.Number):
eq = num1.num %s num2.num
elif isinstance(num1, term.Float):
if isinstance(num2, term.Float):
eq = num1.floatval %s num2.floatval
if not eq:
raise error.UnificationFailed()""" % (ext, python, python)).compile()
expose_builtin(globals()["impl_arith_%s" % (ext, )], prolog,
unwrap_spec=["arithmetic", "arithmetic"])
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# analysing and construction atoms
def impl_atom_concat(engine, a1, a2, result, continuation):
if isinstance(a1, term.Var):
if isinstance(a2, term.Var):
# nondeterministic splitting of result
r = helper.convert_to_str(result)
for i in range(len(r) + 1):
oldstate = engine.heap.branch()
try:
a1.unify(term.Atom(r[:i]), engine.heap)
a2.unify(term.Atom(r[i:]), engine.heap)
return continuation.call(engine, choice_point=True)
except error.UnificationFailed:
engine.heap.revert(oldstate)
raise error.UnificationFailed()
else:
s2 = helper.convert_to_str(a2)
r = helper.convert_to_str(result)
if r.endswith(s2):
stop = len(r) - len(s2)
assert stop > 0
a1.unify(term.Atom(r[:stop]), engine.heap)
else:
raise error.UnificationFailed()
else:
s1 = helper.convert_to_str(a1)
if isinstance(a2, term.Var):
r = helper.convert_to_str(result)
if r.startswith(s1):
a2.unify(term.Atom(r[len(s1):]), engine.heap)
else:
raise error.UnificationFailed()
else:
s2 = helper.convert_to_str(a2)
result.unify(term.Atom(s1 + s2), engine.heap)
return continuation.call(engine, choice_point=False)
expose_builtin(impl_atom_concat, "atom_concat",
unwrap_spec=["obj", "obj", "obj"],
handles_continuation=True)
def impl_atom_length(engine, s, length):
if not (isinstance(length, term.Var) or isinstance(length, term.Number)):
error.throw_type_error("integer", length)
term.Number(len(s)).unify(length, engine.heap)
expose_builtin(impl_atom_length, "atom_length", unwrap_spec = ["atom", "obj"])
def impl_sub_atom(engine, s, before, length, after, sub, continuation):
# XXX can possibly be optimized
if isinstance(length, term.Var):
startlength = 0
stoplength = len(s) + 1
else:
startlength = helper.unwrap_int(length)
stoplength = startlength + 1
if startlength < 0:
startlength = 0
stoplength = len(s) + 1
if isinstance(before, term.Var):
startbefore = 0
stopbefore = len(s) + 1
else:
startbefore = helper.unwrap_int(before)
stopbefore = startbefore + 1
if startbefore < 0:
startbefore = 0
stopbefore = len(s) + 1
oldstate = engine.heap.branch()
if not isinstance(sub, term.Var):
s1 = helper.unwrap_atom(sub)
if len(s1) >= stoplength or len(s1) < startlength:
raise error.UnificationFailed()
start = startbefore
while True:
try:
try:
b = s.find(s1, start, stopbefore + len(s1)) # XXX -1?
if b < 0:
break
start = b + 1
before.unify(term.Number(b), engine.heap)
after.unify(term.Number(len(s) - len(s1) - b), engine.heap)
length.unify(term.Number(len(s1)), engine.heap)
return continuation.call(engine, choice_point=True)
except:
engine.heap.revert(oldstate)
raise
except error.UnificationFailed:
pass
raise error.UnificationFailed()
if isinstance(after, term.Var):
for b in range(startbefore, stopbefore):
for l in range(startlength, stoplength):
if l + b > len(s):
continue
try:
try:
before.unify(term.Number(b), engine.heap)
after.unify(term.Number(len(s) - l - b), engine.heap)
length.unify(term.Number(l), engine.heap)
sub.unify(term.Atom(s[b:b + l]), engine.heap)
return continuation.call(engine, choice_point=True)
except:
engine.heap.revert(oldstate)
raise
except error.UnificationFailed:
pass
else:
a = helper.unwrap_int(after)
for l in range(startlength, stoplength):
b = len(s) - l - a
assert b >= 0
if l + b > len(s):
continue
try:
try:
before.unify(term.Number(b), engine.heap)
after.unify(term.Number(a), engine.heap)
length.unify(term.Number(l), engine.heap)
sub.unify(term.Atom(s[b:b + l]), engine.heap)
return continuation.call(engine, choice_point=True)
return None
except:
engine.heap.revert(oldstate)
raise
except error.UnificationFailed:
pass
raise error.UnificationFailed()
expose_builtin(impl_sub_atom, "sub_atom",
unwrap_spec=["atom", "obj", "obj", "obj", "obj"],
handles_continuation=True)
| Python |
# all builtins
builtins = {}
builtins_list = []
# imports to register builtins
import pypy.lang.prolog.builtin.allsolution
import pypy.lang.prolog.builtin.arithmeticbuiltin
import pypy.lang.prolog.builtin.atomconstruction
import pypy.lang.prolog.builtin.control
import pypy.lang.prolog.builtin.database
import pypy.lang.prolog.builtin.exception
import pypy.lang.prolog.builtin.formatting
import pypy.lang.prolog.builtin.metacall
import pypy.lang.prolog.builtin.parseraccess
import pypy.lang.prolog.builtin.source
import pypy.lang.prolog.builtin.termconstruction
import pypy.lang.prolog.builtin.unify
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# database
def impl_abolish(engine, predicate):
from pypy.lang.prolog.builtin import builtins
name, arity = helper.unwrap_predicate_indicator(predicate)
if arity < 0:
error.throw_domain_error("not_less_than_zero", term.Number(arity))
signature = name + "/" + str(arity)
if signature in builtins:
error.throw_permission_error("modify", "static_procedure",
predicate)
if signature in engine.signature2function:
del engine.signature2function[signature]
expose_builtin(impl_abolish, "abolish", unwrap_spec=["obj"])
def impl_assert(engine, rule):
engine.add_rule(rule.getvalue(engine.heap))
expose_builtin(impl_assert, ["assert", "assertz"], unwrap_spec=["callable"])
def impl_asserta(engine, rule):
engine.add_rule(rule.getvalue(engine.heap), end=False)
expose_builtin(impl_asserta, "asserta", unwrap_spec=["callable"])
def impl_retract(engine, pattern):
from pypy.lang.prolog.builtin import builtins
if isinstance(pattern, term.Term) and pattern.name == ":-":
head = helper.ensure_callable(pattern.args[0])
body = helper.ensure_callable(pattern.args[1])
else:
head = pattern
body = None
if head.signature in builtins:
assert isinstance(head, term.Callable)
error.throw_permission_error("modify", "static_procedure",
head.get_prolog_signature())
function = engine.signature2function.get(head.signature, None)
if function is None:
raise error.UnificationFailed
#import pdb; pdb.set_trace()
rulechain = function.rulechain
while rulechain:
rule = rulechain.rule
oldstate = engine.heap.branch()
# standardizing apart
try:
deleted_body = rule.clone_and_unify_head(engine.heap, head)
if body is not None:
body.unify(deleted_body, engine.heap)
except error.UnificationFailed:
engine.heap.revert(oldstate)
else:
if function.rulechain is rulechain:
if rulechain.next is None:
del engine.signature2function[head.signature]
else:
function.rulechain = rulechain.next
else:
function.remove(rulechain)
break
rulechain = rulechain.next
else:
raise error.UnificationFailed()
expose_builtin(impl_retract, "retract", unwrap_spec=["callable"])
| Python |
import py
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.builtin.register import expose_builtin
# ___________________________________________________________________
# analysing and construction terms
def impl_functor(engine, t, functor, arity):
if helper.is_atomic(t):
functor.unify(t, engine.heap)
arity.unify(term.Number(0), engine.heap)
elif isinstance(t, term.Term):
functor.unify(term.Atom(t.name), engine.heap)
arity.unify(term.Number(len(t.args)), engine.heap)
elif isinstance(t, term.Var):
if isinstance(functor, term.Var):
error.throw_instantiation_error()
a = helper.unwrap_int(arity)
if a < 0:
error.throw_domain_error("not_less_than_zero", arity)
else:
functor = helper.ensure_atomic(functor)
if a == 0:
t.unify(helper.ensure_atomic(functor), engine.heap)
else:
name = helper.unwrap_atom(functor)
t.unify(
term.Term(name, [term.Var() for i in range(a)]),
engine.heap)
expose_builtin(impl_functor, "functor", unwrap_spec=["obj", "obj", "obj"])
def impl_arg(engine, first, second, third, continuation):
if isinstance(second, term.Var):
error.throw_instantiation_error()
if isinstance(second, term.Atom):
raise error.UnificationFailed()
if not isinstance(second, term.Term):
error.throw_type_error("compound", second)
if isinstance(first, term.Var):
for i in range(len(second.args)):
arg = second.args[i]
oldstate = engine.heap.branch()
try:
third.unify(arg, engine.heap)
first.unify(term.Number(i + 1), engine.heap)
return continuation.call(engine, choice_point=True)
except error.UnificationFailed:
engine.heap.revert(oldstate)
raise error.UnificationFailed()
elif isinstance(first, term.Number):
num = first.num
if num == 0:
raise error.UnificationFailed
if num < 0:
error.throw_domain_error("not_less_than_zero", first)
if num > len(second.args):
raise error.UnificationFailed()
arg = second.args[num - 1]
third.unify(arg, engine.heap)
else:
error.throw_type_error("integer", first)
return continuation.call(engine, choice_point=False)
expose_builtin(impl_arg, "arg", unwrap_spec=["obj", "obj", "obj"],
handles_continuation=True)
def impl_univ(engine, first, second):
if not isinstance(first, term.Var):
if isinstance(first, term.Term):
l = [term.Atom(first.name)] + first.args
else:
l = [first]
u1 = helper.wrap_list(l)
if not isinstance(second, term.Var):
u1.unify(second, engine.heap)
else:
u1.unify(second, engine.heap)
else:
if isinstance(second, term.Var):
error.throw_instantiation_error()
else:
l = helper.unwrap_list(second)
head = l[0]
if not isinstance(head, term.Atom):
error.throw_type_error("atom", head)
term.Term(head.name, l[1:]).unify(first, engine.heap)
expose_builtin(impl_univ, "=..", unwrap_spec=["obj", "obj"])
def impl_copy_term(engine, interm, outterm):
d = {}
copy = interm.copy(engine.heap, d)
outterm.unify(copy, engine.heap)
expose_builtin(impl_copy_term, "copy_term", unwrap_spec=["obj", "obj"])
| Python |
import os, sys
from pypy.rlib.parsing.parsing import ParseError
from pypy.rlib.parsing.deterministic import LexerError
from pypy.lang.prolog.interpreter.interactive import helptext
from pypy.lang.prolog.interpreter.parsing import parse_file, get_query_and_vars
from pypy.lang.prolog.interpreter.parsing import get_engine
from pypy.lang.prolog.interpreter.engine import Engine
from pypy.lang.prolog.interpreter.engine import Continuation
from pypy.lang.prolog.interpreter import error, term
import pypy.lang.prolog.interpreter.term
pypy.lang.prolog.interpreter.term.DEBUG = False
class StopItNow(Exception):
pass
class ContinueContinuation(Continuation):
def __init__(self, var_to_pos, write):
self.var_to_pos = var_to_pos
self.write = write
def _call(self, engine):
self.write("yes\n")
var_representation(self.var_to_pos, engine, self.write)
while 1:
res = getch()
#self.write(res+"\n")
if res in "\r\x04\n":
self.write("\n")
raise StopItNow()
if res in ";nr":
raise error.UnificationFailed
elif res in "h?":
self.write(helptext)
elif res in "p":
var_representation(self.var_to_pos, engine, self.write)
else:
self.write('unknown action. press "h" for help\n')
def var_representation(var_to_pos, engine, write):
from pypy.lang.prolog.builtin import formatting
f = formatting.TermFormatter(engine, quoted=True, max_depth=20)
for var, real_var in var_to_pos.iteritems():
if var.startswith("_"):
continue
val = f.format(real_var.getvalue(engine.heap))
write("%s = %s\n" % (var, val))
def getch():
line = readline()
return line[0]
def debug(msg):
os.write(2, "debug: " + msg + '\n')
def printmessage(msg):
os.write(1, msg)
def readline():
result = []
while 1:
s = os.read(0, 1)
result.append(s)
if s == "\n":
break
if s == '':
if len(result) > 1:
break
raise SystemExit
return "".join(result)
def run(goal, var_to_pos, e):
from pypy.lang.prolog.interpreter.error import UnificationFailed, CatchableError
from pypy.lang.prolog.interpreter.error import UncatchableError, UserError
from pypy.lang.prolog.builtin import formatting
f = formatting.TermFormatter(e, quoted=True, max_depth=20)
try:
e.run(goal, ContinueContinuation(var_to_pos, printmessage))
except UnificationFailed:
printmessage("no\n")
except UncatchableError, e:
printmessage("INTERNAL ERROR: %s\n" % (e.message, ))
except UserError, e:
printmessage("ERROR: ")
f._make_reverse_op_mapping()
printmessage("Unhandled exception: ")
printmessage(f.format(e.term))
except CatchableError, e:
f._make_reverse_op_mapping()
printmessage("ERROR: ")
t = e.term
if isinstance(t, term.Term):
errorterm = t.args[0]
if isinstance(errorterm, term.Callable):
if errorterm.name == "instantiation_error":
printmessage("arguments not sufficiently instantiated\n")
return
elif errorterm.name == "existence_error":
if isinstance(errorterm, term.Term):
printmessage("Undefined %s: %s\n" % (
f.format(errorterm.args[0]),
f.format(errorterm.args[1])))
return
elif errorterm.name == "domain_error":
if isinstance(errorterm, term.Term):
printmessage(
"Domain error: '%s' expected, found '%s'\n" % (
f.format(errorterm.args[0]),
f.format(errorterm.args[1])))
return
elif errorterm.name == "type_error":
if isinstance(errorterm, term.Term):
printmessage(
"Type error: '%s' expected, found '%s'\n" % (
f.format(errorterm.args[0]),
f.format(errorterm.args[1])))
return
printmessage(" (but I cannot tell you which one)\n")
except StopItNow:
pass
else:
printmessage("yes\n")
def repl(engine):
printmessage("welcome!\n")
while 1:
printmessage(">?- ")
line = readline()
if line == "halt.\n":
break
try:
goals, var_to_pos = engine.parse(line)
except ParseError, exc:
printmessage(exc.nice_error_message("<stdin>", line) + "\n")
continue
except LexerError, exc:
printmessage(exc.nice_error_message("<stdin>") + "\n")
continue
for goal in goals:
run(goal, var_to_pos, engine)
def execute(e, filename):
e.run(term.Term("consult", [term.Atom(filename)]))
if __name__ == '__main__':
e = Engine()
repl(e)
| Python |
from pypy.jit.hintannotator.policy import ManualGraphPolicy
from pypy.lang.prolog.interpreter import term, engine, helper
from pypy.translator.translator import graphof
from pypy.annotation.specialize import getuniquenondirectgraph
forbidden_modules = {'pypy.lang.prolog.interpreter.parser': True,
}
good_modules = {'pypy.lang.prolog.builtin.control': True,
'pypy.lang.prolog.builtin.register': True
}
PORTAL = engine.Engine.portal_try_rule.im_func
class PyrologHintAnnotatorPolicy(ManualGraphPolicy):
PORTAL = PORTAL
def look_inside_graph_of_module(self, graph, func, mod):
if mod in forbidden_modules:
return False
if mod in good_modules:
return True
if mod.startswith("pypy.lang.prolog"):
return False
return True
def fill_timeshift_graphs(self, portal_graph):
import pypy
for cls in [term.Var, term.Term, term.Number, term.Atom]:
self.seegraph(cls.copy)
self.seegraph(cls.__init__)
self.seegraph(cls.copy_and_unify)
for cls in [term.Term, term.Number, term.Atom]:
self.seegraph(cls.copy_and_basic_unify)
self.seegraph(cls.dereference)
self.seegraph(cls.copy_and_basic_unify)
for cls in [term.Var, term.Term, term.Number, term.Atom]:
self.seegraph(cls.get_unify_hash)
self.seegraph(cls.eval_arithmetic)
for cls in [term.Callable, term.Atom, term.Term]:
self.seegraph(cls.get_prolog_signature)
self.seegraph(cls.unify_hash_of_children)
self.seegraph(PORTAL)
self.seegraph(engine.Heap.newvar)
self.seegraph(term.Rule.clone_and_unify_head)
self.seegraph(engine.Engine.call)
self.seegraph(engine.Engine._call)
self.seegraph(engine.Engine.user_call)
self.seegraph(engine.Engine._user_call)
self.seegraph(engine.Engine.try_rule)
self.seegraph(engine.Engine._try_rule)
self.seegraph(engine.Engine.main_loop)
self.seegraph(engine.Engine.dispatch_bytecode)
self.seegraph(engine.LinkedRules.find_applicable_rule)
for method in "branch revert discard newvar extend maxvar".split():
self.seegraph(getattr(engine.Heap, method))
self.seegraph(engine.Continuation.call)
for cls in [engine.Continuation, engine.LimitedScopeContinuation,
pypy.lang.prolog.builtin.control.AndContinuation]:
self.seegraph(cls._call)
for function in "".split():
self.seegraph(getattr(helper, function))
def get_portal(drv):
t = drv.translator
portal = getattr(PORTAL, 'im_func', PORTAL)
policy = PyrologHintAnnotatorPolicy()
policy.seetranslator(t)
return portal, policy
| Python |
class PrologError(Exception):
pass
class CatchableError(PrologError):
def __init__(self, errorterm):
from pypy.lang.prolog.interpreter import term
self.term = term.Term("error", [errorterm])
class UserError(CatchableError):
def __init__(self, errorterm):
self.term = errorterm
class UncatchableError(PrologError):
def __init__(self, message):
self.message = message
class UnificationFailed(PrologError):
pass
class FunctionNotFound(PrologError):
def __init__(self, signature):
self.signature = signature
class CutException(PrologError):
def __init__(self, continuation):
self.continuation = continuation
def throw_instantiation_error():
from pypy.lang.prolog.interpreter import term
raise CatchableError(term.Atom.newatom("instantiation_error"))
def throw_type_error(valid_type, obj):
from pypy.lang.prolog.interpreter import term
# valid types are:
# atom, atomic, byte, callable, character
# evaluable, in_byte, in_character, integer, list
# number, predicate_indicator, variable
from pypy.lang.prolog.interpreter import term
raise CatchableError(
term.Term("type_error", [term.Atom.newatom(valid_type), obj]))
def throw_domain_error(valid_domain, obj):
from pypy.lang.prolog.interpreter import term
# valid domains are:
# character_code_list, close_option, flag_value, io_mode,
# not_empty_list, not_less_than_zero, operator_priority,
# operator_specifier, prolog_flag, read_option, source_sink,
# stream, stream_option, stream_or_alias, stream_position,
# stream_property, write_option
raise CatchableError(
term.Term("domain_error", [term.Atom.newatom(valid_domain), obj]))
def throw_existence_error(object_type, obj):
from pypy.lang.prolog.interpreter import term
# valid types are:
# procedure, source_sink, stream
raise CatchableError(
term.Term("existence_error", [term.Atom.newatom(object_type), obj]))
def throw_permission_error(operation, permission_type, obj):
from pypy.lang.prolog.interpreter import term
# valid operations are:
# access, create, input, modify, open, output, reposition
# valid permission_types are:
# binary_stream, flag, operator, past_end_of_stream, private_procedure,
# static_procedure, source_sink, stream, text_stream.
raise CatchableError(
term.Term("permission_error", [term.Atom.newatom(operation),
term.Atom.newatom(permission_type),
obj]))
| Python |
import py
from pypy.rlib.parsing.ebnfparse import parse_ebnf
from pypy.rlib.parsing.regexparse import parse_regex
from pypy.rlib.parsing.lexer import Lexer, DummyLexer
from pypy.rlib.parsing.deterministic import DFA
from pypy.rlib.parsing.tree import Nonterminal, Symbol, RPythonVisitor
from pypy.rlib.parsing.parsing import PackratParser, LazyParseTable, Rule
from pypy.rlib.parsing.regex import StringExpression
def make_regexes():
regexs = [
("VAR", parse_regex("[A-Z_]([a-zA-Z0-9]|_)*|_")),
("NUMBER", parse_regex("(0|[1-9][0-9]*)(\.[0-9]+)?")),
("IGNORE", parse_regex(
"[ \\n\\t]|(/\\*[^\\*]*(\\*[^/][^\\*]*)*\\*/)|(%[^\\n]*)")),
("ATOM", parse_regex("([a-z]([a-zA-Z0-9]|_)*)|('[^']*')|\[\]|!|\+|\-")),
("(", parse_regex("\(")),
(")", parse_regex("\)")),
("[", parse_regex("\[")),
("]", parse_regex("\]")),
(".", parse_regex("\.")),
("|", parse_regex("\|")),
]
return zip(*regexs)
basic_rules = [
Rule('query', [['toplevel_op_expr', '.', 'EOF']]),
Rule('fact', [['toplevel_op_expr', '.']]),
Rule('complexterm', [['ATOM', '(', 'toplevel_op_expr', ')'], ['expr']]),
Rule('expr',
[['VAR'],
['NUMBER'],
['+', 'NUMBER'],
['-', 'NUMBER'],
['ATOM'],
['(', 'toplevel_op_expr', ')'],
['listexpr'],
]),
Rule('listexpr', [['[', 'listbody', ']']]),
Rule('listbody',
[['toplevel_op_expr', '|', 'toplevel_op_expr'],
['toplevel_op_expr']])
]
# x: term with priority lower than f
# y: term with priority lower or equal than f
# possible types: xf yf xfx xfy yfx yfy fy fx
# priorities: A > B
#
# binaryops
# (1) xfx: A -> B f B | B
# (2) xfy: A -> B f A | B
# (3) yfx: A -> A f B | B
# (4) yfy: A -> A f A | B
#
# unaryops
# (5) fx: A -> f A | B
# (6) fy: A -> f B | B
# (7) xf: A -> B f | B
# (8) yf: A -> A f | B
def make_default_operations():
operations = [
(1200, [("xfx", ["-->", ":-"]),
("fx", [":-", "?-"])]),
(1100, [("xfy", [";"])]),
(1050, [("xfy", ["->"])]),
(1000, [("xfy", [","])]),
(900, [("fy", ["\\+"]),
("fx", ["~"])]),
(700, [("xfx", ["<", "=", "=..", "=@=", "=:=", "=<", "==", "=\=", ">",
">=", "@<", "@=<", "@>", "@>=", "\=", "\==", "is"])]),
(600, [("xfy", [":"])]),
(500, [("yfx", ["+", "-", "/\\", "\\/", "xor"]),
( "fx", ["+", "-", "?", "\\"])]),
(400, [("yfx", ["*", "/", "//", "<<", ">>", "mod", "rem"])]),
(200, [("xfx", ["**"]), ("xfy", ["^"])]),
]
return operations
default_operations = make_default_operations()
import sys
sys.setrecursionlimit(10000)
def make_from_form(form, op, x, y):
result = []
for c in form:
if c == 'x':
result.append(x)
if c == 'y':
result.append(y)
if c == 'f':
result.append(op)
return result
def make_expansion(y, x, allops):
expansions = []
for form, ops in allops:
for op in ops:
expansion = make_from_form(form, op, x, y)
expansions.append(expansion)
expansions.append([x])
return expansions
def eliminate_immediate_left_recursion(symbol, expansions):
newsymbol = "extra%s" % (symbol, )
newexpansions = []
with_recursion = [expansion for expansion in expansions
if expansion[0] == symbol]
without_recursion = [expansion for expansion in expansions
if expansion[0] != symbol]
expansions = [expansion + [newsymbol] for expansion in without_recursion]
newexpansions = [expansion[1:] + [newsymbol]
for expansion in with_recursion]
newexpansions.append([])
return expansions, newexpansions, newsymbol
def make_all_rules(standard_rules, operations=None):
if operations is None:
operations = default_operations
all_rules = standard_rules[:]
for i in range(len(operations)):
precedence, allops = operations[i]
if i == 0:
y = "toplevel_op_expr"
else:
y = "expr%s" % (precedence, )
if i != len(operations) - 1:
x = "expr%s" % (operations[i + 1][0], )
else:
x = "complexterm"
expansions = make_expansion(y, x, allops)
tup = eliminate_immediate_left_recursion(y, expansions)
expansions, extra_expansions, extra_symbol = tup
all_rules.append(Rule(extra_symbol, extra_expansions))
all_rules.append(Rule(y, expansions))
return all_rules
def add_necessary_regexs(regexs, names, operations=None):
if operations is None:
operations = default_operations
regexs = regexs[:]
names = names[:]
for precedence, allops in operations:
for form, ops in allops:
for op in ops:
regexs.insert(-1, StringExpression(op))
names.insert(-1, "ATOM")
return regexs, names
class PrologParseTable(LazyParseTable):
def terminal_equality(self, symbol, input):
if input.name == "ATOM":
return symbol == "ATOM" or symbol == input.source
return symbol == input.name
class PrologPackratParser(PackratParser):
def __init__(self, rules, startsymbol):
PackratParser.__init__(self, rules, startsymbol, PrologParseTable,
check_for_left_recursion=False)
def make_basic_rules():
names, regexs = make_regexes()
return basic_rules, names, regexs
def make_parser(basic_rules, names, regexs):
real_rules = make_all_rules(basic_rules)
# for r in real_rules:
# print r
regexs, names = add_necessary_regexs(list(regexs), list(names))
lexer = Lexer(regexs, names, ignore=["IGNORE"])
parser_fact = PrologPackratParser(real_rules, "fact")
parser_query = PrologPackratParser(real_rules, "query")
return lexer, parser_fact, parser_query, basic_rules
def make_all():
return make_parser(*make_basic_rules())
def make_parser_at_runtime(operations):
real_rules = make_all_rules(basic_rules, operations)
parser_fact = PrologPackratParser(real_rules, "fact")
return parser_fact
def _dummyfunc(arg, tree):
return parser_fact
def parse_file(s, parser=None, callback=_dummyfunc, arg=None):
tokens = lexer.tokenize(s)
lines = []
line = []
for tok in tokens:
line.append(tok)
if tok.name == ".":
lines.append(line)
line = []
if parser is None:
parser = parser_fact
trees = []
for line in lines:
tree = parser.parse(line, lazy=False)
if callback is not None:
# XXX ugh
parser = callback(arg, tree)
if parser is None:
parser = parser_fact
trees.append(tree)
return trees
def parse_query(s):
tokens = lexer.tokenize(s, eof=True)
s = parser_query.parse(tokens, lazy=False)
def parse_query_term(s):
return get_query_and_vars(s)[0]
def get_query_and_vars(s):
tokens = lexer.tokenize(s, eof=True)
s = parser_query.parse(tokens, lazy=False)
builder = TermBuilder()
query = builder.build(s)
return query, builder.varname_to_var
class OrderTransformer(object):
def transform(self, node):
if isinstance(node, Symbol):
return node
children = [c for c in node.children
if isinstance(c, Symbol) or (
isinstance(c, Nonterminal) and len(c.children))]
if isinstance(node, Nonterminal):
if len(children) == 1:
return Nonterminal(
node.symbol, [self.transform(children[0])])
if len(children) == 2 or len(children) == 3:
left = children[-2]
right = children[-1]
if (isinstance(right, Nonterminal) and
right.symbol.startswith("extraexpr")):
if len(children) == 2:
leftreplacement = self.transform(left)
else:
leftreplacement = Nonterminal(
node.symbol,
[self.transform(children[0]),
self.transform(left)])
children = [leftreplacement,
self.transform(right.children[0]),
self.transform(right.children[1])]
newnode = Nonterminal(node.symbol, children)
return self.transform_extra(right, newnode)
children = [self.transform(child) for child in children]
return Nonterminal(node.symbol, children)
def transform_extra(self, extranode, child):
children = [c for c in extranode.children
if isinstance(c, Symbol) or (
isinstance(c, Nonterminal) and len(c.children))]
symbol = extranode.symbol[5:]
if len(children) == 2:
return child
right = children[2]
assert isinstance(right, Nonterminal)
children = [child,
self.transform(right.children[0]),
self.transform(right.children[1])]
newnode = Nonterminal(symbol, children)
return self.transform_extra(right, newnode)
class TermBuilder(RPythonVisitor):
def __init__(self):
self.varname_to_var = {}
def build(self, s):
"NOT_RPYTHON"
if isinstance(s, list):
return self.build_many(s)
return self.build_query(s)
def build_many(self, trees):
ot = OrderTransformer()
facts = []
for tree in trees:
s = ot.transform(tree)
facts.append(self.build_fact(s))
return facts
def build_query(self, s):
ot = OrderTransformer()
s = ot.transform(s)
return self.visit(s.children[0])
def build_fact(self, node):
self.varname_to_var = {}
return self.visit(node.children[0])
def visit(self, node):
node = self.find_first_interesting(node)
return self.dispatch(node)
def general_nonterminal_visit(self, node):
from pypy.lang.prolog.interpreter.term import Term, Number, Float
children = []
name = ""
for child in node.children:
if isinstance(child, Symbol):
name = self.general_symbol_visit(child).name
else:
children.append(child)
children = [self.visit(child) for child in children]
if len(children) == 1 and (name == "-" or name == "+"):
if name == "-":
factor = -1
else:
factor = 1
child = children[0]
if isinstance(child, Number):
return Number(factor * child.num)
if isinstance(child, Float):
return Float(factor * child.floatval)
return Term(name, children)
def build_list(self, node):
result = []
while node is not None:
node = self._build_list(node, result)
return result
def _build_list(self, node, result):
node = self.find_first_interesting(node)
if isinstance(node, Nonterminal):
child = node.children[1]
if (isinstance(child, Symbol) and
node.children[1].additional_info == ","):
element = self.visit(node.children[0])
result.append(element)
return node.children[2]
result.append(self.visit(node))
def find_first_interesting(self, node):
if isinstance(node, Nonterminal) and len(node.children) == 1:
return self.find_first_interesting(node.children[0])
return node
def general_symbol_visit(self, node):
from pypy.lang.prolog.interpreter.term import Atom
if node.additional_info.startswith("'"):
end = len(node.additional_info) - 1
assert end >= 0
name = unescape(node.additional_info[1:end])
else:
name = node.additional_info
return Atom.newatom(name)
def visit_VAR(self, node):
from pypy.lang.prolog.interpreter.term import Var
varname = node.additional_info
if varname == "_":
return Var()
if varname in self.varname_to_var:
return self.varname_to_var[varname]
res = Var()
self.varname_to_var[varname] = res
return res
def visit_NUMBER(self, node):
from pypy.lang.prolog.interpreter.term import Number, Float
s = node.additional_info
try:
return Number(int(s))
except ValueError:
return Float(float(s))
def visit_complexterm(self, node):
from pypy.lang.prolog.interpreter.term import Term
name = self.general_symbol_visit(node.children[0]).name
children = self.build_list(node.children[2])
return Term(name, children)
def visit_expr(self, node):
from pypy.lang.prolog.interpreter.term import Number, Float
if node.children[0].additional_info == '-':
result = self.visit(node.children[1])
if isinstance(result, Number):
return Number(-result.num)
elif isinstance(result, Float):
return Float(-result.floatval)
return self.visit(node.children[1])
def visit_listexpr(self, node):
from pypy.lang.prolog.interpreter.term import Atom, Term
node = node.children[1]
if len(node.children) == 1:
l = self.build_list(node)
start = Atom.newatom("[]")
else:
l = self.build_list(node.children[0])
start = self.visit(node.children[2])
l.reverse()
curr = start
for elt in l:
curr = Term(".", [elt, curr])
return curr
ESCAPES = {
"\\a": "\a",
"\\b": "\b",
"\\f": "\f",
"\\n": "\n",
"\\r": "\r",
"\\t": "\t",
"\\v": "\v",
"\\\\": "\\"
}
def unescape(s):
if "\\" not in s:
return s
result = []
i = 0
escape = False
while i < len(s):
c = s[i]
if escape:
escape = False
f = "\\" + c
if f in ESCAPES:
result.append(ESCAPES[f])
else:
result.append(c)
elif c == "\\":
escape = True
else:
result.append(c)
i += 1
return "".join(result)
def get_engine(source):
from pypy.lang.prolog.interpreter.engine import Engine
trees = parse_file(source)
builder = TermBuilder()
e = Engine()
for fact in builder.build_many(trees):
e.add_rule(fact)
return e
# generated code between this line and its other occurence
parser_fact = PrologPackratParser([Rule('query', [['toplevel_op_expr', '.', 'EOF']]),
Rule('fact', [['toplevel_op_expr', '.']]),
Rule('complexterm', [['ATOM', '(', 'toplevel_op_expr', ')'], ['expr']]),
Rule('expr', [['VAR'], ['NUMBER'], ['+', 'NUMBER'], ['-', 'NUMBER'], ['ATOM'], ['(', 'toplevel_op_expr', ')'], ['listexpr']]),
Rule('listexpr', [['[', 'listbody', ']']]),
Rule('listbody', [['toplevel_op_expr', '|', 'toplevel_op_expr'], ['toplevel_op_expr']]),
Rule('extratoplevel_op_expr', [[]]),
Rule('toplevel_op_expr', [['expr1100', '-->', 'expr1100', 'extratoplevel_op_expr'], ['expr1100', ':-', 'expr1100', 'extratoplevel_op_expr'], [':-', 'expr1100', 'extratoplevel_op_expr'], ['?-', 'expr1100', 'extratoplevel_op_expr'], ['expr1100', 'extratoplevel_op_expr']]),
Rule('extraexpr1100', [[]]),
Rule('expr1100', [['expr1050', ';', 'expr1100', 'extraexpr1100'], ['expr1050', 'extraexpr1100']]),
Rule('extraexpr1050', [[]]),
Rule('expr1050', [['expr1000', '->', 'expr1050', 'extraexpr1050'], ['expr1000', 'extraexpr1050']]),
Rule('extraexpr1000', [[]]),
Rule('expr1000', [['expr900', ',', 'expr1000', 'extraexpr1000'], ['expr900', 'extraexpr1000']]),
Rule('extraexpr900', [[]]),
Rule('expr900', [['\\+', 'expr900', 'extraexpr900'], ['~', 'expr700', 'extraexpr900'], ['expr700', 'extraexpr900']]),
Rule('extraexpr700', [[]]),
Rule('expr700', [['expr600', '<', 'expr600', 'extraexpr700'], ['expr600', '=', 'expr600', 'extraexpr700'], ['expr600', '=..', 'expr600', 'extraexpr700'], ['expr600', '=@=', 'expr600', 'extraexpr700'], ['expr600', '=:=', 'expr600', 'extraexpr700'], ['expr600', '=<', 'expr600', 'extraexpr700'], ['expr600', '==', 'expr600', 'extraexpr700'], ['expr600', '=\\=', 'expr600', 'extraexpr700'], ['expr600', '>', 'expr600', 'extraexpr700'], ['expr600', '>=', 'expr600', 'extraexpr700'], ['expr600', '@<', 'expr600', 'extraexpr700'], ['expr600', '@=<', 'expr600', 'extraexpr700'], ['expr600', '@>', 'expr600', 'extraexpr700'], ['expr600', '@>=', 'expr600', 'extraexpr700'], ['expr600', '\\=', 'expr600', 'extraexpr700'], ['expr600', '\\==', 'expr600', 'extraexpr700'], ['expr600', 'is', 'expr600', 'extraexpr700'], ['expr600', 'extraexpr700']]),
Rule('extraexpr600', [[]]),
Rule('expr600', [['expr500', ':', 'expr600', 'extraexpr600'], ['expr500', 'extraexpr600']]),
Rule('extraexpr500', [['+', 'expr400', 'extraexpr500'], ['-', 'expr400', 'extraexpr500'], ['/\\', 'expr400', 'extraexpr500'], ['\\/', 'expr400', 'extraexpr500'], ['xor', 'expr400', 'extraexpr500'], []]),
Rule('expr500', [['+', 'expr400', 'extraexpr500'], ['-', 'expr400', 'extraexpr500'], ['?', 'expr400', 'extraexpr500'], ['\\', 'expr400', 'extraexpr500'], ['expr400', 'extraexpr500']]),
Rule('extraexpr400', [['*', 'expr200', 'extraexpr400'], ['/', 'expr200', 'extraexpr400'], ['//', 'expr200', 'extraexpr400'], ['<<', 'expr200', 'extraexpr400'], ['>>', 'expr200', 'extraexpr400'], ['mod', 'expr200', 'extraexpr400'], ['rem', 'expr200', 'extraexpr400'], []]),
Rule('expr400', [['expr200', 'extraexpr400']]),
Rule('extraexpr200', [[]]),
Rule('expr200', [['complexterm', '**', 'complexterm', 'extraexpr200'], ['complexterm', '^', 'expr200', 'extraexpr200'], ['complexterm', 'extraexpr200']])],
'fact')
parser_query = PrologPackratParser([Rule('query', [['toplevel_op_expr', '.', 'EOF']]),
Rule('fact', [['toplevel_op_expr', '.']]),
Rule('complexterm', [['ATOM', '(', 'toplevel_op_expr', ')'], ['expr']]),
Rule('expr', [['VAR'], ['NUMBER'], ['+', 'NUMBER'], ['-', 'NUMBER'], ['ATOM'], ['(', 'toplevel_op_expr', ')'], ['listexpr']]),
Rule('listexpr', [['[', 'listbody', ']']]),
Rule('listbody', [['toplevel_op_expr', '|', 'toplevel_op_expr'], ['toplevel_op_expr']]),
Rule('extratoplevel_op_expr', [[]]),
Rule('toplevel_op_expr', [['expr1100', '-->', 'expr1100', 'extratoplevel_op_expr'], ['expr1100', ':-', 'expr1100', 'extratoplevel_op_expr'], [':-', 'expr1100', 'extratoplevel_op_expr'], ['?-', 'expr1100', 'extratoplevel_op_expr'], ['expr1100', 'extratoplevel_op_expr']]),
Rule('extraexpr1100', [[]]),
Rule('expr1100', [['expr1050', ';', 'expr1100', 'extraexpr1100'], ['expr1050', 'extraexpr1100']]),
Rule('extraexpr1050', [[]]),
Rule('expr1050', [['expr1000', '->', 'expr1050', 'extraexpr1050'], ['expr1000', 'extraexpr1050']]),
Rule('extraexpr1000', [[]]),
Rule('expr1000', [['expr900', ',', 'expr1000', 'extraexpr1000'], ['expr900', 'extraexpr1000']]),
Rule('extraexpr900', [[]]),
Rule('expr900', [['\\+', 'expr900', 'extraexpr900'], ['~', 'expr700', 'extraexpr900'], ['expr700', 'extraexpr900']]),
Rule('extraexpr700', [[]]),
Rule('expr700', [['expr600', '<', 'expr600', 'extraexpr700'], ['expr600', '=', 'expr600', 'extraexpr700'], ['expr600', '=..', 'expr600', 'extraexpr700'], ['expr600', '=@=', 'expr600', 'extraexpr700'], ['expr600', '=:=', 'expr600', 'extraexpr700'], ['expr600', '=<', 'expr600', 'extraexpr700'], ['expr600', '==', 'expr600', 'extraexpr700'], ['expr600', '=\\=', 'expr600', 'extraexpr700'], ['expr600', '>', 'expr600', 'extraexpr700'], ['expr600', '>=', 'expr600', 'extraexpr700'], ['expr600', '@<', 'expr600', 'extraexpr700'], ['expr600', '@=<', 'expr600', 'extraexpr700'], ['expr600', '@>', 'expr600', 'extraexpr700'], ['expr600', '@>=', 'expr600', 'extraexpr700'], ['expr600', '\\=', 'expr600', 'extraexpr700'], ['expr600', '\\==', 'expr600', 'extraexpr700'], ['expr600', 'is', 'expr600', 'extraexpr700'], ['expr600', 'extraexpr700']]),
Rule('extraexpr600', [[]]),
Rule('expr600', [['expr500', ':', 'expr600', 'extraexpr600'], ['expr500', 'extraexpr600']]),
Rule('extraexpr500', [['+', 'expr400', 'extraexpr500'], ['-', 'expr400', 'extraexpr500'], ['/\\', 'expr400', 'extraexpr500'], ['\\/', 'expr400', 'extraexpr500'], ['xor', 'expr400', 'extraexpr500'], []]),
Rule('expr500', [['+', 'expr400', 'extraexpr500'], ['-', 'expr400', 'extraexpr500'], ['?', 'expr400', 'extraexpr500'], ['\\', 'expr400', 'extraexpr500'], ['expr400', 'extraexpr500']]),
Rule('extraexpr400', [['*', 'expr200', 'extraexpr400'], ['/', 'expr200', 'extraexpr400'], ['//', 'expr200', 'extraexpr400'], ['<<', 'expr200', 'extraexpr400'], ['>>', 'expr200', 'extraexpr400'], ['mod', 'expr200', 'extraexpr400'], ['rem', 'expr200', 'extraexpr400'], []]),
Rule('expr400', [['expr200', 'extraexpr400']]),
Rule('extraexpr200', [[]]),
Rule('expr200', [['complexterm', '**', 'complexterm', 'extraexpr200'], ['complexterm', '^', 'expr200', 'extraexpr200'], ['complexterm', 'extraexpr200']])],
'query')
def recognize(runner, i):
assert i >= 0
input = runner.text
state = 0
while 1:
if state == 0:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 0
return ~i
if char == '\t':
state = 1
elif char == '\n':
state = 1
elif char == ' ':
state = 1
elif char == '(':
state = 2
elif char == ',':
state = 3
elif char == '0':
state = 4
elif '1' <= char <= '9':
state = 5
elif char == '<':
state = 6
elif char == '@':
state = 7
elif 'A' <= char <= 'Z':
state = 8
elif char == '_':
state = 8
elif char == '\\':
state = 9
elif 'a' <= char <= 'h':
state = 10
elif 'j' <= char <= 'l':
state = 10
elif 'n' <= char <= 'q':
state = 10
elif 's' <= char <= 'w':
state = 10
elif char == 'y':
state = 10
elif char == 'z':
state = 10
elif char == 'x':
state = 11
elif char == '|':
state = 12
elif char == "'":
state = 13
elif char == '+':
state = 14
elif char == '/':
state = 15
elif char == ';':
state = 16
elif char == '?':
state = 17
elif char == '[':
state = 18
elif char == '*':
state = 19
elif char == '.':
state = 20
elif char == ':':
state = 21
elif char == '>':
state = 22
elif char == '^':
state = 23
elif char == 'r':
state = 24
elif char == '~':
state = 25
elif char == '!':
state = 26
elif char == '%':
state = 27
elif char == ')':
state = 28
elif char == '-':
state = 29
elif char == '=':
state = 30
elif char == ']':
state = 31
elif char == 'i':
state = 32
elif char == 'm':
state = 33
else:
break
if state == 4:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 4
return i
if char == '.':
state = 73
else:
break
if state == 5:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 5
return i
if char == '.':
state = 73
elif '0' <= char <= '9':
state = 5
continue
else:
break
if state == 6:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 6
return i
if char == '<':
state = 72
else:
break
if state == 7:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 7
return ~i
if char == '=':
state = 67
elif char == '<':
state = 68
elif char == '>':
state = 69
else:
break
if state == 8:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 8
return i
if '0' <= char <= '9':
state = 8
continue
elif 'A' <= char <= 'Z':
state = 8
continue
elif char == '_':
state = 8
continue
elif 'a' <= char <= 'z':
state = 8
continue
else:
break
if state == 9:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 9
return i
if char == '=':
state = 64
elif char == '/':
state = 65
elif char == '+':
state = 63
else:
break
if state == 10:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 10
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'z':
state = 10
continue
else:
break
if state == 11:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 11
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'n':
state = 10
continue
elif 'p' <= char <= 'z':
state = 10
continue
elif char == 'o':
state = 61
else:
break
if state == 13:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 13
return ~i
if char == "'":
state = 26
elif '\x00' <= char <= '&':
state = 13
continue
elif '(' <= char <= '\xff':
state = 13
continue
else:
break
if state == 15:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 15
return i
if char == '*':
state = 57
elif char == '\\':
state = 58
elif char == '/':
state = 59
else:
break
if state == 17:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 17
return i
if char == '-':
state = 56
else:
break
if state == 18:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 18
return i
if char == ']':
state = 26
else:
break
if state == 19:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 19
return i
if char == '*':
state = 55
else:
break
if state == 21:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 21
return i
if char == '-':
state = 54
else:
break
if state == 22:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 22
return i
if char == '=':
state = 52
elif char == '>':
state = 53
else:
break
if state == 24:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 24
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'd':
state = 10
continue
elif 'f' <= char <= 'z':
state = 10
continue
elif char == 'e':
state = 50
else:
break
if state == 27:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 27
return i
if '\x00' <= char <= '\t':
state = 27
continue
elif '\x0b' <= char <= '\xff':
state = 27
continue
else:
break
if state == 29:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 29
return i
if char == '>':
state = 48
elif char == '-':
state = 47
else:
break
if state == 30:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 30
return i
if char == '@':
state = 37
elif char == '<':
state = 38
elif char == '.':
state = 39
elif char == ':':
state = 40
elif char == '=':
state = 41
elif char == '\\':
state = 42
else:
break
if state == 32:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 32
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'r':
state = 10
continue
elif 't' <= char <= 'z':
state = 10
continue
elif char == 's':
state = 36
else:
break
if state == 33:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 33
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'n':
state = 10
continue
elif 'p' <= char <= 'z':
state = 10
continue
elif char == 'o':
state = 34
else:
break
if state == 34:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 34
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'c':
state = 10
continue
elif 'e' <= char <= 'z':
state = 10
continue
elif char == 'd':
state = 35
else:
break
if state == 35:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 35
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'z':
state = 10
continue
else:
break
if state == 36:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 36
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'z':
state = 10
continue
else:
break
if state == 37:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 37
return ~i
if char == '=':
state = 46
else:
break
if state == 39:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 39
return ~i
if char == '.':
state = 45
else:
break
if state == 40:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 40
return ~i
if char == '=':
state = 44
else:
break
if state == 42:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 42
return ~i
if char == '=':
state = 43
else:
break
if state == 47:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 47
return ~i
if char == '>':
state = 49
else:
break
if state == 50:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 50
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'l':
state = 10
continue
elif 'n' <= char <= 'z':
state = 10
continue
elif char == 'm':
state = 51
else:
break
if state == 51:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 51
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'z':
state = 10
continue
else:
break
if state == 57:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 57
return ~i
if '\x00' <= char <= ')':
state = 57
continue
elif '+' <= char <= '\xff':
state = 57
continue
elif char == '*':
state = 60
else:
break
if state == 60:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 60
return ~i
if '\x00' <= char <= '.':
state = 57
continue
elif '0' <= char <= '\xff':
state = 57
continue
elif char == '/':
state = 1
else:
break
if state == 61:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 61
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'q':
state = 10
continue
elif 's' <= char <= 'z':
state = 10
continue
elif char == 'r':
state = 62
else:
break
if state == 62:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 62
return i
if '0' <= char <= '9':
state = 10
continue
elif 'A' <= char <= 'Z':
state = 10
continue
elif char == '_':
state = 10
continue
elif 'a' <= char <= 'z':
state = 10
continue
else:
break
if state == 64:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 64
return i
if char == '=':
state = 66
else:
break
if state == 67:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 67
return ~i
if char == '<':
state = 71
else:
break
if state == 69:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 69
return i
if char == '=':
state = 70
else:
break
if state == 73:
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 73
return ~i
if '0' <= char <= '9':
state = 74
else:
break
if state == 74:
runner.last_matched_index = i - 1
runner.last_matched_state = state
if i < len(input):
char = input[i]
i += 1
else:
runner.state = 74
return i
if '0' <= char <= '9':
state = 74
continue
else:
break
runner.last_matched_state = state
runner.last_matched_index = i - 1
runner.state = state
if i == len(input):
return i
else:
return ~i
break
runner.state = state
return ~i
lexer = DummyLexer(recognize, DFA(75,
{(0, '\t'): 1,
(0, '\n'): 1,
(0, ' '): 1,
(0, '!'): 26,
(0, '%'): 27,
(0, "'"): 13,
(0, '('): 2,
(0, ')'): 28,
(0, '*'): 19,
(0, '+'): 14,
(0, ','): 3,
(0, '-'): 29,
(0, '.'): 20,
(0, '/'): 15,
(0, '0'): 4,
(0, '1'): 5,
(0, '2'): 5,
(0, '3'): 5,
(0, '4'): 5,
(0, '5'): 5,
(0, '6'): 5,
(0, '7'): 5,
(0, '8'): 5,
(0, '9'): 5,
(0, ':'): 21,
(0, ';'): 16,
(0, '<'): 6,
(0, '='): 30,
(0, '>'): 22,
(0, '?'): 17,
(0, '@'): 7,
(0, 'A'): 8,
(0, 'B'): 8,
(0, 'C'): 8,
(0, 'D'): 8,
(0, 'E'): 8,
(0, 'F'): 8,
(0, 'G'): 8,
(0, 'H'): 8,
(0, 'I'): 8,
(0, 'J'): 8,
(0, 'K'): 8,
(0, 'L'): 8,
(0, 'M'): 8,
(0, 'N'): 8,
(0, 'O'): 8,
(0, 'P'): 8,
(0, 'Q'): 8,
(0, 'R'): 8,
(0, 'S'): 8,
(0, 'T'): 8,
(0, 'U'): 8,
(0, 'V'): 8,
(0, 'W'): 8,
(0, 'X'): 8,
(0, 'Y'): 8,
(0, 'Z'): 8,
(0, '['): 18,
(0, '\\'): 9,
(0, ']'): 31,
(0, '^'): 23,
(0, '_'): 8,
(0, 'a'): 10,
(0, 'b'): 10,
(0, 'c'): 10,
(0, 'd'): 10,
(0, 'e'): 10,
(0, 'f'): 10,
(0, 'g'): 10,
(0, 'h'): 10,
(0, 'i'): 32,
(0, 'j'): 10,
(0, 'k'): 10,
(0, 'l'): 10,
(0, 'm'): 33,
(0, 'n'): 10,
(0, 'o'): 10,
(0, 'p'): 10,
(0, 'q'): 10,
(0, 'r'): 24,
(0, 's'): 10,
(0, 't'): 10,
(0, 'u'): 10,
(0, 'v'): 10,
(0, 'w'): 10,
(0, 'x'): 11,
(0, 'y'): 10,
(0, 'z'): 10,
(0, '|'): 12,
(0, '~'): 25,
(4, '.'): 73,
(5, '.'): 73,
(5, '0'): 5,
(5, '1'): 5,
(5, '2'): 5,
(5, '3'): 5,
(5, '4'): 5,
(5, '5'): 5,
(5, '6'): 5,
(5, '7'): 5,
(5, '8'): 5,
(5, '9'): 5,
(6, '<'): 72,
(7, '<'): 68,
(7, '='): 67,
(7, '>'): 69,
(8, '0'): 8,
(8, '1'): 8,
(8, '2'): 8,
(8, '3'): 8,
(8, '4'): 8,
(8, '5'): 8,
(8, '6'): 8,
(8, '7'): 8,
(8, '8'): 8,
(8, '9'): 8,
(8, 'A'): 8,
(8, 'B'): 8,
(8, 'C'): 8,
(8, 'D'): 8,
(8, 'E'): 8,
(8, 'F'): 8,
(8, 'G'): 8,
(8, 'H'): 8,
(8, 'I'): 8,
(8, 'J'): 8,
(8, 'K'): 8,
(8, 'L'): 8,
(8, 'M'): 8,
(8, 'N'): 8,
(8, 'O'): 8,
(8, 'P'): 8,
(8, 'Q'): 8,
(8, 'R'): 8,
(8, 'S'): 8,
(8, 'T'): 8,
(8, 'U'): 8,
(8, 'V'): 8,
(8, 'W'): 8,
(8, 'X'): 8,
(8, 'Y'): 8,
(8, 'Z'): 8,
(8, '_'): 8,
(8, 'a'): 8,
(8, 'b'): 8,
(8, 'c'): 8,
(8, 'd'): 8,
(8, 'e'): 8,
(8, 'f'): 8,
(8, 'g'): 8,
(8, 'h'): 8,
(8, 'i'): 8,
(8, 'j'): 8,
(8, 'k'): 8,
(8, 'l'): 8,
(8, 'm'): 8,
(8, 'n'): 8,
(8, 'o'): 8,
(8, 'p'): 8,
(8, 'q'): 8,
(8, 'r'): 8,
(8, 's'): 8,
(8, 't'): 8,
(8, 'u'): 8,
(8, 'v'): 8,
(8, 'w'): 8,
(8, 'x'): 8,
(8, 'y'): 8,
(8, 'z'): 8,
(9, '+'): 63,
(9, '/'): 65,
(9, '='): 64,
(10, '0'): 10,
(10, '1'): 10,
(10, '2'): 10,
(10, '3'): 10,
(10, '4'): 10,
(10, '5'): 10,
(10, '6'): 10,
(10, '7'): 10,
(10, '8'): 10,
(10, '9'): 10,
(10, 'A'): 10,
(10, 'B'): 10,
(10, 'C'): 10,
(10, 'D'): 10,
(10, 'E'): 10,
(10, 'F'): 10,
(10, 'G'): 10,
(10, 'H'): 10,
(10, 'I'): 10,
(10, 'J'): 10,
(10, 'K'): 10,
(10, 'L'): 10,
(10, 'M'): 10,
(10, 'N'): 10,
(10, 'O'): 10,
(10, 'P'): 10,
(10, 'Q'): 10,
(10, 'R'): 10,
(10, 'S'): 10,
(10, 'T'): 10,
(10, 'U'): 10,
(10, 'V'): 10,
(10, 'W'): 10,
(10, 'X'): 10,
(10, 'Y'): 10,
(10, 'Z'): 10,
(10, '_'): 10,
(10, 'a'): 10,
(10, 'b'): 10,
(10, 'c'): 10,
(10, 'd'): 10,
(10, 'e'): 10,
(10, 'f'): 10,
(10, 'g'): 10,
(10, 'h'): 10,
(10, 'i'): 10,
(10, 'j'): 10,
(10, 'k'): 10,
(10, 'l'): 10,
(10, 'm'): 10,
(10, 'n'): 10,
(10, 'o'): 10,
(10, 'p'): 10,
(10, 'q'): 10,
(10, 'r'): 10,
(10, 's'): 10,
(10, 't'): 10,
(10, 'u'): 10,
(10, 'v'): 10,
(10, 'w'): 10,
(10, 'x'): 10,
(10, 'y'): 10,
(10, 'z'): 10,
(11, '0'): 10,
(11, '1'): 10,
(11, '2'): 10,
(11, '3'): 10,
(11, '4'): 10,
(11, '5'): 10,
(11, '6'): 10,
(11, '7'): 10,
(11, '8'): 10,
(11, '9'): 10,
(11, 'A'): 10,
(11, 'B'): 10,
(11, 'C'): 10,
(11, 'D'): 10,
(11, 'E'): 10,
(11, 'F'): 10,
(11, 'G'): 10,
(11, 'H'): 10,
(11, 'I'): 10,
(11, 'J'): 10,
(11, 'K'): 10,
(11, 'L'): 10,
(11, 'M'): 10,
(11, 'N'): 10,
(11, 'O'): 10,
(11, 'P'): 10,
(11, 'Q'): 10,
(11, 'R'): 10,
(11, 'S'): 10,
(11, 'T'): 10,
(11, 'U'): 10,
(11, 'V'): 10,
(11, 'W'): 10,
(11, 'X'): 10,
(11, 'Y'): 10,
(11, 'Z'): 10,
(11, '_'): 10,
(11, 'a'): 10,
(11, 'b'): 10,
(11, 'c'): 10,
(11, 'd'): 10,
(11, 'e'): 10,
(11, 'f'): 10,
(11, 'g'): 10,
(11, 'h'): 10,
(11, 'i'): 10,
(11, 'j'): 10,
(11, 'k'): 10,
(11, 'l'): 10,
(11, 'm'): 10,
(11, 'n'): 10,
(11, 'o'): 61,
(11, 'p'): 10,
(11, 'q'): 10,
(11, 'r'): 10,
(11, 's'): 10,
(11, 't'): 10,
(11, 'u'): 10,
(11, 'v'): 10,
(11, 'w'): 10,
(11, 'x'): 10,
(11, 'y'): 10,
(11, 'z'): 10,
(13, '\x00'): 13,
(13, '\x01'): 13,
(13, '\x02'): 13,
(13, '\x03'): 13,
(13, '\x04'): 13,
(13, '\x05'): 13,
(13, '\x06'): 13,
(13, '\x07'): 13,
(13, '\x08'): 13,
(13, '\t'): 13,
(13, '\n'): 13,
(13, '\x0b'): 13,
(13, '\x0c'): 13,
(13, '\r'): 13,
(13, '\x0e'): 13,
(13, '\x0f'): 13,
(13, '\x10'): 13,
(13, '\x11'): 13,
(13, '\x12'): 13,
(13, '\x13'): 13,
(13, '\x14'): 13,
(13, '\x15'): 13,
(13, '\x16'): 13,
(13, '\x17'): 13,
(13, '\x18'): 13,
(13, '\x19'): 13,
(13, '\x1a'): 13,
(13, '\x1b'): 13,
(13, '\x1c'): 13,
(13, '\x1d'): 13,
(13, '\x1e'): 13,
(13, '\x1f'): 13,
(13, ' '): 13,
(13, '!'): 13,
(13, '"'): 13,
(13, '#'): 13,
(13, '$'): 13,
(13, '%'): 13,
(13, '&'): 13,
(13, "'"): 26,
(13, '('): 13,
(13, ')'): 13,
(13, '*'): 13,
(13, '+'): 13,
(13, ','): 13,
(13, '-'): 13,
(13, '.'): 13,
(13, '/'): 13,
(13, '0'): 13,
(13, '1'): 13,
(13, '2'): 13,
(13, '3'): 13,
(13, '4'): 13,
(13, '5'): 13,
(13, '6'): 13,
(13, '7'): 13,
(13, '8'): 13,
(13, '9'): 13,
(13, ':'): 13,
(13, ';'): 13,
(13, '<'): 13,
(13, '='): 13,
(13, '>'): 13,
(13, '?'): 13,
(13, '@'): 13,
(13, 'A'): 13,
(13, 'B'): 13,
(13, 'C'): 13,
(13, 'D'): 13,
(13, 'E'): 13,
(13, 'F'): 13,
(13, 'G'): 13,
(13, 'H'): 13,
(13, 'I'): 13,
(13, 'J'): 13,
(13, 'K'): 13,
(13, 'L'): 13,
(13, 'M'): 13,
(13, 'N'): 13,
(13, 'O'): 13,
(13, 'P'): 13,
(13, 'Q'): 13,
(13, 'R'): 13,
(13, 'S'): 13,
(13, 'T'): 13,
(13, 'U'): 13,
(13, 'V'): 13,
(13, 'W'): 13,
(13, 'X'): 13,
(13, 'Y'): 13,
(13, 'Z'): 13,
(13, '['): 13,
(13, '\\'): 13,
(13, ']'): 13,
(13, '^'): 13,
(13, '_'): 13,
(13, '`'): 13,
(13, 'a'): 13,
(13, 'b'): 13,
(13, 'c'): 13,
(13, 'd'): 13,
(13, 'e'): 13,
(13, 'f'): 13,
(13, 'g'): 13,
(13, 'h'): 13,
(13, 'i'): 13,
(13, 'j'): 13,
(13, 'k'): 13,
(13, 'l'): 13,
(13, 'm'): 13,
(13, 'n'): 13,
(13, 'o'): 13,
(13, 'p'): 13,
(13, 'q'): 13,
(13, 'r'): 13,
(13, 's'): 13,
(13, 't'): 13,
(13, 'u'): 13,
(13, 'v'): 13,
(13, 'w'): 13,
(13, 'x'): 13,
(13, 'y'): 13,
(13, 'z'): 13,
(13, '{'): 13,
(13, '|'): 13,
(13, '}'): 13,
(13, '~'): 13,
(13, '\x7f'): 13,
(13, '\x80'): 13,
(13, '\x81'): 13,
(13, '\x82'): 13,
(13, '\x83'): 13,
(13, '\x84'): 13,
(13, '\x85'): 13,
(13, '\x86'): 13,
(13, '\x87'): 13,
(13, '\x88'): 13,
(13, '\x89'): 13,
(13, '\x8a'): 13,
(13, '\x8b'): 13,
(13, '\x8c'): 13,
(13, '\x8d'): 13,
(13, '\x8e'): 13,
(13, '\x8f'): 13,
(13, '\x90'): 13,
(13, '\x91'): 13,
(13, '\x92'): 13,
(13, '\x93'): 13,
(13, '\x94'): 13,
(13, '\x95'): 13,
(13, '\x96'): 13,
(13, '\x97'): 13,
(13, '\x98'): 13,
(13, '\x99'): 13,
(13, '\x9a'): 13,
(13, '\x9b'): 13,
(13, '\x9c'): 13,
(13, '\x9d'): 13,
(13, '\x9e'): 13,
(13, '\x9f'): 13,
(13, '\xa0'): 13,
(13, '\xa1'): 13,
(13, '\xa2'): 13,
(13, '\xa3'): 13,
(13, '\xa4'): 13,
(13, '\xa5'): 13,
(13, '\xa6'): 13,
(13, '\xa7'): 13,
(13, '\xa8'): 13,
(13, '\xa9'): 13,
(13, '\xaa'): 13,
(13, '\xab'): 13,
(13, '\xac'): 13,
(13, '\xad'): 13,
(13, '\xae'): 13,
(13, '\xaf'): 13,
(13, '\xb0'): 13,
(13, '\xb1'): 13,
(13, '\xb2'): 13,
(13, '\xb3'): 13,
(13, '\xb4'): 13,
(13, '\xb5'): 13,
(13, '\xb6'): 13,
(13, '\xb7'): 13,
(13, '\xb8'): 13,
(13, '\xb9'): 13,
(13, '\xba'): 13,
(13, '\xbb'): 13,
(13, '\xbc'): 13,
(13, '\xbd'): 13,
(13, '\xbe'): 13,
(13, '\xbf'): 13,
(13, '\xc0'): 13,
(13, '\xc1'): 13,
(13, '\xc2'): 13,
(13, '\xc3'): 13,
(13, '\xc4'): 13,
(13, '\xc5'): 13,
(13, '\xc6'): 13,
(13, '\xc7'): 13,
(13, '\xc8'): 13,
(13, '\xc9'): 13,
(13, '\xca'): 13,
(13, '\xcb'): 13,
(13, '\xcc'): 13,
(13, '\xcd'): 13,
(13, '\xce'): 13,
(13, '\xcf'): 13,
(13, '\xd0'): 13,
(13, '\xd1'): 13,
(13, '\xd2'): 13,
(13, '\xd3'): 13,
(13, '\xd4'): 13,
(13, '\xd5'): 13,
(13, '\xd6'): 13,
(13, '\xd7'): 13,
(13, '\xd8'): 13,
(13, '\xd9'): 13,
(13, '\xda'): 13,
(13, '\xdb'): 13,
(13, '\xdc'): 13,
(13, '\xdd'): 13,
(13, '\xde'): 13,
(13, '\xdf'): 13,
(13, '\xe0'): 13,
(13, '\xe1'): 13,
(13, '\xe2'): 13,
(13, '\xe3'): 13,
(13, '\xe4'): 13,
(13, '\xe5'): 13,
(13, '\xe6'): 13,
(13, '\xe7'): 13,
(13, '\xe8'): 13,
(13, '\xe9'): 13,
(13, '\xea'): 13,
(13, '\xeb'): 13,
(13, '\xec'): 13,
(13, '\xed'): 13,
(13, '\xee'): 13,
(13, '\xef'): 13,
(13, '\xf0'): 13,
(13, '\xf1'): 13,
(13, '\xf2'): 13,
(13, '\xf3'): 13,
(13, '\xf4'): 13,
(13, '\xf5'): 13,
(13, '\xf6'): 13,
(13, '\xf7'): 13,
(13, '\xf8'): 13,
(13, '\xf9'): 13,
(13, '\xfa'): 13,
(13, '\xfb'): 13,
(13, '\xfc'): 13,
(13, '\xfd'): 13,
(13, '\xfe'): 13,
(13, '\xff'): 13,
(15, '*'): 57,
(15, '/'): 59,
(15, '\\'): 58,
(17, '-'): 56,
(18, ']'): 26,
(19, '*'): 55,
(21, '-'): 54,
(22, '='): 52,
(22, '>'): 53,
(24, '0'): 10,
(24, '1'): 10,
(24, '2'): 10,
(24, '3'): 10,
(24, '4'): 10,
(24, '5'): 10,
(24, '6'): 10,
(24, '7'): 10,
(24, '8'): 10,
(24, '9'): 10,
(24, 'A'): 10,
(24, 'B'): 10,
(24, 'C'): 10,
(24, 'D'): 10,
(24, 'E'): 10,
(24, 'F'): 10,
(24, 'G'): 10,
(24, 'H'): 10,
(24, 'I'): 10,
(24, 'J'): 10,
(24, 'K'): 10,
(24, 'L'): 10,
(24, 'M'): 10,
(24, 'N'): 10,
(24, 'O'): 10,
(24, 'P'): 10,
(24, 'Q'): 10,
(24, 'R'): 10,
(24, 'S'): 10,
(24, 'T'): 10,
(24, 'U'): 10,
(24, 'V'): 10,
(24, 'W'): 10,
(24, 'X'): 10,
(24, 'Y'): 10,
(24, 'Z'): 10,
(24, '_'): 10,
(24, 'a'): 10,
(24, 'b'): 10,
(24, 'c'): 10,
(24, 'd'): 10,
(24, 'e'): 50,
(24, 'f'): 10,
(24, 'g'): 10,
(24, 'h'): 10,
(24, 'i'): 10,
(24, 'j'): 10,
(24, 'k'): 10,
(24, 'l'): 10,
(24, 'm'): 10,
(24, 'n'): 10,
(24, 'o'): 10,
(24, 'p'): 10,
(24, 'q'): 10,
(24, 'r'): 10,
(24, 's'): 10,
(24, 't'): 10,
(24, 'u'): 10,
(24, 'v'): 10,
(24, 'w'): 10,
(24, 'x'): 10,
(24, 'y'): 10,
(24, 'z'): 10,
(27, '\x00'): 27,
(27, '\x01'): 27,
(27, '\x02'): 27,
(27, '\x03'): 27,
(27, '\x04'): 27,
(27, '\x05'): 27,
(27, '\x06'): 27,
(27, '\x07'): 27,
(27, '\x08'): 27,
(27, '\t'): 27,
(27, '\x0b'): 27,
(27, '\x0c'): 27,
(27, '\r'): 27,
(27, '\x0e'): 27,
(27, '\x0f'): 27,
(27, '\x10'): 27,
(27, '\x11'): 27,
(27, '\x12'): 27,
(27, '\x13'): 27,
(27, '\x14'): 27,
(27, '\x15'): 27,
(27, '\x16'): 27,
(27, '\x17'): 27,
(27, '\x18'): 27,
(27, '\x19'): 27,
(27, '\x1a'): 27,
(27, '\x1b'): 27,
(27, '\x1c'): 27,
(27, '\x1d'): 27,
(27, '\x1e'): 27,
(27, '\x1f'): 27,
(27, ' '): 27,
(27, '!'): 27,
(27, '"'): 27,
(27, '#'): 27,
(27, '$'): 27,
(27, '%'): 27,
(27, '&'): 27,
(27, "'"): 27,
(27, '('): 27,
(27, ')'): 27,
(27, '*'): 27,
(27, '+'): 27,
(27, ','): 27,
(27, '-'): 27,
(27, '.'): 27,
(27, '/'): 27,
(27, '0'): 27,
(27, '1'): 27,
(27, '2'): 27,
(27, '3'): 27,
(27, '4'): 27,
(27, '5'): 27,
(27, '6'): 27,
(27, '7'): 27,
(27, '8'): 27,
(27, '9'): 27,
(27, ':'): 27,
(27, ';'): 27,
(27, '<'): 27,
(27, '='): 27,
(27, '>'): 27,
(27, '?'): 27,
(27, '@'): 27,
(27, 'A'): 27,
(27, 'B'): 27,
(27, 'C'): 27,
(27, 'D'): 27,
(27, 'E'): 27,
(27, 'F'): 27,
(27, 'G'): 27,
(27, 'H'): 27,
(27, 'I'): 27,
(27, 'J'): 27,
(27, 'K'): 27,
(27, 'L'): 27,
(27, 'M'): 27,
(27, 'N'): 27,
(27, 'O'): 27,
(27, 'P'): 27,
(27, 'Q'): 27,
(27, 'R'): 27,
(27, 'S'): 27,
(27, 'T'): 27,
(27, 'U'): 27,
(27, 'V'): 27,
(27, 'W'): 27,
(27, 'X'): 27,
(27, 'Y'): 27,
(27, 'Z'): 27,
(27, '['): 27,
(27, '\\'): 27,
(27, ']'): 27,
(27, '^'): 27,
(27, '_'): 27,
(27, '`'): 27,
(27, 'a'): 27,
(27, 'b'): 27,
(27, 'c'): 27,
(27, 'd'): 27,
(27, 'e'): 27,
(27, 'f'): 27,
(27, 'g'): 27,
(27, 'h'): 27,
(27, 'i'): 27,
(27, 'j'): 27,
(27, 'k'): 27,
(27, 'l'): 27,
(27, 'm'): 27,
(27, 'n'): 27,
(27, 'o'): 27,
(27, 'p'): 27,
(27, 'q'): 27,
(27, 'r'): 27,
(27, 's'): 27,
(27, 't'): 27,
(27, 'u'): 27,
(27, 'v'): 27,
(27, 'w'): 27,
(27, 'x'): 27,
(27, 'y'): 27,
(27, 'z'): 27,
(27, '{'): 27,
(27, '|'): 27,
(27, '}'): 27,
(27, '~'): 27,
(27, '\x7f'): 27,
(27, '\x80'): 27,
(27, '\x81'): 27,
(27, '\x82'): 27,
(27, '\x83'): 27,
(27, '\x84'): 27,
(27, '\x85'): 27,
(27, '\x86'): 27,
(27, '\x87'): 27,
(27, '\x88'): 27,
(27, '\x89'): 27,
(27, '\x8a'): 27,
(27, '\x8b'): 27,
(27, '\x8c'): 27,
(27, '\x8d'): 27,
(27, '\x8e'): 27,
(27, '\x8f'): 27,
(27, '\x90'): 27,
(27, '\x91'): 27,
(27, '\x92'): 27,
(27, '\x93'): 27,
(27, '\x94'): 27,
(27, '\x95'): 27,
(27, '\x96'): 27,
(27, '\x97'): 27,
(27, '\x98'): 27,
(27, '\x99'): 27,
(27, '\x9a'): 27,
(27, '\x9b'): 27,
(27, '\x9c'): 27,
(27, '\x9d'): 27,
(27, '\x9e'): 27,
(27, '\x9f'): 27,
(27, '\xa0'): 27,
(27, '\xa1'): 27,
(27, '\xa2'): 27,
(27, '\xa3'): 27,
(27, '\xa4'): 27,
(27, '\xa5'): 27,
(27, '\xa6'): 27,
(27, '\xa7'): 27,
(27, '\xa8'): 27,
(27, '\xa9'): 27,
(27, '\xaa'): 27,
(27, '\xab'): 27,
(27, '\xac'): 27,
(27, '\xad'): 27,
(27, '\xae'): 27,
(27, '\xaf'): 27,
(27, '\xb0'): 27,
(27, '\xb1'): 27,
(27, '\xb2'): 27,
(27, '\xb3'): 27,
(27, '\xb4'): 27,
(27, '\xb5'): 27,
(27, '\xb6'): 27,
(27, '\xb7'): 27,
(27, '\xb8'): 27,
(27, '\xb9'): 27,
(27, '\xba'): 27,
(27, '\xbb'): 27,
(27, '\xbc'): 27,
(27, '\xbd'): 27,
(27, '\xbe'): 27,
(27, '\xbf'): 27,
(27, '\xc0'): 27,
(27, '\xc1'): 27,
(27, '\xc2'): 27,
(27, '\xc3'): 27,
(27, '\xc4'): 27,
(27, '\xc5'): 27,
(27, '\xc6'): 27,
(27, '\xc7'): 27,
(27, '\xc8'): 27,
(27, '\xc9'): 27,
(27, '\xca'): 27,
(27, '\xcb'): 27,
(27, '\xcc'): 27,
(27, '\xcd'): 27,
(27, '\xce'): 27,
(27, '\xcf'): 27,
(27, '\xd0'): 27,
(27, '\xd1'): 27,
(27, '\xd2'): 27,
(27, '\xd3'): 27,
(27, '\xd4'): 27,
(27, '\xd5'): 27,
(27, '\xd6'): 27,
(27, '\xd7'): 27,
(27, '\xd8'): 27,
(27, '\xd9'): 27,
(27, '\xda'): 27,
(27, '\xdb'): 27,
(27, '\xdc'): 27,
(27, '\xdd'): 27,
(27, '\xde'): 27,
(27, '\xdf'): 27,
(27, '\xe0'): 27,
(27, '\xe1'): 27,
(27, '\xe2'): 27,
(27, '\xe3'): 27,
(27, '\xe4'): 27,
(27, '\xe5'): 27,
(27, '\xe6'): 27,
(27, '\xe7'): 27,
(27, '\xe8'): 27,
(27, '\xe9'): 27,
(27, '\xea'): 27,
(27, '\xeb'): 27,
(27, '\xec'): 27,
(27, '\xed'): 27,
(27, '\xee'): 27,
(27, '\xef'): 27,
(27, '\xf0'): 27,
(27, '\xf1'): 27,
(27, '\xf2'): 27,
(27, '\xf3'): 27,
(27, '\xf4'): 27,
(27, '\xf5'): 27,
(27, '\xf6'): 27,
(27, '\xf7'): 27,
(27, '\xf8'): 27,
(27, '\xf9'): 27,
(27, '\xfa'): 27,
(27, '\xfb'): 27,
(27, '\xfc'): 27,
(27, '\xfd'): 27,
(27, '\xfe'): 27,
(27, '\xff'): 27,
(29, '-'): 47,
(29, '>'): 48,
(30, '.'): 39,
(30, ':'): 40,
(30, '<'): 38,
(30, '='): 41,
(30, '@'): 37,
(30, '\\'): 42,
(32, '0'): 10,
(32, '1'): 10,
(32, '2'): 10,
(32, '3'): 10,
(32, '4'): 10,
(32, '5'): 10,
(32, '6'): 10,
(32, '7'): 10,
(32, '8'): 10,
(32, '9'): 10,
(32, 'A'): 10,
(32, 'B'): 10,
(32, 'C'): 10,
(32, 'D'): 10,
(32, 'E'): 10,
(32, 'F'): 10,
(32, 'G'): 10,
(32, 'H'): 10,
(32, 'I'): 10,
(32, 'J'): 10,
(32, 'K'): 10,
(32, 'L'): 10,
(32, 'M'): 10,
(32, 'N'): 10,
(32, 'O'): 10,
(32, 'P'): 10,
(32, 'Q'): 10,
(32, 'R'): 10,
(32, 'S'): 10,
(32, 'T'): 10,
(32, 'U'): 10,
(32, 'V'): 10,
(32, 'W'): 10,
(32, 'X'): 10,
(32, 'Y'): 10,
(32, 'Z'): 10,
(32, '_'): 10,
(32, 'a'): 10,
(32, 'b'): 10,
(32, 'c'): 10,
(32, 'd'): 10,
(32, 'e'): 10,
(32, 'f'): 10,
(32, 'g'): 10,
(32, 'h'): 10,
(32, 'i'): 10,
(32, 'j'): 10,
(32, 'k'): 10,
(32, 'l'): 10,
(32, 'm'): 10,
(32, 'n'): 10,
(32, 'o'): 10,
(32, 'p'): 10,
(32, 'q'): 10,
(32, 'r'): 10,
(32, 's'): 36,
(32, 't'): 10,
(32, 'u'): 10,
(32, 'v'): 10,
(32, 'w'): 10,
(32, 'x'): 10,
(32, 'y'): 10,
(32, 'z'): 10,
(33, '0'): 10,
(33, '1'): 10,
(33, '2'): 10,
(33, '3'): 10,
(33, '4'): 10,
(33, '5'): 10,
(33, '6'): 10,
(33, '7'): 10,
(33, '8'): 10,
(33, '9'): 10,
(33, 'A'): 10,
(33, 'B'): 10,
(33, 'C'): 10,
(33, 'D'): 10,
(33, 'E'): 10,
(33, 'F'): 10,
(33, 'G'): 10,
(33, 'H'): 10,
(33, 'I'): 10,
(33, 'J'): 10,
(33, 'K'): 10,
(33, 'L'): 10,
(33, 'M'): 10,
(33, 'N'): 10,
(33, 'O'): 10,
(33, 'P'): 10,
(33, 'Q'): 10,
(33, 'R'): 10,
(33, 'S'): 10,
(33, 'T'): 10,
(33, 'U'): 10,
(33, 'V'): 10,
(33, 'W'): 10,
(33, 'X'): 10,
(33, 'Y'): 10,
(33, 'Z'): 10,
(33, '_'): 10,
(33, 'a'): 10,
(33, 'b'): 10,
(33, 'c'): 10,
(33, 'd'): 10,
(33, 'e'): 10,
(33, 'f'): 10,
(33, 'g'): 10,
(33, 'h'): 10,
(33, 'i'): 10,
(33, 'j'): 10,
(33, 'k'): 10,
(33, 'l'): 10,
(33, 'm'): 10,
(33, 'n'): 10,
(33, 'o'): 34,
(33, 'p'): 10,
(33, 'q'): 10,
(33, 'r'): 10,
(33, 's'): 10,
(33, 't'): 10,
(33, 'u'): 10,
(33, 'v'): 10,
(33, 'w'): 10,
(33, 'x'): 10,
(33, 'y'): 10,
(33, 'z'): 10,
(34, '0'): 10,
(34, '1'): 10,
(34, '2'): 10,
(34, '3'): 10,
(34, '4'): 10,
(34, '5'): 10,
(34, '6'): 10,
(34, '7'): 10,
(34, '8'): 10,
(34, '9'): 10,
(34, 'A'): 10,
(34, 'B'): 10,
(34, 'C'): 10,
(34, 'D'): 10,
(34, 'E'): 10,
(34, 'F'): 10,
(34, 'G'): 10,
(34, 'H'): 10,
(34, 'I'): 10,
(34, 'J'): 10,
(34, 'K'): 10,
(34, 'L'): 10,
(34, 'M'): 10,
(34, 'N'): 10,
(34, 'O'): 10,
(34, 'P'): 10,
(34, 'Q'): 10,
(34, 'R'): 10,
(34, 'S'): 10,
(34, 'T'): 10,
(34, 'U'): 10,
(34, 'V'): 10,
(34, 'W'): 10,
(34, 'X'): 10,
(34, 'Y'): 10,
(34, 'Z'): 10,
(34, '_'): 10,
(34, 'a'): 10,
(34, 'b'): 10,
(34, 'c'): 10,
(34, 'd'): 35,
(34, 'e'): 10,
(34, 'f'): 10,
(34, 'g'): 10,
(34, 'h'): 10,
(34, 'i'): 10,
(34, 'j'): 10,
(34, 'k'): 10,
(34, 'l'): 10,
(34, 'm'): 10,
(34, 'n'): 10,
(34, 'o'): 10,
(34, 'p'): 10,
(34, 'q'): 10,
(34, 'r'): 10,
(34, 's'): 10,
(34, 't'): 10,
(34, 'u'): 10,
(34, 'v'): 10,
(34, 'w'): 10,
(34, 'x'): 10,
(34, 'y'): 10,
(34, 'z'): 10,
(35, '0'): 10,
(35, '1'): 10,
(35, '2'): 10,
(35, '3'): 10,
(35, '4'): 10,
(35, '5'): 10,
(35, '6'): 10,
(35, '7'): 10,
(35, '8'): 10,
(35, '9'): 10,
(35, 'A'): 10,
(35, 'B'): 10,
(35, 'C'): 10,
(35, 'D'): 10,
(35, 'E'): 10,
(35, 'F'): 10,
(35, 'G'): 10,
(35, 'H'): 10,
(35, 'I'): 10,
(35, 'J'): 10,
(35, 'K'): 10,
(35, 'L'): 10,
(35, 'M'): 10,
(35, 'N'): 10,
(35, 'O'): 10,
(35, 'P'): 10,
(35, 'Q'): 10,
(35, 'R'): 10,
(35, 'S'): 10,
(35, 'T'): 10,
(35, 'U'): 10,
(35, 'V'): 10,
(35, 'W'): 10,
(35, 'X'): 10,
(35, 'Y'): 10,
(35, 'Z'): 10,
(35, '_'): 10,
(35, 'a'): 10,
(35, 'b'): 10,
(35, 'c'): 10,
(35, 'd'): 10,
(35, 'e'): 10,
(35, 'f'): 10,
(35, 'g'): 10,
(35, 'h'): 10,
(35, 'i'): 10,
(35, 'j'): 10,
(35, 'k'): 10,
(35, 'l'): 10,
(35, 'm'): 10,
(35, 'n'): 10,
(35, 'o'): 10,
(35, 'p'): 10,
(35, 'q'): 10,
(35, 'r'): 10,
(35, 's'): 10,
(35, 't'): 10,
(35, 'u'): 10,
(35, 'v'): 10,
(35, 'w'): 10,
(35, 'x'): 10,
(35, 'y'): 10,
(35, 'z'): 10,
(36, '0'): 10,
(36, '1'): 10,
(36, '2'): 10,
(36, '3'): 10,
(36, '4'): 10,
(36, '5'): 10,
(36, '6'): 10,
(36, '7'): 10,
(36, '8'): 10,
(36, '9'): 10,
(36, 'A'): 10,
(36, 'B'): 10,
(36, 'C'): 10,
(36, 'D'): 10,
(36, 'E'): 10,
(36, 'F'): 10,
(36, 'G'): 10,
(36, 'H'): 10,
(36, 'I'): 10,
(36, 'J'): 10,
(36, 'K'): 10,
(36, 'L'): 10,
(36, 'M'): 10,
(36, 'N'): 10,
(36, 'O'): 10,
(36, 'P'): 10,
(36, 'Q'): 10,
(36, 'R'): 10,
(36, 'S'): 10,
(36, 'T'): 10,
(36, 'U'): 10,
(36, 'V'): 10,
(36, 'W'): 10,
(36, 'X'): 10,
(36, 'Y'): 10,
(36, 'Z'): 10,
(36, '_'): 10,
(36, 'a'): 10,
(36, 'b'): 10,
(36, 'c'): 10,
(36, 'd'): 10,
(36, 'e'): 10,
(36, 'f'): 10,
(36, 'g'): 10,
(36, 'h'): 10,
(36, 'i'): 10,
(36, 'j'): 10,
(36, 'k'): 10,
(36, 'l'): 10,
(36, 'm'): 10,
(36, 'n'): 10,
(36, 'o'): 10,
(36, 'p'): 10,
(36, 'q'): 10,
(36, 'r'): 10,
(36, 's'): 10,
(36, 't'): 10,
(36, 'u'): 10,
(36, 'v'): 10,
(36, 'w'): 10,
(36, 'x'): 10,
(36, 'y'): 10,
(36, 'z'): 10,
(37, '='): 46,
(39, '.'): 45,
(40, '='): 44,
(42, '='): 43,
(47, '>'): 49,
(50, '0'): 10,
(50, '1'): 10,
(50, '2'): 10,
(50, '3'): 10,
(50, '4'): 10,
(50, '5'): 10,
(50, '6'): 10,
(50, '7'): 10,
(50, '8'): 10,
(50, '9'): 10,
(50, 'A'): 10,
(50, 'B'): 10,
(50, 'C'): 10,
(50, 'D'): 10,
(50, 'E'): 10,
(50, 'F'): 10,
(50, 'G'): 10,
(50, 'H'): 10,
(50, 'I'): 10,
(50, 'J'): 10,
(50, 'K'): 10,
(50, 'L'): 10,
(50, 'M'): 10,
(50, 'N'): 10,
(50, 'O'): 10,
(50, 'P'): 10,
(50, 'Q'): 10,
(50, 'R'): 10,
(50, 'S'): 10,
(50, 'T'): 10,
(50, 'U'): 10,
(50, 'V'): 10,
(50, 'W'): 10,
(50, 'X'): 10,
(50, 'Y'): 10,
(50, 'Z'): 10,
(50, '_'): 10,
(50, 'a'): 10,
(50, 'b'): 10,
(50, 'c'): 10,
(50, 'd'): 10,
(50, 'e'): 10,
(50, 'f'): 10,
(50, 'g'): 10,
(50, 'h'): 10,
(50, 'i'): 10,
(50, 'j'): 10,
(50, 'k'): 10,
(50, 'l'): 10,
(50, 'm'): 51,
(50, 'n'): 10,
(50, 'o'): 10,
(50, 'p'): 10,
(50, 'q'): 10,
(50, 'r'): 10,
(50, 's'): 10,
(50, 't'): 10,
(50, 'u'): 10,
(50, 'v'): 10,
(50, 'w'): 10,
(50, 'x'): 10,
(50, 'y'): 10,
(50, 'z'): 10,
(51, '0'): 10,
(51, '1'): 10,
(51, '2'): 10,
(51, '3'): 10,
(51, '4'): 10,
(51, '5'): 10,
(51, '6'): 10,
(51, '7'): 10,
(51, '8'): 10,
(51, '9'): 10,
(51, 'A'): 10,
(51, 'B'): 10,
(51, 'C'): 10,
(51, 'D'): 10,
(51, 'E'): 10,
(51, 'F'): 10,
(51, 'G'): 10,
(51, 'H'): 10,
(51, 'I'): 10,
(51, 'J'): 10,
(51, 'K'): 10,
(51, 'L'): 10,
(51, 'M'): 10,
(51, 'N'): 10,
(51, 'O'): 10,
(51, 'P'): 10,
(51, 'Q'): 10,
(51, 'R'): 10,
(51, 'S'): 10,
(51, 'T'): 10,
(51, 'U'): 10,
(51, 'V'): 10,
(51, 'W'): 10,
(51, 'X'): 10,
(51, 'Y'): 10,
(51, 'Z'): 10,
(51, '_'): 10,
(51, 'a'): 10,
(51, 'b'): 10,
(51, 'c'): 10,
(51, 'd'): 10,
(51, 'e'): 10,
(51, 'f'): 10,
(51, 'g'): 10,
(51, 'h'): 10,
(51, 'i'): 10,
(51, 'j'): 10,
(51, 'k'): 10,
(51, 'l'): 10,
(51, 'm'): 10,
(51, 'n'): 10,
(51, 'o'): 10,
(51, 'p'): 10,
(51, 'q'): 10,
(51, 'r'): 10,
(51, 's'): 10,
(51, 't'): 10,
(51, 'u'): 10,
(51, 'v'): 10,
(51, 'w'): 10,
(51, 'x'): 10,
(51, 'y'): 10,
(51, 'z'): 10,
(57, '\x00'): 57,
(57, '\x01'): 57,
(57, '\x02'): 57,
(57, '\x03'): 57,
(57, '\x04'): 57,
(57, '\x05'): 57,
(57, '\x06'): 57,
(57, '\x07'): 57,
(57, '\x08'): 57,
(57, '\t'): 57,
(57, '\n'): 57,
(57, '\x0b'): 57,
(57, '\x0c'): 57,
(57, '\r'): 57,
(57, '\x0e'): 57,
(57, '\x0f'): 57,
(57, '\x10'): 57,
(57, '\x11'): 57,
(57, '\x12'): 57,
(57, '\x13'): 57,
(57, '\x14'): 57,
(57, '\x15'): 57,
(57, '\x16'): 57,
(57, '\x17'): 57,
(57, '\x18'): 57,
(57, '\x19'): 57,
(57, '\x1a'): 57,
(57, '\x1b'): 57,
(57, '\x1c'): 57,
(57, '\x1d'): 57,
(57, '\x1e'): 57,
(57, '\x1f'): 57,
(57, ' '): 57,
(57, '!'): 57,
(57, '"'): 57,
(57, '#'): 57,
(57, '$'): 57,
(57, '%'): 57,
(57, '&'): 57,
(57, "'"): 57,
(57, '('): 57,
(57, ')'): 57,
(57, '*'): 60,
(57, '+'): 57,
(57, ','): 57,
(57, '-'): 57,
(57, '.'): 57,
(57, '/'): 57,
(57, '0'): 57,
(57, '1'): 57,
(57, '2'): 57,
(57, '3'): 57,
(57, '4'): 57,
(57, '5'): 57,
(57, '6'): 57,
(57, '7'): 57,
(57, '8'): 57,
(57, '9'): 57,
(57, ':'): 57,
(57, ';'): 57,
(57, '<'): 57,
(57, '='): 57,
(57, '>'): 57,
(57, '?'): 57,
(57, '@'): 57,
(57, 'A'): 57,
(57, 'B'): 57,
(57, 'C'): 57,
(57, 'D'): 57,
(57, 'E'): 57,
(57, 'F'): 57,
(57, 'G'): 57,
(57, 'H'): 57,
(57, 'I'): 57,
(57, 'J'): 57,
(57, 'K'): 57,
(57, 'L'): 57,
(57, 'M'): 57,
(57, 'N'): 57,
(57, 'O'): 57,
(57, 'P'): 57,
(57, 'Q'): 57,
(57, 'R'): 57,
(57, 'S'): 57,
(57, 'T'): 57,
(57, 'U'): 57,
(57, 'V'): 57,
(57, 'W'): 57,
(57, 'X'): 57,
(57, 'Y'): 57,
(57, 'Z'): 57,
(57, '['): 57,
(57, '\\'): 57,
(57, ']'): 57,
(57, '^'): 57,
(57, '_'): 57,
(57, '`'): 57,
(57, 'a'): 57,
(57, 'b'): 57,
(57, 'c'): 57,
(57, 'd'): 57,
(57, 'e'): 57,
(57, 'f'): 57,
(57, 'g'): 57,
(57, 'h'): 57,
(57, 'i'): 57,
(57, 'j'): 57,
(57, 'k'): 57,
(57, 'l'): 57,
(57, 'm'): 57,
(57, 'n'): 57,
(57, 'o'): 57,
(57, 'p'): 57,
(57, 'q'): 57,
(57, 'r'): 57,
(57, 's'): 57,
(57, 't'): 57,
(57, 'u'): 57,
(57, 'v'): 57,
(57, 'w'): 57,
(57, 'x'): 57,
(57, 'y'): 57,
(57, 'z'): 57,
(57, '{'): 57,
(57, '|'): 57,
(57, '}'): 57,
(57, '~'): 57,
(57, '\x7f'): 57,
(57, '\x80'): 57,
(57, '\x81'): 57,
(57, '\x82'): 57,
(57, '\x83'): 57,
(57, '\x84'): 57,
(57, '\x85'): 57,
(57, '\x86'): 57,
(57, '\x87'): 57,
(57, '\x88'): 57,
(57, '\x89'): 57,
(57, '\x8a'): 57,
(57, '\x8b'): 57,
(57, '\x8c'): 57,
(57, '\x8d'): 57,
(57, '\x8e'): 57,
(57, '\x8f'): 57,
(57, '\x90'): 57,
(57, '\x91'): 57,
(57, '\x92'): 57,
(57, '\x93'): 57,
(57, '\x94'): 57,
(57, '\x95'): 57,
(57, '\x96'): 57,
(57, '\x97'): 57,
(57, '\x98'): 57,
(57, '\x99'): 57,
(57, '\x9a'): 57,
(57, '\x9b'): 57,
(57, '\x9c'): 57,
(57, '\x9d'): 57,
(57, '\x9e'): 57,
(57, '\x9f'): 57,
(57, '\xa0'): 57,
(57, '\xa1'): 57,
(57, '\xa2'): 57,
(57, '\xa3'): 57,
(57, '\xa4'): 57,
(57, '\xa5'): 57,
(57, '\xa6'): 57,
(57, '\xa7'): 57,
(57, '\xa8'): 57,
(57, '\xa9'): 57,
(57, '\xaa'): 57,
(57, '\xab'): 57,
(57, '\xac'): 57,
(57, '\xad'): 57,
(57, '\xae'): 57,
(57, '\xaf'): 57,
(57, '\xb0'): 57,
(57, '\xb1'): 57,
(57, '\xb2'): 57,
(57, '\xb3'): 57,
(57, '\xb4'): 57,
(57, '\xb5'): 57,
(57, '\xb6'): 57,
(57, '\xb7'): 57,
(57, '\xb8'): 57,
(57, '\xb9'): 57,
(57, '\xba'): 57,
(57, '\xbb'): 57,
(57, '\xbc'): 57,
(57, '\xbd'): 57,
(57, '\xbe'): 57,
(57, '\xbf'): 57,
(57, '\xc0'): 57,
(57, '\xc1'): 57,
(57, '\xc2'): 57,
(57, '\xc3'): 57,
(57, '\xc4'): 57,
(57, '\xc5'): 57,
(57, '\xc6'): 57,
(57, '\xc7'): 57,
(57, '\xc8'): 57,
(57, '\xc9'): 57,
(57, '\xca'): 57,
(57, '\xcb'): 57,
(57, '\xcc'): 57,
(57, '\xcd'): 57,
(57, '\xce'): 57,
(57, '\xcf'): 57,
(57, '\xd0'): 57,
(57, '\xd1'): 57,
(57, '\xd2'): 57,
(57, '\xd3'): 57,
(57, '\xd4'): 57,
(57, '\xd5'): 57,
(57, '\xd6'): 57,
(57, '\xd7'): 57,
(57, '\xd8'): 57,
(57, '\xd9'): 57,
(57, '\xda'): 57,
(57, '\xdb'): 57,
(57, '\xdc'): 57,
(57, '\xdd'): 57,
(57, '\xde'): 57,
(57, '\xdf'): 57,
(57, '\xe0'): 57,
(57, '\xe1'): 57,
(57, '\xe2'): 57,
(57, '\xe3'): 57,
(57, '\xe4'): 57,
(57, '\xe5'): 57,
(57, '\xe6'): 57,
(57, '\xe7'): 57,
(57, '\xe8'): 57,
(57, '\xe9'): 57,
(57, '\xea'): 57,
(57, '\xeb'): 57,
(57, '\xec'): 57,
(57, '\xed'): 57,
(57, '\xee'): 57,
(57, '\xef'): 57,
(57, '\xf0'): 57,
(57, '\xf1'): 57,
(57, '\xf2'): 57,
(57, '\xf3'): 57,
(57, '\xf4'): 57,
(57, '\xf5'): 57,
(57, '\xf6'): 57,
(57, '\xf7'): 57,
(57, '\xf8'): 57,
(57, '\xf9'): 57,
(57, '\xfa'): 57,
(57, '\xfb'): 57,
(57, '\xfc'): 57,
(57, '\xfd'): 57,
(57, '\xfe'): 57,
(57, '\xff'): 57,
(60, '\x00'): 57,
(60, '\x01'): 57,
(60, '\x02'): 57,
(60, '\x03'): 57,
(60, '\x04'): 57,
(60, '\x05'): 57,
(60, '\x06'): 57,
(60, '\x07'): 57,
(60, '\x08'): 57,
(60, '\t'): 57,
(60, '\n'): 57,
(60, '\x0b'): 57,
(60, '\x0c'): 57,
(60, '\r'): 57,
(60, '\x0e'): 57,
(60, '\x0f'): 57,
(60, '\x10'): 57,
(60, '\x11'): 57,
(60, '\x12'): 57,
(60, '\x13'): 57,
(60, '\x14'): 57,
(60, '\x15'): 57,
(60, '\x16'): 57,
(60, '\x17'): 57,
(60, '\x18'): 57,
(60, '\x19'): 57,
(60, '\x1a'): 57,
(60, '\x1b'): 57,
(60, '\x1c'): 57,
(60, '\x1d'): 57,
(60, '\x1e'): 57,
(60, '\x1f'): 57,
(60, ' '): 57,
(60, '!'): 57,
(60, '"'): 57,
(60, '#'): 57,
(60, '$'): 57,
(60, '%'): 57,
(60, '&'): 57,
(60, "'"): 57,
(60, '('): 57,
(60, ')'): 57,
(60, '*'): 57,
(60, '+'): 57,
(60, ','): 57,
(60, '-'): 57,
(60, '.'): 57,
(60, '/'): 1,
(60, '0'): 57,
(60, '1'): 57,
(60, '2'): 57,
(60, '3'): 57,
(60, '4'): 57,
(60, '5'): 57,
(60, '6'): 57,
(60, '7'): 57,
(60, '8'): 57,
(60, '9'): 57,
(60, ':'): 57,
(60, ';'): 57,
(60, '<'): 57,
(60, '='): 57,
(60, '>'): 57,
(60, '?'): 57,
(60, '@'): 57,
(60, 'A'): 57,
(60, 'B'): 57,
(60, 'C'): 57,
(60, 'D'): 57,
(60, 'E'): 57,
(60, 'F'): 57,
(60, 'G'): 57,
(60, 'H'): 57,
(60, 'I'): 57,
(60, 'J'): 57,
(60, 'K'): 57,
(60, 'L'): 57,
(60, 'M'): 57,
(60, 'N'): 57,
(60, 'O'): 57,
(60, 'P'): 57,
(60, 'Q'): 57,
(60, 'R'): 57,
(60, 'S'): 57,
(60, 'T'): 57,
(60, 'U'): 57,
(60, 'V'): 57,
(60, 'W'): 57,
(60, 'X'): 57,
(60, 'Y'): 57,
(60, 'Z'): 57,
(60, '['): 57,
(60, '\\'): 57,
(60, ']'): 57,
(60, '^'): 57,
(60, '_'): 57,
(60, '`'): 57,
(60, 'a'): 57,
(60, 'b'): 57,
(60, 'c'): 57,
(60, 'd'): 57,
(60, 'e'): 57,
(60, 'f'): 57,
(60, 'g'): 57,
(60, 'h'): 57,
(60, 'i'): 57,
(60, 'j'): 57,
(60, 'k'): 57,
(60, 'l'): 57,
(60, 'm'): 57,
(60, 'n'): 57,
(60, 'o'): 57,
(60, 'p'): 57,
(60, 'q'): 57,
(60, 'r'): 57,
(60, 's'): 57,
(60, 't'): 57,
(60, 'u'): 57,
(60, 'v'): 57,
(60, 'w'): 57,
(60, 'x'): 57,
(60, 'y'): 57,
(60, 'z'): 57,
(60, '{'): 57,
(60, '|'): 57,
(60, '}'): 57,
(60, '~'): 57,
(60, '\x7f'): 57,
(60, '\x80'): 57,
(60, '\x81'): 57,
(60, '\x82'): 57,
(60, '\x83'): 57,
(60, '\x84'): 57,
(60, '\x85'): 57,
(60, '\x86'): 57,
(60, '\x87'): 57,
(60, '\x88'): 57,
(60, '\x89'): 57,
(60, '\x8a'): 57,
(60, '\x8b'): 57,
(60, '\x8c'): 57,
(60, '\x8d'): 57,
(60, '\x8e'): 57,
(60, '\x8f'): 57,
(60, '\x90'): 57,
(60, '\x91'): 57,
(60, '\x92'): 57,
(60, '\x93'): 57,
(60, '\x94'): 57,
(60, '\x95'): 57,
(60, '\x96'): 57,
(60, '\x97'): 57,
(60, '\x98'): 57,
(60, '\x99'): 57,
(60, '\x9a'): 57,
(60, '\x9b'): 57,
(60, '\x9c'): 57,
(60, '\x9d'): 57,
(60, '\x9e'): 57,
(60, '\x9f'): 57,
(60, '\xa0'): 57,
(60, '\xa1'): 57,
(60, '\xa2'): 57,
(60, '\xa3'): 57,
(60, '\xa4'): 57,
(60, '\xa5'): 57,
(60, '\xa6'): 57,
(60, '\xa7'): 57,
(60, '\xa8'): 57,
(60, '\xa9'): 57,
(60, '\xaa'): 57,
(60, '\xab'): 57,
(60, '\xac'): 57,
(60, '\xad'): 57,
(60, '\xae'): 57,
(60, '\xaf'): 57,
(60, '\xb0'): 57,
(60, '\xb1'): 57,
(60, '\xb2'): 57,
(60, '\xb3'): 57,
(60, '\xb4'): 57,
(60, '\xb5'): 57,
(60, '\xb6'): 57,
(60, '\xb7'): 57,
(60, '\xb8'): 57,
(60, '\xb9'): 57,
(60, '\xba'): 57,
(60, '\xbb'): 57,
(60, '\xbc'): 57,
(60, '\xbd'): 57,
(60, '\xbe'): 57,
(60, '\xbf'): 57,
(60, '\xc0'): 57,
(60, '\xc1'): 57,
(60, '\xc2'): 57,
(60, '\xc3'): 57,
(60, '\xc4'): 57,
(60, '\xc5'): 57,
(60, '\xc6'): 57,
(60, '\xc7'): 57,
(60, '\xc8'): 57,
(60, '\xc9'): 57,
(60, '\xca'): 57,
(60, '\xcb'): 57,
(60, '\xcc'): 57,
(60, '\xcd'): 57,
(60, '\xce'): 57,
(60, '\xcf'): 57,
(60, '\xd0'): 57,
(60, '\xd1'): 57,
(60, '\xd2'): 57,
(60, '\xd3'): 57,
(60, '\xd4'): 57,
(60, '\xd5'): 57,
(60, '\xd6'): 57,
(60, '\xd7'): 57,
(60, '\xd8'): 57,
(60, '\xd9'): 57,
(60, '\xda'): 57,
(60, '\xdb'): 57,
(60, '\xdc'): 57,
(60, '\xdd'): 57,
(60, '\xde'): 57,
(60, '\xdf'): 57,
(60, '\xe0'): 57,
(60, '\xe1'): 57,
(60, '\xe2'): 57,
(60, '\xe3'): 57,
(60, '\xe4'): 57,
(60, '\xe5'): 57,
(60, '\xe6'): 57,
(60, '\xe7'): 57,
(60, '\xe8'): 57,
(60, '\xe9'): 57,
(60, '\xea'): 57,
(60, '\xeb'): 57,
(60, '\xec'): 57,
(60, '\xed'): 57,
(60, '\xee'): 57,
(60, '\xef'): 57,
(60, '\xf0'): 57,
(60, '\xf1'): 57,
(60, '\xf2'): 57,
(60, '\xf3'): 57,
(60, '\xf4'): 57,
(60, '\xf5'): 57,
(60, '\xf6'): 57,
(60, '\xf7'): 57,
(60, '\xf8'): 57,
(60, '\xf9'): 57,
(60, '\xfa'): 57,
(60, '\xfb'): 57,
(60, '\xfc'): 57,
(60, '\xfd'): 57,
(60, '\xfe'): 57,
(60, '\xff'): 57,
(61, '0'): 10,
(61, '1'): 10,
(61, '2'): 10,
(61, '3'): 10,
(61, '4'): 10,
(61, '5'): 10,
(61, '6'): 10,
(61, '7'): 10,
(61, '8'): 10,
(61, '9'): 10,
(61, 'A'): 10,
(61, 'B'): 10,
(61, 'C'): 10,
(61, 'D'): 10,
(61, 'E'): 10,
(61, 'F'): 10,
(61, 'G'): 10,
(61, 'H'): 10,
(61, 'I'): 10,
(61, 'J'): 10,
(61, 'K'): 10,
(61, 'L'): 10,
(61, 'M'): 10,
(61, 'N'): 10,
(61, 'O'): 10,
(61, 'P'): 10,
(61, 'Q'): 10,
(61, 'R'): 10,
(61, 'S'): 10,
(61, 'T'): 10,
(61, 'U'): 10,
(61, 'V'): 10,
(61, 'W'): 10,
(61, 'X'): 10,
(61, 'Y'): 10,
(61, 'Z'): 10,
(61, '_'): 10,
(61, 'a'): 10,
(61, 'b'): 10,
(61, 'c'): 10,
(61, 'd'): 10,
(61, 'e'): 10,
(61, 'f'): 10,
(61, 'g'): 10,
(61, 'h'): 10,
(61, 'i'): 10,
(61, 'j'): 10,
(61, 'k'): 10,
(61, 'l'): 10,
(61, 'm'): 10,
(61, 'n'): 10,
(61, 'o'): 10,
(61, 'p'): 10,
(61, 'q'): 10,
(61, 'r'): 62,
(61, 's'): 10,
(61, 't'): 10,
(61, 'u'): 10,
(61, 'v'): 10,
(61, 'w'): 10,
(61, 'x'): 10,
(61, 'y'): 10,
(61, 'z'): 10,
(62, '0'): 10,
(62, '1'): 10,
(62, '2'): 10,
(62, '3'): 10,
(62, '4'): 10,
(62, '5'): 10,
(62, '6'): 10,
(62, '7'): 10,
(62, '8'): 10,
(62, '9'): 10,
(62, 'A'): 10,
(62, 'B'): 10,
(62, 'C'): 10,
(62, 'D'): 10,
(62, 'E'): 10,
(62, 'F'): 10,
(62, 'G'): 10,
(62, 'H'): 10,
(62, 'I'): 10,
(62, 'J'): 10,
(62, 'K'): 10,
(62, 'L'): 10,
(62, 'M'): 10,
(62, 'N'): 10,
(62, 'O'): 10,
(62, 'P'): 10,
(62, 'Q'): 10,
(62, 'R'): 10,
(62, 'S'): 10,
(62, 'T'): 10,
(62, 'U'): 10,
(62, 'V'): 10,
(62, 'W'): 10,
(62, 'X'): 10,
(62, 'Y'): 10,
(62, 'Z'): 10,
(62, '_'): 10,
(62, 'a'): 10,
(62, 'b'): 10,
(62, 'c'): 10,
(62, 'd'): 10,
(62, 'e'): 10,
(62, 'f'): 10,
(62, 'g'): 10,
(62, 'h'): 10,
(62, 'i'): 10,
(62, 'j'): 10,
(62, 'k'): 10,
(62, 'l'): 10,
(62, 'm'): 10,
(62, 'n'): 10,
(62, 'o'): 10,
(62, 'p'): 10,
(62, 'q'): 10,
(62, 'r'): 10,
(62, 's'): 10,
(62, 't'): 10,
(62, 'u'): 10,
(62, 'v'): 10,
(62, 'w'): 10,
(62, 'x'): 10,
(62, 'y'): 10,
(62, 'z'): 10,
(64, '='): 66,
(67, '<'): 71,
(69, '='): 70,
(73, '0'): 74,
(73, '1'): 74,
(73, '2'): 74,
(73, '3'): 74,
(73, '4'): 74,
(73, '5'): 74,
(73, '6'): 74,
(73, '7'): 74,
(73, '8'): 74,
(73, '9'): 74,
(74, '0'): 74,
(74, '1'): 74,
(74, '2'): 74,
(74, '3'): 74,
(74, '4'): 74,
(74, '5'): 74,
(74, '6'): 74,
(74, '7'): 74,
(74, '8'): 74,
(74, '9'): 74},
set([1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 41, 43, 44, 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 74]),
set([1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 41, 43, 44, 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 74]),
['0, start|, 0, start|, 0, 0, 0, 0, 0, start|, 0, 0, 0, start|, 0, start|, 0, start|, 0, 0, 0, 0, start|, 0, start|, 0, start|, 0, start|, 0, start|, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0',
'IGNORE',
'(',
'ATOM',
'NUMBER',
'NUMBER',
'ATOM',
'1, 1, 1, 1',
'VAR',
'ATOM',
'ATOM',
'ATOM',
'|',
'0, 1, 0, start|, 0, final*, start*, 0, 0, 1, final|, start|, 0, final*, start*, 0, 0, final|, start|, 0, 1, final*, start*',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'[',
'ATOM',
'.',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'IGNORE',
')',
'ATOM',
'ATOM',
']',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'2',
'ATOM',
'2',
'2',
'ATOM',
'2',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'2',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'final*, start*, 1, 0, 0, start|, 0, final*, start*, 0, final*, start*, 0, 0, 1, final|, start|, 0, final*, start*, 0, final*, start*, 0, 0, final|, start|, 0, 1, final*, start*, 0, final*, 0, start|, 0, final*, start*, final*, start*, 0, 0, final*, 1, final|, final*, 0, start|, 0, final*, start*, final*, start*, 0, 0, final*, final|, 1, final*, 0, 1, final|, start|, 0, final*, start*, final*, start*, 0, 0, final*, final*, 0, final|, start|, 0, 1, final*, start*, final*, start*, 0, 0, final*',
'ATOM',
'ATOM',
'1, 0, 1, 0, start|',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'2',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'ATOM',
'1, 0',
'NUMBER']), {'IGNORE': None})
basic_rules = [Rule('query', [['toplevel_op_expr', '.', 'EOF']]), Rule('fact', [['toplevel_op_expr', '.']]), Rule('complexterm', [['ATOM', '(', 'toplevel_op_expr', ')'], ['expr']]), Rule('expr', [['VAR'], ['NUMBER'], ['+', 'NUMBER'], ['-', 'NUMBER'], ['ATOM'], ['(', 'toplevel_op_expr', ')'], ['listexpr']]), Rule('listexpr', [['[', 'listbody', ']']]), Rule('listbody', [['toplevel_op_expr', '|', 'toplevel_op_expr'], ['toplevel_op_expr']])]
# generated code between this line and its other occurence
if __name__ == '__main__':
f = py.magic.autopath()
oldcontent = f.read()
s = "# GENERATED CODE BETWEEN THIS LINE AND ITS OTHER OCCURENCE\n".lower()
pre, gen, after = oldcontent.split(s)
lexer, parser_fact, parser_query, basic_rules = make_all()
newcontent = ("%s%s\nparser_fact = %r\nparser_query = %r\n%s\n"
"basic_rules = %r\n%s%s") % (
pre, s, parser_fact, parser_query, lexer.get_dummy_repr(),
basic_rules, s, after)
print newcontent
f.write(newcontent)
| Python |
import py, sys
rootdir = py.magic.autopath().dirpath()
Option = py.test.config.Option
option = py.test.config.addoptions("prolog options",
Option('--slow', action="store_true", dest="slow", default=False,
help="view translation tests' flow graphs with Pygame"),
)
| Python |
#!/usr/bin/env python
try:
import autopath
except ImportError:
pass
import py
import sys
#sys.path.append(str(py.magic.autopath().dirpath().dirpath()))
from pypy.rlib.parsing.parsing import ParseError
from pypy.rlib.parsing.deterministic import LexerError
from pypy.lang.prolog.interpreter.parsing import parse_file, get_query_and_vars
from pypy.lang.prolog.interpreter.parsing import get_engine
from pypy.lang.prolog.interpreter.engine import Engine
from pypy.lang.prolog.interpreter.engine import Continuation
from pypy.lang.prolog.interpreter import error
import pypy.lang.prolog.interpreter.term
pypy.lang.prolog.interpreter.term.DEBUG = False
import code
helptext = """
';': redo
'p': print
'h': help
"""
class StopItNow(Exception):
pass
class ContinueContinuation(Continuation):
def __init__(self, var_to_pos, write):
self.var_to_pos = var_to_pos
self.write = write
def _call(self, engine):
self.write("yes\n")
var_representation(self.var_to_pos, engine, self.write)
while 1:
res = getch()
self.write(res+"\n")
if res in "\r\x04":
self.write("\n")
raise StopItNow()
if res in ";nr":
raise error.UnificationFailed
elif res in "h?":
self.write(helptext)
elif res in "p":
var_representation(self.var_to_pos, engine, self.write)
else:
self.write('unknown action. press "h" for help\n')
def var_representation(var_to_pos, engine, write):
from pypy.lang.prolog.builtin.formatting import TermFormatter
f = TermFormatter(engine, quoted=True, max_depth=10)
vars = var_to_pos.items()
vars.sort()
heap = engine.heap
for var, real_var in vars:
if var.startswith("_"):
continue
val = real_var.getvalue(heap)
write("%s = %s\n" % (var, f.format(val)))
class PrologConsole(code.InteractiveConsole):
def __init__(self, engine):
code.InteractiveConsole.__init__(self, {})
del self.__dict__['compile']
self.engine = engine
def compile(self, source, filename="<input>", symbol="single"):
try:
if not source.strip():
return None, None
return get_query_and_vars(source)
except ParseError, exc:
self.write(exc.nice_error_message("<stdin>", source) + "\n")
raise SyntaxError
except LexerError, exc:
self.write(exc.nice_error_message("<stdin>") + "\n")
raise SyntaxError
def runcode(self, code):
try:
query, var_to_pos = code
if query is None:
return
self.engine.run(query, ContinueContinuation(var_to_pos, self.write))
except error.UnificationFailed:
self.write("no\n")
except error.CatchableError, e:
self.write("ERROR: ")
if e.term.args[0].name == "instantiation_error":
print e.term
self.write("arguments not sufficiently instantiated\n")
elif e.term.args[0].name == "existence_error":
print e.term
self.write("Undefined %s: %s\n" % (e.term.args[0].args[0],
e.term.args[0].args[1]))
else:
self.write("of unknown type: %s\n" % (e.term, ))
except error.UncatchableError, e:
self.write("INTERNAL ERROR: %s\n" % (e.message, ))
except StopItNow:
self.write("yes\n")
def showtracebach(self):
self.write("traceback. boooring. nothing to see here")
class _Getch(object):
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
import msvcrt
self.impl = self.get_windows
except ImportError:
try:
import tty, sys, termios
self.impl = self.get_unix
except ImportError:
import Carbon, Carbon.Evt
self.impl = self.get_carbon
def __call__(self):
return self.impl()
def get_unix(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def get_windows(self):
import msvcrt
return msvcrt.getch()
def get_carbon(self):
"""
A function which returns the current ASCII key that is down;
if no ASCII key is down, the null string is returned. The
page http://www.mactech.com/macintosh-c/chap02-1.html was
very helpful in figuring out how to do this.
"""
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
return ''
else:
# The message (msg) contains the ASCII char which is
# extracted with the 0x000000FF charCodeMask; this
# number is converted to an ASCII character with chr() and
# returned
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
return chr(msg & 0x000000FF)
getch = _Getch()
def main():
import readline
oldps1 = getattr(sys, "ps1", ">>> ")
oldps2 = getattr(sys, "ps2", "... ")
try:
sys.ps1 = ">?- "
sys.ps2 = "... "
if not len(sys.argv) == 2:
e = Engine()
else:
try:
source = py.path.local(sys.argv[1]).read()
e = get_engine(source)
except ParseError, exc:
print exc.nice_error_message("<stdin>", source) + "\n"
sys.exit(1)
except LexerError, exc:
print exc.nice_error_message("<stdin>") + "\n"
sys.exit(1)
c = PrologConsole(e)
c.interact("PyPy Prolog Console")
finally:
sys.ps1 = oldps1
sys.ps2 = oldps2
if __name__ == '__main__':
main()
| Python |
import py
import math
from pypy.lang.prolog.interpreter.parsing import parse_file, TermBuilder
from pypy.lang.prolog.interpreter import engine, helper, term, error
from pypy.lang.prolog.interpreter.error import UnificationFailed, FunctionNotFound
from pypy.rlib.rarithmetic import intmask
from pypy.rlib.jit import we_are_jitted, hint
from pypy.rlib.unroll import unrolling_iterable
arithmetic_functions = {}
arithmetic_functions_list = []
class CodeCollector(object):
def __init__(self):
self.code = []
self.blocks = []
def emit(self, line):
for line in line.split("\n"):
self.code.append(" " * (4 * len(self.blocks)) + line)
def start_block(self, blockstarter):
assert blockstarter.endswith(":")
self.emit(blockstarter)
self.blocks.append(blockstarter)
def end_block(self, starterpart=""):
block = self.blocks.pop()
assert starterpart in block, "ended wrong block %s with %s" % (
block, starterpart)
def tostring(self):
assert not self.blocks
return "\n".join(self.code)
def wrap_builtin_operation(name, pattern, unwrap_spec, can_overflow, intversion):
code = CodeCollector()
code.start_block("def prolog_%s(engine, query):" % name)
for i, spec in enumerate(unwrap_spec):
varname = "var%s" % (i, )
code.emit("%s = eval_arithmetic(engine, query.args[%s])" %
(varname, i))
for i, spec in enumerate(unwrap_spec):
varname = "var%s" % (i, )
if spec == "int":
code.start_block(
"if not isinstance(%s, term.Number):" % (varname, ))
code.emit("error.throw_type_error('int', %s)" % (varname, ))
code.end_block("if")
if "expr" in unwrap_spec and intversion:
# check whether all arguments are ints
for i, spec in enumerate(unwrap_spec):
varname = "var%s" % (i, )
if spec == "int":
continue
code.start_block(
"if isinstance(%s, term.Number):" % (varname, ))
code.emit("v%s = var%s.num" % (i, i))
code.emit("return term.Number(int(%s))" % (pattern, ))
for i, spec in enumerate(unwrap_spec):
if spec == "int":
continue
code.end_block("if")
#general case in an extra function
args = ", ".join(["var%s" % i for i in range(len(unwrap_spec))])
code.emit("return general_%s(%s)" % (name, args))
code.end_block("def")
code.start_block("def general_%s(%s):" % (name, args))
for i, spec in enumerate(unwrap_spec):
varname = "var%s" % (i, )
code.emit("v%s = 0" % (i, ))
code.start_block("if isinstance(%s, term.Number):" % (varname, ))
code.emit("v%s = %s.num" % (i, varname))
code.end_block("if")
expected = 'int'
if spec == "expr":
code.start_block("elif isinstance(%s, term.Float):" % (varname, ))
code.emit("v%s = %s.floatval" % (i, varname))
code.end_block("elif")
expected = 'float'
code.start_block("else:")
code.emit("error.throw_type_error('%s', %s)" % (expected, varname, ))
code.end_block("else")
code.emit("return norm_float(term.Float(%s))" % pattern)
code.end_block("def")
miniglobals = globals().copy()
exec py.code.Source(code.tostring()).compile() in miniglobals
result = miniglobals["prolog_" + name]
result._look_inside_me_ = True
return result
wrap_builtin_operation._annspecialcase_ = 'specialize:memo'
def eval_arithmetic(engine, query):
return query.eval_arithmetic(engine)
eval_arithmetic._look_inside_me_ = True
def norm_float(obj):
v = obj.floatval
if v == int(v):
return term.Number(int(v))
else:
return obj
simple_functions = [
("+", ["expr", "expr"], "v0 + v1", True, True),
("-", ["expr", "expr"], "v0 - v1", True, True),
("*", ["expr", "expr"], "v0 * v1", True, True),
("//", ["int", "int"], "v0 / v1", True, False),
("**", ["expr", "expr"], "float(v0) ** float(v1)", True, False),
(">>", ["int", "int"], "v0 >> v1", False, False),
("<<", ["int", "int"], "intmask(v0 << v1)", False,
False),
("\\/", ["int", "int"], "v0 | v1", False, False),
("/\\", ["int", "int"], "v0 & v1", False, False),
("xor", ["int", "int"], "v0 ^ v1", False, False),
("mod", ["int", "int"], "v0 % v1", False, False),
("\\", ["int"], "~v0", False, False),
("abs", ["expr"], "abs(v0)", True, True),
("max", ["expr", "expr"], "max(v0, v1)", False, True),
("min", ["expr", "expr"], "min(v0, v1)", False, True),
("round", ["expr"], "int(v0 + 0.5)", False, False),
("floor", ["expr"], "math.floor(v0)", False, False), #XXX
("ceiling", ["expr"], "math.ceil(v0)", False, False), #XXX
("float_fractional_part", ["expr"], "v0 - int(v0)", False, False), #XXX
("float_integer_part", ["expr"], "int(v0)", False, True),
]
for prolog_name, unwrap_spec, pattern, overflow, intversion in simple_functions:
# the name is purely for flowgraph viewing reasons
if prolog_name.replace("_", "").isalnum():
name = prolog_name
else:
import unicodedata
name = "".join([unicodedata.name(unicode(c)).replace(" ", "_").replace("-", "").lower() for c in prolog_name])
f = wrap_builtin_operation(name, pattern, unwrap_spec, overflow,
intversion)
signature = "%s/%s" % (prolog_name, len(unwrap_spec))
arithmetic_functions[signature] = f
arithmetic_functions_list.append((signature, f))
arithmetic_functions_list = unrolling_iterable(arithmetic_functions_list)
| Python |
import os
import py
from py.magic import greenlet
from pypy.rlib.objectmodel import we_are_translated
from pypy.rpython.rstack import yield_current_heap_to_caller
from pypy.translator.c.test.test_stackless import StacklessTest
from pypy.lang.prolog.interpreter.error import UnificationFailed, CutException
def make_llheap(choice_point, func, args):
llheap = yield_current_heap_to_caller()
try:
choice_point.current = llheap
try:
func(*args)
except UnificationFailed:
choice_point.no_choice()
except Exception, e:
choice_point.exception = e
choice_point.switch_back()
except:
pass
os.write(0, "bad\n")
return llheap # will nexer be executed, help the translator
make_llheap._annspecialcase_ = "specialize:arg(1)"
class ChoicePoint(object):
def __init__(self, engine, continuation, stop_cut=False):
self._init_current()
self.engine = engine
self.oldstate = engine.heap.branch()
self.continuation = continuation
self.stop_cut = stop_cut
self.any_choice = True
self.exception = None
def _init_current(self):
if we_are_translated():
self.current = None
else:
self.current = greenlet.getcurrent()
def choose(self, last=False):
try:
self.do_continue()
except CutException, e:
if self.stop_cut:
self.continuation = e.continuation
else:
self.exception = e
except UnificationFailed:
self.engine.heap.revert(self.oldstate)
if last:
raise
return
self.switch_back()
assert 0
def chooselast(self):
self.do_continue()
def no_choice(self):
self.exception = UnificationFailed()
def switch(self, func, *args):
if we_are_translated():
llheap = make_llheap(self, func, args)
llheap.switch()
else:
g = greenlet(func)
try:
g.switch(*args)
except UnificationFailed:
self.no_choice()
if self.exception is not None:
raise self.exception
switch._annspecialcase_ = "specialize:arg(1)"
def switch_back(self):
self.current.switch()
def do_continue(self):
self.continuation.run(self.engine)
class RuleChoicePoint(ChoicePoint):
def __init__(self, query, engine, continuation, stop_cut=False):
ChoicePoint.__init__(self, engine, continuation, stop_cut)
self.query = query
self.rule = None
def choose_rule(self, rule):
self.rule = rule
self.choose()
def choose_last_rule(self, rule):
self.rule = rule
self.chooselast()
def do_continue(self):
continuation = self.continuation
self.engine.try_rule(self.rule, self.query, continuation)
| 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 math
from pypy.rlib.objectmodel import we_are_translated, UnboxedValue
from pypy.rlib.rarithmetic import intmask
from pypy.lang.prolog.interpreter.error import UnificationFailed, UncatchableError
from pypy.lang.prolog.interpreter import error
from pypy.rlib.jit import hint
from pypy.rlib.objectmodel import specialize
from pypy.rlib.jit import we_are_jitted, hint, purefunction
DEBUG = False
TAGBITS = 3
CURR_TAG = 1
def tag():
global CURR_TAG
CURR_TAG += 1
assert CURR_TAG <= 2 ** TAGBITS
return CURR_TAG
def debug_print(*args):
if DEBUG and not we_are_translated():
print " ".join([str(a) for a in args])
class PrologObject(object):
__slots__ = ()
_immutable_ = True
def __init__(self):
raise NotImplementedError("abstract base class")
return self
def getvalue(self, heap):
return self
def dereference(self, heap):
raise NotImplementedError("abstract base class")
def copy(self, heap, memo):
raise NotImplementedError("abstract base class")
def copy_and_unify(self, other, heap, memo):
raise NotImplementedError("abstract base class")
def get_unify_hash(self, heap):
# if two non-var objects return two different numbers
# they must not be unifiable
raise NotImplementedError("abstract base class")
@specialize.arg(3)
def unify(self, other, heap, occurs_check=False):
raise NotImplementedError("abstract base class")
@specialize.arg(3)
def _unify(self, other, heap, occurs_check=False):
raise NotImplementedError("abstract base class")
def contains_var(self, var, heap):
return False
def __eq__(self, other):
# for testing
return (self.__class__ == other.__class__ and
self.__dict__ == other.__dict__)
def __ne__(self, other):
# for testing
return not (self == other)
def eval_arithmetic(self, engine):
error.throw_type_error("evaluable", self)
class Var(PrologObject):
TAG = 0
STANDARD_ORDER = 0
__slots__ = ('binding', )
cache = {}
def __init__(self, heap=None):
self.binding = None
@specialize.arg(3)
def unify(self, other, heap, occurs_check=False):
return self.dereference(heap)._unify(other, heap, occurs_check)
@specialize.arg(3)
def _unify(self, other, heap, occurs_check=False):
other = other.dereference(heap)
if isinstance(other, Var) and other is self:
pass
elif occurs_check and other.contains_var(self, heap):
raise UnificationFailed()
else:
self.setvalue(other, heap)
def dereference(self, heap):
next = self.binding
if next is None:
return self
else:
result = next.dereference(heap)
# do path compression
self.setvalue(result, heap)
return result
def getvalue(self, heap):
res = self.dereference(heap)
if not isinstance(res, Var):
return res.getvalue(heap)
return res
def setvalue(self, value, heap):
heap.add_trail(self)
self.binding = value
def copy(self, heap, memo):
hint(self, concrete=True)
try:
return memo[self]
except KeyError:
newvar = memo[self] = heap.newvar()
return newvar
def copy_and_unify(self, other, heap, memo):
hint(self, concrete=True)
self = hint(self, deepfreeze=True)
try:
seen_value = memo[self]
except KeyError:
memo[self] = other
return other
else:
seen_value.unify(other, heap)
return seen_value
def get_unify_hash(self, heap):
if heap is not None:
self = self.dereference(heap)
if isinstance(self, Var):
return 0
return self.get_unify_hash(heap)
return 0
def contains_var(self, var, heap):
self = self.dereference(heap)
if self is var:
return True
if not isinstance(self, Var):
return self.contains_var(var, heap)
return False
def __repr__(self):
return "Var(%s)" % (self.binding, )
def __eq__(self, other):
# for testing
return self is other
def eval_arithmetic(self, engine):
self = self.dereference(engine.heap)
if isinstance(self, Var):
error.throw_instantiation_error()
return self.eval_arithmetic(engine)
class NonVar(PrologObject):
__slots__ = ()
def dereference(self, heap):
return self
@specialize.arg(3)
def unify(self, other, heap, occurs_check=False):
return self._unify(other, heap, occurs_check)
@specialize.arg(3)
def basic_unify(self, other, heap, occurs_check=False):
raise NotImplementedError("abstract base class")
@specialize.arg(3)
def _unify(self, other, heap, occurs_check=False):
other = other.dereference(heap)
if isinstance(other, Var):
other._unify(self, heap, occurs_check)
else:
self.basic_unify(other, heap, occurs_check)
def copy_and_unify(self, other, heap, memo):
other = other.dereference(heap)
if isinstance(other, Var):
copy = self.copy(heap, memo)
other._unify(copy, heap)
return copy
else:
return self.copy_and_basic_unify(other, heap, memo)
def copy_and_basic_unify(self, other, heap, memo):
raise NotImplementedError("abstract base class")
class Callable(NonVar):
__slots__ = ("name", "signature")
name = ""
signature = ""
def get_prolog_signature(self):
raise NotImplementedError("abstract base")
def unify_hash_of_children(self, heap):
raise NotImplementedError("abstract base")
class Atom(Callable):
TAG = tag()
STANDARD_ORDER = 1
cache = {}
_immutable_ = True
def __init__(self, name):
self.name = name
self.signature = self.name + "/0"
def __str__(self):
return self.name
def __repr__(self):
return "Atom(%r)" % (self.name,)
@specialize.arg(3)
def basic_unify(self, other, heap, occurs_check=False):
if isinstance(other, Atom) and (self is other or
other.name == self.name):
return
raise UnificationFailed
def copy(self, heap, memo):
return self
def copy_and_basic_unify(self, other, heap, memo):
hint(self, concrete=True)
if isinstance(other, Atom) and (self is other or
other.name == self.name):
return self
else:
raise UnificationFailed
def get_unify_hash(self, heap):
name = hint(self.name, promote=True)
return intmask(hash(name) << TAGBITS | self.TAG)
def unify_hash_of_children(self, heap):
return []
def get_prolog_signature(self):
return Term("/", [self, NUMBER_0])
@staticmethod
@purefunction
def newatom(name):
result = Atom.cache.get(name, None)
if result is not None:
return result
Atom.cache[name] = result = Atom(name)
return result
def eval_arithmetic(self, engine):
#XXX beautify that
if self.name == "pi":
return Float.pi
if self.name == "e":
return Float.e
error.throw_type_error("evaluable", self.get_prolog_signature())
class Number(NonVar):
TAG = tag()
STANDARD_ORDER = 2
_immutable_ = True
def __init__(self, num):
self.num = num
@specialize.arg(3)
def basic_unify(self, other, heap, occurs_check=False):
if isinstance(other, Number) and other.num == self.num:
return
raise UnificationFailed
def copy(self, heap, memo):
return self
def copy_and_basic_unify(self, other, heap, memo):
hint(self, concrete=True)
if isinstance(other, Number) and other.num == self.num:
return self
else:
raise UnificationFailed
def __str__(self):
return repr(self.num)
def __repr__(self):
return "Number(%r)" % (self.num, )
def get_unify_hash(self, heap):
return intmask(self.num << TAGBITS | self.TAG)
def eval_arithmetic(self, engine):
return self
NUMBER_0 = Number(0)
class Float(NonVar):
TAG = tag()
STANDARD_ORDER = 2
_immutable_ = True
def __init__(self, floatval):
self.floatval = floatval
@specialize.arg(3)
def basic_unify(self, other, heap, occurs_check=False):
if isinstance(other, Float) and other.floatval == self.floatval:
return
raise UnificationFailed
def copy(self, heap, memo):
return self
def copy_and_basic_unify(self, other, heap, memo):
hint(self, concrete=True)
if isinstance(other, Float) and other.floatval == self.floatval:
return self
else:
raise UnificationFailed
def get_unify_hash(self, heap):
#XXX no clue whether this is a good idea...
m, e = math.frexp(self.floatval)
m = intmask(int(m / 2 * 2 ** (32 - TAGBITS)))
return intmask(m << TAGBITS | self.TAG)
def __str__(self):
return repr(self.floatval)
def __repr__(self):
return "Float(%r)" % (self.floatval, )
def eval_arithmetic(self, engine):
from pypy.lang.prolog.interpreter.arithmetic import norm_float
return norm_float(self)
Float.e = Float(math.e)
Float.pi = Float(math.pi)
class BlackBox(NonVar):
# meant to be subclassed
TAG = tag()
STANDARD_ORDER = 4
def __init__(self):
pass
@specialize.arg(3)
def basic_unify(self, other, heap, occurs_check=False):
if self is other:
return
raise UnificationFailed
def copy(self, heap, memo):
return self
def copy_and_basic_unify(self, other, heap, memo):
hint(self, concrete=True)
if self is other:
return self
else:
raise UnificationFailed
def get_unify_hash(self, heap):
return intmask(id(self) << TAGBITS | self.TAG)
# helper functions for various Term methods
def _clone(obj, offset):
return obj.clone(offset)
def _getvalue(obj, heap):
return obj.getvalue(heap)
class Term(Callable):
TAG = tag()
STANDARD_ORDER = 3
_immutable_ = True
def __init__(self, name, args, signature=None):
self.name = name
self.args = args
if signature is None:
self.signature = name + "/" + str(len(args))
else:
self.signature = signature
def __repr__(self):
return "Term(%r, %r)" % (self.name, self.args)
def __str__(self):
return "%s(%s)" % (self.name, ", ".join([str(a) for a in self.args]))
@specialize.arg(3)
def basic_unify(self, other, heap, occurs_check=False):
if (isinstance(other, Term) and
self.name == other.name and
len(self.args) == len(other.args)):
for i in range(len(self.args)):
self.args[i].unify(other.args[i], heap, occurs_check)
else:
raise UnificationFailed
def copy(self, heap, memo):
hint(self, concrete=True)
self = hint(self, deepfreeze=True)
newargs = []
i = 0
while i < len(self.args):
hint(i, concrete=True)
arg = self.args[i].copy(heap, memo)
newargs.append(arg)
i += 1
return Term(self.name, newargs, self.signature)
def copy_and_basic_unify(self, other, heap, memo):
hint(self, concrete=True)
self = hint(self, deepfreeze=True)
if (isinstance(other, Term) and
self.signature == other.signature):
newargs = [None] * len(self.args)
i = 0
while i < len(self.args):
hint(i, concrete=True)
arg = self.args[i].copy_and_unify(other.args[i], heap, memo)
newargs[i] = arg
i += 1
return Term(self.name, newargs, self.signature)
else:
raise UnificationFailed
def getvalue(self, heap):
return self._copy_term(_getvalue, heap)
def _copy_term(self, copy_individual, *extraargs):
args = [None] * len(self.args)
newinstance = False
for i in range(len(self.args)):
arg = self.args[i]
cloned = copy_individual(arg, *extraargs)
if cloned is not arg:
newinstance = True
args[i] = cloned
if newinstance:
return Term(self.name, args, self.signature)
else:
return self
def get_unify_hash(self, heap):
signature = hint(self.signature, promote=True)
return intmask(hash(signature) << TAGBITS | self.TAG)
def unify_hash_of_children(self, heap):
unify_hash = []
i = 0
while i < len(self.args):
unify_hash.append(self.args[i].get_unify_hash(heap))
i += 1
return unify_hash
def get_prolog_signature(self):
return Term("/", [Atom.newatom(self.name), Number(len(self.args))])
def contains_var(self, var, heap):
for arg in self.args:
if arg.contains_var(var, heap):
return True
return False
def eval_arithmetic(self, engine):
from pypy.lang.prolog.interpreter.arithmetic import arithmetic_functions
from pypy.lang.prolog.interpreter.arithmetic import arithmetic_functions_list
if we_are_jitted():
signature = hint(self.signature, promote=True)
func = None
for sig, func in arithmetic_functions_list:
if sig == signature:
break
else:
func = arithmetic_functions.get(self.signature, None)
if func is None:
error.throw_type_error("evaluable", self.get_prolog_signature())
return func(engine, self)
class Rule(object):
_immutable_ = True
unify_hash = []
def __init__(self, head, body):
from pypy.lang.prolog.interpreter import helper
assert isinstance(head, Callable)
self.head = head
if body is not None:
body = helper.ensure_callable(body)
self.body = body
else:
self.body = None
self.signature = self.head.signature
if isinstance(head, Term):
self.unify_hash = [arg.get_unify_hash(None) for arg in head.args]
self._does_contain_cut()
def _does_contain_cut(self):
if self.body is None:
self.contains_cut = False
return
stack = [self.body]
while stack:
current = stack.pop()
if isinstance(current, Atom):
if current.name == "!":
self.contains_cut = True
return
elif isinstance(current, Term):
stack.extend(current.args)
self.contains_cut = False
def clone_and_unify_head(self, heap, head):
memo = {}
h2 = self.head
hint(h2, concrete=True)
if isinstance(h2, Term):
assert isinstance(head, Term)
i = 0
while i < len(h2.args):
i = hint(i, concrete=True)
arg2 = h2.args[i]
arg1 = head.args[i]
arg2.copy_and_unify(arg1, heap, memo)
i += 1
body = self.body
hint(body, concrete=True)
if body is None:
return None
return body.copy(heap, memo)
def __repr__(self):
if self.body is None:
return "%s." % (self.head, )
return "%s :- %s." % (self.head, self.body)
@specialize.argtype(0)
def rcmp(a, b): # RPython does not support cmp...
if a == b:
return 0
if a < b:
return -1
return 1
def cmp_standard_order(obj1, obj2, heap):
c = rcmp(obj1.STANDARD_ORDER, obj2.STANDARD_ORDER)
if c != 0:
return c
if isinstance(obj1, Var):
assert isinstance(obj2, Var)
return rcmp(id(obj1), id(obj2))
if isinstance(obj1, Atom):
assert isinstance(obj2, Atom)
return rcmp(obj1.name, obj2.name)
if isinstance(obj1, Term):
assert isinstance(obj2, Term)
c = rcmp(len(obj1.args), len(obj2.args))
if c != 0:
return c
c = rcmp(obj1.name, obj2.name)
if c != 0:
return c
for i in range(len(obj1.args)):
a1 = obj1.args[i].dereference(heap)
a2 = obj2.args[i].dereference(heap)
c = cmp_standard_order(a1, a2, heap)
if c != 0:
return c
return 0
# XXX hum
if isinstance(obj1, Number):
if isinstance(obj2, Number):
return rcmp(obj1.num, obj2.num)
elif isinstance(obj2, Float):
return rcmp(obj1.num, obj2.floatval)
if isinstance(obj1, Float):
if isinstance(obj2, Number):
return rcmp(obj1.floatval, obj2.num)
elif isinstance(obj2, Float):
return rcmp(obj1.floatval, obj2.floatval)
assert 0
| Python |
""" Helper functions for dealing with prolog terms"""
from pypy.lang.prolog.interpreter import term
from pypy.lang.prolog.interpreter import error
emptylist = term.Atom.newatom("[]")
def wrap_list(python_list):
curr = emptylist
for i in range(len(python_list) - 1, -1, -1):
curr = term.Term(".", [python_list[i], curr])
return curr
def unwrap_list(prolog_list):
result = []
curr = prolog_list
while isinstance(curr, term.Term):
if not curr.name == ".":
error.throw_type_error("list", prolog_list)
result.append(curr.args[0])
curr = curr.args[1]
if isinstance(curr, term.Atom) and curr.name == "[]":
return result
error.throw_type_error("list", prolog_list)
def is_callable(var, engine):
return isinstance(var, term.Callable)
is_callable._look_inside_me_ = True
def ensure_callable(var):
if isinstance(var, term.Var):
error.throw_instantiation_error()
elif isinstance(var, term.Callable):
return var
else:
error.throw_type_error("callable", var)
ensure_callable._look_inside_me_ = True
def unwrap_int(obj):
if isinstance(obj, term.Number):
return obj.num
elif isinstance(obj, term.Float):
f = obj.floatval; i = int(f)
if f == i:
return i
error.throw_type_error('integer', obj)
def unwrap_atom(obj):
if isinstance(obj, term.Atom):
return obj.name
error.throw_type_error('atom', obj)
unwrap_atom._look_inside_me_ = True
def unwrap_predicate_indicator(predicate):
if not isinstance(predicate, term.Term):
error.throw_type_error("predicate_indicator", predicate)
assert 0, "unreachable"
if not predicate.name == "/" or len(predicate.args) != 2:
error.throw_type_error("predicate_indicator", predicate)
name = unwrap_atom(predicate.args[0])
arity = unwrap_int(predicate.args[1])
return name, arity
def ensure_atomic(obj):
if not is_atomic(obj):
error.throw_type_error('atomic', obj)
return obj
def is_atomic(obj):
return (isinstance(obj, term.Atom) or isinstance(obj, term.Float) or
isinstance(obj, term.Number))
def convert_to_str(obj):
if isinstance(obj, term.Var):
error.throw_instantiation_error()
if isinstance(obj, term.Atom):
return obj.name
elif isinstance(obj, term.Number):
return str(obj.num)
elif isinstance(obj, term.Float):
return str(obj.floatval)
error.throw_type_error("atomic", obj)
| Python |
from pypy.lang.prolog.interpreter.term import Var, Term, Rule, Atom, debug_print, \
Callable
from pypy.lang.prolog.interpreter.error import UnificationFailed, FunctionNotFound, \
CutException
from pypy.lang.prolog.interpreter import error
from pypy.rlib.jit import hint, we_are_jitted, _is_early_constant, purefunction
from pypy.rlib.objectmodel import specialize
from pypy.rlib.unroll import unrolling_iterable
DEBUG = False
# bytecodes:
CALL = 'a'
USER_CALL = 'u'
TRY_RULE = 't'
CONTINUATION = 'c'
DONE = 'd'
class Continuation(object):
def call(self, engine, choice_point=True):
if choice_point:
return engine.main_loop(CONTINUATION, None, self, None)
return (CONTINUATION, None, self, None)
def _call(self, engine):
return (DONE, None, None, None)
DONOTHING = Continuation()
class LimitedScopeContinuation(Continuation):
def __init__(self, continuation):
self.scope_active = True
self.continuation = continuation
def _call(self, engine):
self.scope_active = False
return self.continuation.call(engine, choice_point=False)
class Heap(object):
def __init__(self):
self.trail = []
def reset(self):
self.trail = []
self.last_branch = 0
def add_trail(self, var):
self.trail.append((var, var.binding))
def branch(self):
return len(self.trail)
def revert(self, state):
trails = state
for i in range(len(self.trail) - 1, trails - 1, -1):
var, val = self.trail[i]
var.binding = val
del self.trail[trails:]
def discard(self, state):
pass #XXX for now
def maxvar(self):
XXX
return self.needed_vars
def newvar(self):
result = Var(self)
return result
class LinkedRules(object):
_immutable_ = True
def __init__(self, rule, next=None):
self.rule = rule
self.next = next
def copy(self, stopat=None):
first = LinkedRules(self.rule)
curr = self.next
copy = first
while curr is not stopat:
new = LinkedRules(curr.rule)
copy.next = new
copy = new
curr = curr.next
return first, copy
def find_applicable_rule(self, uh2):
#import pdb;pdb.set_trace()
while self:
uh = self.rule.unify_hash
hint(uh, concrete=True)
uh = hint(uh, deepfreeze=True)
j = 0
while j < len(uh):
hint(j, concrete=True)
hash1 = uh[j]
hash2 = uh2[j]
if hash1 != 0 and hash2 * (hash2 - hash1) != 0:
break
j += 1
else:
return self
self = self.next
return None
def __repr__(self):
return "LinkedRules(%r, %r)" % (self.rule, self.next)
class Function(object):
def __init__(self, firstrule=None):
if firstrule is None:
self.rulechain = self.last = None
else:
self.rulechain = LinkedRules(firstrule)
self.last = self.rulechain
def add_rule(self, rule, end):
if self.rulechain is None:
self.rulechain = self.last = LinkedRules(rule)
elif end:
self.rulechain, last = self.rulechain.copy()
self.last = LinkedRules(rule)
last.next = self.last
else:
self.rulechain = LinkedRules(rule, self.rulechain)
def remove(self, rulechain):
self.rulechain, last = self.rulechain.copy(rulechain)
last.next = rulechain.next
class Engine(object):
def __init__(self):
self.heap = Heap()
self.signature2function = {}
self.parser = None
self.operations = None
#XXX circular imports hack
from pypy.lang.prolog.builtin import builtins_list
globals()['unrolling_builtins'] = unrolling_iterable(builtins_list)
def add_rule(self, rule, end=True):
from pypy.lang.prolog import builtin
if DEBUG:
debug_print("add_rule", rule)
if isinstance(rule, Term):
if rule.name == ":-":
rule = Rule(rule.args[0], rule.args[1])
else:
rule = Rule(rule, None)
signature = rule.signature
elif isinstance(rule, Atom):
rule = Rule(rule, None)
signature = rule.signature
else:
error.throw_type_error("callable", rule)
assert 0, "unreachable" # make annotator happy
if signature in builtin.builtins:
error.throw_permission_error(
"modify", "static_procedure", rule.head.get_prolog_signature())
function = self.signature2function.get(signature, None)
if function is not None:
self.signature2function[signature].add_rule(rule, end)
else:
self.signature2function[signature] = Function(rule)
def run(self, query, continuation=DONOTHING):
if not isinstance(query, Callable):
error.throw_type_error("callable", query)
try:
return self.call(query, continuation, choice_point=True)
except CutException, e:
return self.continue_after_cut(e.continuation)
def _build_and_run(self, tree):
from pypy.lang.prolog.interpreter.parsing import TermBuilder
builder = TermBuilder()
term = builder.build_query(tree)
if isinstance(term, Term) and term.name == ":-" and len(term.args) == 1:
self.run(term.args[0])
else:
self.add_rule(term)
return self.parser
def runstring(self, s):
from pypy.lang.prolog.interpreter.parsing import parse_file
trees = parse_file(s, self.parser, Engine._build_and_run, self)
def call(self, query, continuation=DONOTHING, choice_point=True):
assert isinstance(query, Callable)
if not choice_point:
return (CALL, query, continuation, None)
return self.main_loop(CALL, query, continuation)
def _call(self, query, continuation):
signature = query.signature
from pypy.lang.prolog.builtin import builtins
builtins = hint(builtins, deepfreeze=True)
signature = hint(signature, promote=True)
for bsig, builtin in unrolling_builtins:
if signature == bsig:
return builtin.call(self, query, continuation)
return self.user_call(query, continuation, choice_point=False)
def _opaque_call(self, query, continuation):
from pypy.lang.prolog.builtin import builtins
signature = query.signature
builtin = builtins.get(signature, None)
if builtin is not None:
return builtin.call(self, query, continuation)
# do a real call
return self.user_call(query, continuation, choice_point=False)
def main_loop(self, where, query, continuation, rule=None):
next = (DONE, None, None, None)
hint(where, concrete=True)
hint(rule, concrete=True)
while 1:
if where == DONE:
return next
next = self.dispatch_bytecode(where, query, continuation, rule)
where, query, continuation, rule = next
where = hint(where, promote=True)
def dispatch_bytecode(self, where, query, continuation, rule):
if where == CALL:
next = self._call(query, continuation)
elif where == TRY_RULE:
rule = hint(rule, promote=True)
next = self._try_rule(rule, query, continuation)
elif where == USER_CALL:
next = self._user_call(query, continuation)
elif where == CONTINUATION:
hint(continuation.__class__, promote=True)
next = continuation._call(self)
else:
raise Exception("unknown bytecode")
return next
@purefunction
def _jit_lookup(self, signature):
signature2function = self.signature2function
function = signature2function.get(signature, None)
if function is None:
signature2function[signature] = function = Function()
return function
def user_call(self, query, continuation, choice_point=True):
if not choice_point:
return (USER_CALL, query, continuation, None)
return self.main_loop(USER_CALL, query, continuation)
def _user_call(self, query, continuation):
signature = hint(query.signature, promote=True)
function = self._jit_lookup(signature)
startrulechain = function.rulechain
startrulechain = hint(startrulechain, promote=True)
if startrulechain is None:
error.throw_existence_error(
"procedure", query.get_prolog_signature())
unify_hash = query.unify_hash_of_children(self.heap)
rulechain = startrulechain.find_applicable_rule(unify_hash)
if rulechain is None:
# none of the rules apply
raise UnificationFailed()
rule = rulechain.rule
rulechain = rulechain.next
oldstate = self.heap.branch()
while 1:
if rulechain is not None:
rulechain = rulechain.find_applicable_rule(unify_hash)
choice_point = rulechain is not None
else:
choice_point = False
hint(rule, concrete=True)
if rule.contains_cut:
continuation = LimitedScopeContinuation(continuation)
try:
result = self.try_rule(rule, query, continuation)
self.heap.discard(oldstate)
return result
except UnificationFailed:
self.heap.revert(oldstate)
except CutException, e:
if continuation.scope_active:
return self.continue_after_cut(e.continuation,
continuation)
raise
else:
inline = rule.body is None # inline facts
try:
# for the last rule (rulechain is None), this will always
# return, because choice_point is False
result = self.try_rule(rule, query, continuation,
choice_point=choice_point,
inline=inline)
self.heap.discard(oldstate)
return result
except UnificationFailed:
assert choice_point
self.heap.revert(oldstate)
rule = rulechain.rule
rulechain = rulechain.next
def try_rule(self, rule, query, continuation=DONOTHING, choice_point=True,
inline=False):
if not choice_point:
return (TRY_RULE, query, continuation, rule)
if not we_are_jitted():
return self.portal_try_rule(rule, query, continuation, choice_point)
if inline:
return self.main_loop(TRY_RULE, query, continuation, rule)
#if _is_early_constant(rule):
# rule = hint(rule, promote=True)
# return self.portal_try_rule(rule, query, continuation, choice_point)
return self._opaque_try_rule(rule, query, continuation, choice_point)
def _opaque_try_rule(self, rule, query, continuation, choice_point):
return self.portal_try_rule(rule, query, continuation, choice_point)
def portal_try_rule(self, rule, query, continuation, choice_point):
hint(None, global_merge_point=True)
hint(choice_point, concrete=True)
if not choice_point:
return self._try_rule(rule, query, continuation)
where = TRY_RULE
next = (DONE, None, None, None)
hint(where, concrete=True)
hint(rule, concrete=True)
signature = hint(query.signature, promote=True)
while 1:
hint(None, global_merge_point=True)
if where == DONE:
return next
if rule is not None:
assert rule.signature == signature
next = self.dispatch_bytecode(where, query, continuation, rule)
where, query, continuation, rule = next
rule = hint(rule, promote=True)
if query is not None:
signature = hint(query.signature, promote=True)
where = hint(where, promote=True)
def _try_rule(self, rule, query, continuation):
rule = hint(rule, deepfreeze=True)
hint(self, concrete=True)
# standardizing apart
nextcall = rule.clone_and_unify_head(self.heap, query)
if nextcall is not None:
return self.call(nextcall, continuation, choice_point=False)
else:
return continuation.call(self, choice_point=False)
def continue_after_cut(self, continuation, lsc=None):
while 1:
try:
return continuation.call(self, choice_point=True)
except CutException, e:
if lsc is not None and not lsc.scope_active:
raise
continuation = e.continuation
def parse(self, s):
from pypy.lang.prolog.interpreter.parsing import parse_file, TermBuilder, lexer
builder = TermBuilder()
trees = parse_file(s, self.parser)
terms = builder.build_many(trees)
return terms, builder.varname_to_var
def getoperations(self):
from pypy.lang.prolog.interpreter.parsing import default_operations
if self.operations is None:
return default_operations
return self.operations
| Python |
#!/usr/bin/env python
try:
import autopath
except ImportError:
pass
import py
import sys
#sys.path.append(str(py.magic.autopath().dirpath().dirpath()))
from pypy.rlib.parsing.parsing import ParseError
from pypy.rlib.parsing.deterministic import LexerError
from pypy.lang.prolog.interpreter.parsing import parse_file, get_query_and_vars
from pypy.lang.prolog.interpreter.parsing import get_engine
from pypy.lang.prolog.interpreter.engine import Engine
from pypy.lang.prolog.interpreter.engine import Continuation
from pypy.lang.prolog.interpreter import error
import pypy.lang.prolog.interpreter.term
pypy.lang.prolog.interpreter.term.DEBUG = False
import code
helptext = """
';': redo
'p': print
'h': help
"""
class StopItNow(Exception):
pass
class ContinueContinuation(Continuation):
def __init__(self, var_to_pos, write):
self.var_to_pos = var_to_pos
self.write = write
def _call(self, engine):
self.write("yes\n")
var_representation(self.var_to_pos, engine, self.write)
while 1:
res = getch()
self.write(res+"\n")
if res in "\r\x04":
self.write("\n")
raise StopItNow()
if res in ";nr":
raise error.UnificationFailed
elif res in "h?":
self.write(helptext)
elif res in "p":
var_representation(self.var_to_pos, engine, self.write)
else:
self.write('unknown action. press "h" for help\n')
def var_representation(var_to_pos, engine, write):
from pypy.lang.prolog.builtin.formatting import TermFormatter
f = TermFormatter(engine, quoted=True, max_depth=10)
vars = var_to_pos.items()
vars.sort()
heap = engine.heap
for var, real_var in vars:
if var.startswith("_"):
continue
val = real_var.getvalue(heap)
write("%s = %s\n" % (var, f.format(val)))
class PrologConsole(code.InteractiveConsole):
def __init__(self, engine):
code.InteractiveConsole.__init__(self, {})
del self.__dict__['compile']
self.engine = engine
def compile(self, source, filename="<input>", symbol="single"):
try:
if not source.strip():
return None, None
return get_query_and_vars(source)
except ParseError, exc:
self.write(exc.nice_error_message("<stdin>", source) + "\n")
raise SyntaxError
except LexerError, exc:
self.write(exc.nice_error_message("<stdin>") + "\n")
raise SyntaxError
def runcode(self, code):
try:
query, var_to_pos = code
if query is None:
return
self.engine.run(query, ContinueContinuation(var_to_pos, self.write))
except error.UnificationFailed:
self.write("no\n")
except error.CatchableError, e:
self.write("ERROR: ")
if e.term.args[0].name == "instantiation_error":
print e.term
self.write("arguments not sufficiently instantiated\n")
elif e.term.args[0].name == "existence_error":
print e.term
self.write("Undefined %s: %s\n" % (e.term.args[0].args[0],
e.term.args[0].args[1]))
else:
self.write("of unknown type: %s\n" % (e.term, ))
except error.UncatchableError, e:
self.write("INTERNAL ERROR: %s\n" % (e.message, ))
except StopItNow:
self.write("yes\n")
def showtracebach(self):
self.write("traceback. boooring. nothing to see here")
class _Getch(object):
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
import msvcrt
self.impl = self.get_windows
except ImportError:
try:
import tty, sys, termios
self.impl = self.get_unix
except ImportError:
import Carbon, Carbon.Evt
self.impl = self.get_carbon
def __call__(self):
return self.impl()
def get_unix(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def get_windows(self):
import msvcrt
return msvcrt.getch()
def get_carbon(self):
"""
A function which returns the current ASCII key that is down;
if no ASCII key is down, the null string is returned. The
page http://www.mactech.com/macintosh-c/chap02-1.html was
very helpful in figuring out how to do this.
"""
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
return ''
else:
# The message (msg) contains the ASCII char which is
# extracted with the 0x000000FF charCodeMask; this
# number is converted to an ASCII character with chr() and
# returned
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
return chr(msg & 0x000000FF)
getch = _Getch()
def main():
import readline
oldps1 = getattr(sys, "ps1", ">>> ")
oldps2 = getattr(sys, "ps2", "... ")
try:
sys.ps1 = ">?- "
sys.ps2 = "... "
if not len(sys.argv) == 2:
e = Engine()
else:
try:
source = py.path.local(sys.argv[1]).read()
e = get_engine(source)
except ParseError, exc:
print exc.nice_error_message("<stdin>", source) + "\n"
sys.exit(1)
except LexerError, exc:
print exc.nice_error_message("<stdin>") + "\n"
sys.exit(1)
c = PrologConsole(e)
c.interact("PyPy Prolog Console")
finally:
sys.ps1 = oldps1
sys.ps2 = oldps2
if __name__ == '__main__':
main()
| Python |
from pypy.translator.interactive import Translation
from pypy.rpython.test.test_llinterp import interpret
from pypy.lang.prolog.interpreter import parsing
from pypy.lang.prolog.interpreter.term import Atom
from pypy.lang.prolog.interpreter.test.tool import *
from pypy.lang.prolog.interpreter.conftest import option
if not option.slow:
py.test.skip("slow tests")
def test_parser():
def f(x):
if x:
s = "a(X, Y, Z)."
else:
s = "f(a, X, _, _, X, f(X, 2.455))."
term = parsing.parse_file(s)
assert isinstance(term, parsing.Nonterminal)
return term.symbol
assert f(True) == "file"
assert f(True) == "file"
t = Translation(f)
t.annotate([bool])
t.rtype()
t.backendopt()
func = t.compile_c()
assert func(True) == "file"
assert func(False) == "file"
def test_engine():
e = get_engine("""
g(a, a).
g(a, b).
g(b, c).
f(X, Z) :- g(X, Y), g(Y, Z).
""")
t1 = parse_query_term("f(a, c).")
t2 = parse_query_term("f(X, c).")
def run():
e.run(t1)
e.run(t2)
v0 = e.heap.getvar(0)
if isinstance(v0, Atom):
return v0.name
return "no!"
assert run() == "a"
t = Translation(run)
t.annotate()
t.rtype()
func = t.compile_c()
assert func() == "a"
| Python |
import py
from pypy.lang.prolog.interpreter.error import UnificationFailed, FunctionNotFound
from pypy.lang.prolog.interpreter.parsing import parse_query_term, get_engine
from pypy.lang.prolog.interpreter.engine import Continuation, Heap, Engine
def assert_true(query, e=None):
if e is None:
e = Engine()
terms, vars = e.parse(query)
term, = terms
e.run(term)
return dict([(name, var.dereference(e.heap))
for name, var in vars.iteritems()])
def assert_false(query, e=None):
if e is None:
e = Engine()
term = e.parse(query)[0][0]
py.test.raises(UnificationFailed, e.run, term)
def prolog_raises(exc, query, e=None):
return assert_true("catch(((%s), fail), error(%s), true)." %
(query, exc), e)
class CollectAllContinuation(Continuation):
def __init__(self, vars):
self.heaps = []
self.vars = vars
def _call(self, engine):
self.heaps.append(dict([(name, var.dereference(engine.heap))
for name, var in self.vars.iteritems()]))
print "restarting computation"
raise UnificationFailed
def collect_all(engine, s):
terms, vars = engine.parse(s)
term, = terms
collector = CollectAllContinuation(vars)
py.test.raises(UnificationFailed, engine.run, term,
collector)
return collector.heaps
| Python |
from pypy.objspace.proxy import patch_space_in_place
from pypy.interpreter import gateway, baseobjspace
#-- THE BUILTINS ----------------------------------------------------------------------
# this collects all multimethods to be made part of the Space
all_mms = {}
W_Root = baseobjspace.W_Root
#-- MISC ----------------------------------------------------
from pypy.module.cclp.misc import app_interp_id
#-- THREADING/COROUTINING -----------------------------------
from pypy.module.cclp.scheduler import TopLevelScheduler
from pypy.module.cclp.global_state import sched
#-- COMP. SPACE --------------------------------------------
from pypy.module.cclp.cspace import W_ThreadGroupScheduler, W_CSpace
#-- VARIABLE ------------------------------------------------
from pypy.module.cclp.variable import app_newvar, wait, app_wait, app_wait_needed, \
app_is_aliased, app_is_free, app_is_bound, app_alias_of, alias_of, app_bind, \
app_unify, W_Var, W_CVar, W_Future, all_mms as variable_mms, app_entail
from pypy.module.cclp.constraint.variable import app_domain
from pypy.module.cclp.types import app_domain_of, app_name_of, AppCoroutine
all_mms.update(variable_mms)
#-- SPACE HELPERS -------------------------------------
nb_forcing_args = {}
def setup():
nb_forcing_args.update({
'setattr': 2, # instead of 3
'setitem': 2, # instead of 3
'get': 2, # instead of 3
# ---- irregular operations ----
'wrap': 0,
'str_w': 1,
'int_w': 1,
'float_w': 1,
'uint_w': 1,
'unichars_w': 1,
'bigint_w': 1,
'interpclass_w': 1,
'unwrap': 1,
'is_true': 1,
'is_w': 2,
'newtuple': 0,
'newlist': 0,
'newstring': 0,
'newunicode': 0,
'newdict': 0,
'newslice': 0,
'call_args': 1,
'marshal_w': 1,
'log': 1,
})
for opname, _, arity, _ in baseobjspace.ObjSpace.MethodTable:
nb_forcing_args.setdefault(opname, arity)
for opname in baseobjspace.ObjSpace.IrregularOpTable:
assert opname in nb_forcing_args, "missing %r" % opname
setup()
del setup
def eqproxy(space, parentfn):
"""shortcuts wait filtering"""
def eq(w_obj1, w_obj2):
assert isinstance(w_obj1, W_Root)
assert isinstance(w_obj2, W_Root)
#w("#> check identity")
if space.is_true(space.is_nb_(w_obj1, w_obj2)):
return space.newbool(True)
#w("#> check aliasing")
if space.is_true(space.is_free(w_obj1)):
if space.is_true(space.is_free(w_obj2)):
if space.is_true(alias_of(space, w_obj1, w_obj2)):
return space.newbool(True) # and just go on ...
#w("#> using parent eq")
return parentfn(wait(space, w_obj1), wait(space, w_obj2))
return eq
def isproxy(space, parentfn):
def is_(w_obj1, w_obj2):
assert isinstance(w_obj1, W_Root)
assert isinstance(w_obj2, W_Root)
if space.is_true(space.is_nb_(w_obj1, w_obj2)):
return space.newbool(True)
return parentfn(wait(space, w_obj1), wait(space, w_obj2))
return is_
def cmpproxy(space, parentfn):
def cmp(w_obj1, w_obj2):
assert isinstance(w_obj1, W_Root)
assert isinstance(w_obj2, W_Root)
if space.is_true(space.is_nb_(w_obj1, w_obj2)):
return space.newint(0)
if space.is_true(space.is_free(w_obj1)):
if space.is_true(space.is_free(w_obj2)):
if space.is_true(alias_of(space, w_obj1, w_obj2)):
return space.newint(0) # and just go on ...
return parentfn(wait(space, w_obj1), wait(space, w_obj2))
return cmp
def neproxy(space, parentfn):
def ne(w_obj1, w_obj2):
assert isinstance(w_obj1, W_Root)
assert isinstance(w_obj2, W_Root)
if space.is_true(space.is_nb_(w_obj1, w_obj2)):
return space.newbool(False)
if space.is_true(space.is_free(w_obj1)):
if space.is_true(space.is_free(w_obj2)):
if space.is_true(alias_of(space, w_obj1, w_obj2)):
return space.newbool(False) # and just go on ...
return parentfn(wait(space, w_obj1), wait(space, w_obj2))
return ne
def proxymaker(space, opname, parentfn):
if opname == "eq":
return eqproxy(space, parentfn)
if opname == "is_": # FIXME : is_, is_w ?
return isproxy(space, parentfn)
if opname == "ne":
return neproxy(space, parentfn)
if opname == "cmp":
return cmpproxy(space, parentfn)
nb_args = nb_forcing_args[opname]
if nb_args == 0:
proxy = None
elif nb_args == 1:
def proxy(w1, *extra):
w1 = wait(space, w1)
return parentfn(w1, *extra)
elif nb_args == 2:
def proxy(w1, w2, *extra):
w1 = wait(space, w1)
w2 = wait(space, w2)
return parentfn(w1, w2, *extra)
elif nb_args == 3:
def proxy(w1, w2, w3, *extra):
w1 = wait(space, w1)
w2 = wait(space, w2)
w3 = wait(space, w3)
return parentfn(w1, w2, w3, *extra)
else:
raise NotImplementedError("operation %r has arity %d" %
(opname, nb_args))
return proxy
from pypy.objspace.std import stdtypedef
from pypy.tool.sourcetools import func_with_new_name
def Space(*args, **kwds):
try:
# for now, always make up a wrapped StdObjSpace
from pypy.objspace import std
space = std.Space(*args, **kwds)
# multimethods hack
space.model.typeorder[W_Var] = [(W_Var, None),
(W_Root, None)] # None means no conversion
space.model.typeorder[W_Future] = [(W_Future, None), (W_Var, None), (W_Root, None)]
space.model.typeorder[W_CVar] = [(W_CVar, None), (W_Var, None), (W_Root, None)]
for name in all_mms.keys():
exprargs, expr, miniglobals, fallback = (
all_mms[name].install_not_sliced(space.model.typeorder, baked_perform_call=False))
func = stdtypedef.make_perform_trampoline('__mm_' + name,
exprargs, expr, miniglobals,
all_mms[name])
# e.g. add(space, w_x, w_y)
def make_boundmethod(func=func):
def boundmethod(*args):
return func(space, *args)
return func_with_new_name(boundmethod, 'boundmethod_'+name)
boundmethod = make_boundmethod()
setattr(space, name, boundmethod) # store into 'space' instance
# /multimethods hack
#-- BUILTINS
#-- variable -------
space.setitem(space.builtin.w_dict, space.wrap('newvar'),
space.wrap(app_newvar))
space.setitem(space.builtin.w_dict, space.wrap('domain'),
space.wrap(app_domain))
space.setitem(space.builtin.w_dict, space.wrap('domain_of'),
space.wrap(app_domain_of))
space.setitem(space.builtin.w_dict, space.wrap('name_of'),
space.wrap(app_name_of))
space.setitem(space.builtin.w_dict, space.wrap('is_free'),
space.wrap(app_is_free))
space.setitem(space.builtin.w_dict, space.wrap('is_bound'),
space.wrap(app_is_bound))
space.setitem(space.builtin.w_dict, space.wrap('alias_of'),
space.wrap(app_alias_of))
space.setitem(space.builtin.w_dict, space.wrap('is_aliased'),
space.wrap(app_is_aliased))
space.setitem(space.builtin.w_dict, space.wrap('bind'),
space.wrap(app_bind))
space.setitem(space.builtin.w_dict, space.wrap('entail'),
space.wrap(app_entail))
space.setitem(space.builtin.w_dict, space.wrap('unify'),
space.wrap(app_unify))
#-- variables & threading --
space.setitem(space.builtin.w_dict, space.wrap('wait'),
space.wrap(app_wait))
space.setitem(space.builtin.w_dict, space.wrap('wait_needed'),
space.wrap(app_wait_needed))
#-- misc -----
space.setitem(space.builtin.w_dict, space.wrap('interp_id'),
space.wrap(app_interp_id))
# make sure that _stackless is imported
w_modules = space.getbuiltinmodule('_stackless')
# cleanup func called from space.finish()
def exitfunc():
pass
app_exitfunc = gateway.interp2app(exitfunc, unwrap_spec=[])
space.setitem(space.sys.w_dict, space.wrap("exitfunc"), space.wrap(app_exitfunc))
# capture one non-blocking op
space.is_nb_ = space.is_
# do the magic
patch_space_in_place(space, 'logic', proxymaker)
# instantiate singleton scheduler
sched.main_thread = AppCoroutine.w_getcurrent(space)
tg = W_ThreadGroupScheduler(space)
sched.uler = TopLevelScheduler(space, tg)
tg._init_head(sched.main_thread)
except:
import traceback
traceback.print_exc()
raise
return space
| Python |
import operator
from pypy.interpreter.error import OperationError
from pypy.interpreter.baseobjspace import ObjSpace
from pypy.interpreter.function import Function, Method
from pypy.interpreter.argument import Arguments
from pypy.interpreter.typedef import default_identity_hash
from pypy.tool.sourcetools import compile2, func_with_new_name
def raiseattrerror(space, w_obj, name, w_descr=None):
w_type = space.type(w_obj)
typename = w_type.getname(space, '?')
if w_descr is None:
msg = "'%s' object has no attribute '%s'" % (typename, name)
else:
msg = "'%s' object attribute '%s' is read-only" % (typename, name)
raise OperationError(space.w_AttributeError, space.wrap(msg))
class Object:
def descr__getattribute__(space, w_obj, w_name):
name = space.str_w(w_name)
w_descr = space.lookup(w_obj, name)
if w_descr is not None:
if space.is_data_descr(w_descr):
return space.get(w_descr, w_obj)
w_value = w_obj.getdictvalue_attr_is_in_class(space, w_name)
else:
w_value = w_obj.getdictvalue(space, w_name)
if w_value is not None:
return w_value
if w_descr is not None:
return space.get(w_descr, w_obj)
raiseattrerror(space, w_obj, name)
def descr__setattr__(space, w_obj, w_name, w_value):
name = space.str_w(w_name)
w_descr = space.lookup(w_obj, name)
shadows_type = False
if w_descr is not None:
if space.is_data_descr(w_descr):
space.set(w_descr, w_obj, w_value)
return
shadows_type = True
if w_obj.setdictvalue(space, w_name, w_value, shadows_type):
return
raiseattrerror(space, w_obj, name, w_descr)
def descr__delattr__(space, w_obj, w_name):
name = space.str_w(w_name)
w_descr = space.lookup(w_obj, name)
if w_descr is not None:
if space.is_data_descr(w_descr):
space.delete(w_descr, w_obj)
return
if w_obj.deldictvalue(space, w_name):
return
raiseattrerror(space, w_obj, name, w_descr)
def descr__init__(space, w_obj, __args__):
pass
class DescrOperation:
_mixin_ = True
def is_data_descr(space, w_obj):
return space.lookup(w_obj, '__set__') is not None
def get_and_call_args(space, w_descr, w_obj, args):
descr = space.interpclass_w(w_descr)
# a special case for performance and to avoid infinite recursion
if type(descr) is Function:
return descr.call_args(args.prepend(w_obj))
else:
w_impl = space.get(w_descr, w_obj)
return space.call_args(w_impl, args)
def get_and_call_function(space, w_descr, w_obj, *args_w):
descr = space.interpclass_w(w_descr)
# a special case for performance and to avoid infinite recursion
if type(descr) is Function:
# the fastcall paths are purely for performance, but the resulting
# increase of speed is huge
return descr.funccall(w_obj, *args_w)
else:
args = Arguments(space, list(args_w))
w_impl = space.get(w_descr, w_obj)
return space.call_args(w_impl, args)
def call_args(space, w_obj, args):
# two special cases for performance
if isinstance(w_obj, Function):
return w_obj.call_args(args)
if isinstance(w_obj, Method):
return w_obj.call_args(args)
w_descr = space.lookup(w_obj, '__call__')
if w_descr is None:
raise OperationError(
space.w_TypeError,
space.mod(space.wrap('object %r is not callable'),
space.newtuple([w_obj])))
return space.get_and_call_args(w_descr, w_obj, args)
def get(space, w_descr, w_obj, w_type=None):
w_get = space.lookup(w_descr, '__get__')
if w_get is None:
return w_descr
if w_type is None:
w_type = space.type(w_obj)
return space.get_and_call_function(w_get, w_descr, w_obj, w_type)
def set(space, w_descr, w_obj, w_val):
w_set = space.lookup(w_descr, '__set__')
if w_set is None:
raise OperationError(space.w_TypeError,
space.wrap("object is not a descriptor with set"))
return space.get_and_call_function(w_set, w_descr, w_obj, w_val)
def delete(space, w_descr, w_obj):
w_delete = space.lookup(w_descr, '__delete__')
if w_delete is None:
raise OperationError(space.w_TypeError,
space.wrap("object is not a descriptor with delete"))
return space.get_and_call_function(w_delete, w_descr, w_obj)
def getattr(space, w_obj, w_name):
w_descr = space.lookup(w_obj, '__getattribute__')
try:
if w_descr is None: # obscure case
raise OperationError(space.w_AttributeError, space.w_None)
return space.get_and_call_function(w_descr, w_obj, w_name)
except OperationError, e:
if not e.match(space, space.w_AttributeError):
raise
w_descr = space.lookup(w_obj, '__getattr__')
if w_descr is None:
raise
return space.get_and_call_function(w_descr, w_obj, w_name)
def setattr(space, w_obj, w_name, w_val):
w_descr = space.lookup(w_obj, '__setattr__')
if w_descr is None:
raise OperationError(space.w_AttributeError,
space.wrap("object is readonly"))
return space.get_and_call_function(w_descr, w_obj, w_name, w_val)
def delattr(space, w_obj, w_name):
w_descr = space.lookup(w_obj, '__delattr__')
if w_descr is None:
raise OperationError(space.w_AttributeError,
space.wrap("object does not support attribute removal"))
return space.get_and_call_function(w_descr, w_obj, w_name)
def is_true(space, w_obj):
w_descr = space.lookup(w_obj, '__nonzero__')
if w_descr is None:
w_descr = space.lookup(w_obj, '__len__')
if w_descr is None:
return True
w_res = space.get_and_call_function(w_descr, w_obj)
# more shortcuts for common cases
if w_res is space.w_False:
return False
if w_res is space.w_True:
return True
w_restype = space.type(w_res)
if (space.is_w(w_restype, space.w_bool) or
space.is_w(w_restype, space.w_int)):
return space.int_w(w_res) != 0
else:
raise OperationError(space.w_TypeError,
space.wrap('__nonzero__ should return '
'bool or int'))
def nonzero(self, w_obj):
if self.is_true(w_obj):
return self.w_True
else:
return self.w_False
## def len(self, w_obj):
## XXX needs to check that the result is an int (or long?) >= 0
def iter(space, w_obj):
w_descr = space.lookup(w_obj, '__iter__')
if w_descr is None:
w_descr = space.lookup(w_obj, '__getitem__')
if w_descr is None:
raise OperationError(space.w_TypeError,
space.wrap("iteration over non-sequence"))
return space.newseqiter(w_obj)
return space.get_and_call_function(w_descr, w_obj)
def next(space, w_obj):
w_descr = space.lookup(w_obj, 'next')
if w_descr is None:
raise OperationError(space.w_TypeError,
space.wrap("iterator has no next() method"))
return space.get_and_call_function(w_descr, w_obj)
def getitem(space, w_obj, w_key):
w_descr = space.lookup(w_obj, '__getitem__')
if w_descr is None:
raise OperationError(space.w_TypeError,
space.wrap("cannot get items from object"))
return space.get_and_call_function(w_descr, w_obj, w_key)
def setitem(space, w_obj, w_key, w_val):
w_descr = space.lookup(w_obj, '__setitem__')
if w_descr is None:
raise OperationError(space.w_TypeError,
space.wrap("cannot set items on object"))
return space.get_and_call_function(w_descr, w_obj, w_key, w_val)
def delitem(space, w_obj, w_key):
w_descr = space.lookup(w_obj, '__delitem__')
if w_descr is None:
raise OperationError(space.w_TypeError,
space.wrap("cannot delete items from object"))
return space.get_and_call_function(w_descr, w_obj, w_key)
def pow(space, w_obj1, w_obj2, w_obj3):
w_typ1 = space.type(w_obj1)
w_typ2 = space.type(w_obj2)
w_left_src, w_left_impl = space.lookup_in_type_where(w_typ1, '__pow__')
if space.is_w(w_typ1, w_typ2):
w_right_impl = None
else:
w_right_src, w_right_impl = space.lookup_in_type_where(w_typ2, '__rpow__')
if (w_left_src is not w_right_src # XXX see binop_impl
and space.is_true(space.issubtype(w_typ2, w_typ1))):
w_obj1, w_obj2 = w_obj2, w_obj1
w_left_impl, w_right_impl = w_right_impl, w_left_impl
if w_left_impl is not None:
if space.is_w(w_obj3, space.w_None):
w_res = space.get_and_call_function(w_left_impl, w_obj1, w_obj2)
else:
w_res = space.get_and_call_function(w_left_impl, w_obj1, w_obj2, w_obj3)
if _check_notimplemented(space, w_res):
return w_res
if w_right_impl is not None:
if space.is_w(w_obj3, space.w_None):
w_res = space.get_and_call_function(w_right_impl, w_obj2, w_obj1)
else:
w_res = space.get_and_call_function(w_right_impl, w_obj2, w_obj1,
w_obj3)
if _check_notimplemented(space, w_res):
return w_res
raise OperationError(space.w_TypeError,
space.wrap("operands do not support **"))
def inplace_pow(space, w_lhs, w_rhs):
w_impl = space.lookup(w_lhs, '__ipow__')
if w_impl is not None:
w_res = space.get_and_call_function(w_impl, w_lhs, w_rhs)
if _check_notimplemented(space, w_res):
return w_res
return space.pow(w_lhs, w_rhs, space.w_None)
def contains(space, w_container, w_item):
w_descr = space.lookup(w_container, '__contains__')
if w_descr is not None:
return space.get_and_call_function(w_descr, w_container, w_item)
w_iter = space.iter(w_container)
while 1:
try:
w_next = space.next(w_iter)
except OperationError, e:
if not e.match(space, space.w_StopIteration):
raise
return space.w_False
if space.eq_w(w_next, w_item):
return space.w_True
def hash(space, w_obj):
w_hash = space.lookup(w_obj, '__hash__')
if w_hash is None:
if space.lookup(w_obj, '__eq__') is not None or \
space.lookup(w_obj, '__cmp__') is not None:
raise OperationError(space.w_TypeError,
space.wrap("unhashable type"))
return default_identity_hash(space, w_obj)
w_result = space.get_and_call_function(w_hash, w_obj)
if space.is_true(space.isinstance(w_result, space.w_int)):
return w_result
else:
raise OperationError(space.w_TypeError,
space.wrap("__hash__() should return an int"))
def userdel(space, w_obj):
w_del = space.lookup(w_obj, '__del__')
if w_del is not None:
space.get_and_call_function(w_del, w_obj)
def cmp(space, w_v, w_w):
if space.is_w(w_v, w_w):
return space.wrap(0)
# The real comparison
if space.is_w(space.type(w_v), space.type(w_w)):
# for object of the same type, prefer __cmp__ over rich comparison.
w_cmp = space.lookup(w_v, '__cmp__')
w_res = _invoke_binop(space, w_cmp, w_v, w_w)
if w_res is not None:
return w_res
# fall back to rich comparison.
if space.eq_w(w_v, w_w):
return space.wrap(0)
elif space.is_true(space.lt(w_v, w_w)):
return space.wrap(-1)
return space.wrap(1)
def coerce(space, w_obj1, w_obj2):
w_typ1 = space.type(w_obj1)
w_typ2 = space.type(w_obj2)
w_left_src, w_left_impl = space.lookup_in_type_where(w_typ1, '__coerce__')
if space.is_w(w_typ1, w_typ2):
w_right_impl = None
else:
w_right_src, w_right_impl = space.lookup_in_type_where(w_typ2, '__coerce__')
if (w_left_src is not w_right_src # XXX see binop_impl
and space.is_true(space.issubtype(w_typ2, w_typ1))):
w_obj1, w_obj2 = w_obj2, w_obj1
w_left_impl, w_right_impl = w_right_impl, w_left_impl
w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2)
if w_res is None or space.is_w(w_res, space.w_None):
w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1)
if w_res is None or space.is_w(w_res, space.w_None):
raise OperationError(space.w_TypeError,
space.wrap("coercion failed"))
if (not space.is_true(space.isinstance(w_res, space.w_tuple)) or
space.int_w(space.len(w_res)) != 2):
raise OperationError(space.w_TypeError,
space.wrap("coercion should return None or 2-tuple"))
w_res = space.newtuple([space.getitem(w_res, space.wrap(1)), space.getitem(w_res, space.wrap(0))])
elif (not space.is_true(space.isinstance(w_res, space.w_tuple)) or
space.int_w(space.len(w_res)) != 2):
raise OperationError(space.w_TypeError,
space.wrap("coercion should return None or 2-tuple"))
return w_res
# xxx ord
# helpers
def _check_notimplemented(space, w_obj):
return not space.is_w(w_obj, space.w_NotImplemented)
def _invoke_binop(space, w_impl, w_obj1, w_obj2):
if w_impl is not None:
w_res = space.get_and_call_function(w_impl, w_obj1, w_obj2)
if _check_notimplemented(space, w_res):
return w_res
return None
# helper for invoking __cmp__
def _conditional_neg(space, w_obj, flag):
if flag:
return space.neg(w_obj)
else:
return w_obj
def _cmp(space, w_obj1, w_obj2):
w_typ1 = space.type(w_obj1)
w_typ2 = space.type(w_obj2)
w_left_src, w_left_impl = space.lookup_in_type_where(w_typ1, '__cmp__')
do_neg1 = False
do_neg2 = True
if space.is_w(w_typ1, w_typ2):
w_right_impl = None
else:
w_right_src, w_right_impl = space.lookup_in_type_where(w_typ2, '__cmp__')
if (w_left_src is not w_right_src # XXX see binop_impl
and space.is_true(space.issubtype(w_typ2, w_typ1))):
w_obj1, w_obj2 = w_obj2, w_obj1
w_left_impl, w_right_impl = w_right_impl, w_left_impl
do_neg1, do_neg2 = do_neg2, do_neg1
w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2)
if w_res is not None:
return _conditional_neg(space, w_res, do_neg1)
w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1)
if w_res is not None:
return _conditional_neg(space, w_res, do_neg2)
# fall back to internal rules
if space.is_w(w_obj1, w_obj2):
return space.wrap(0)
if space.is_w(w_obj1, space.w_None):
return space.wrap(-1)
if space.is_w(w_obj2, space.w_None):
return space.wrap(1)
if space.is_w(w_typ1, w_typ2):
#print "WARNING, comparison by address!"
w_id1 = space.id(w_obj1)
w_id2 = space.id(w_obj2)
else:
#print "WARNING, comparison by address!"
w_id1 = space.id(w_typ1)
w_id2 = space.id(w_typ2)
if space.is_true(space.lt(w_id1, w_id2)):
return space.wrap(-1)
else:
return space.wrap(1)
# regular methods def helpers
def _make_binop_impl(symbol, specialnames):
left, right = specialnames
def binop_impl(space, w_obj1, w_obj2):
w_typ1 = space.type(w_obj1)
w_typ2 = space.type(w_obj2)
w_left_src, w_left_impl = space.lookup_in_type_where(w_typ1, left)
if space.is_w(w_typ1, w_typ2):
w_right_impl = None
else:
w_right_src, w_right_impl = space.lookup_in_type_where(w_typ2, right)
# the logic to decide if the reverse operation should be tried
# before the direct one is very obscure. For now, and for
# sanity reasons, we just compare the two places where the
# __xxx__ and __rxxx__ methods where found by identity.
# Note that space.is_w() is potentially not happy if one of them
# is None (e.g. with the thunk space)...
if (w_left_src is not w_right_src # XXX
and space.is_true(space.issubtype(w_typ2, w_typ1))):
w_obj1, w_obj2 = w_obj2, w_obj1
w_left_impl, w_right_impl = w_right_impl, w_left_impl
w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2)
if w_res is not None:
return w_res
w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1)
if w_res is not None:
return w_res
raise OperationError(space.w_TypeError,
space.wrap("unsupported operand type(s) for %s" % symbol))
return func_with_new_name(binop_impl, "binop_%s_impl"%left.strip('_'))
def _make_comparison_impl(symbol, specialnames):
left, right = specialnames
op = getattr(operator, left)
def comparison_impl(space, w_obj1, w_obj2):
#from pypy.objspace.std.tlistobject import W_TransparentList
#if isinstance(w_obj1, W_TransparentList):
# import pdb;pdb.set_trace()
w_typ1 = space.type(w_obj1)
w_typ2 = space.type(w_obj2)
w_left_src, w_left_impl = space.lookup_in_type_where(w_typ1, left)
w_first = w_obj1
w_second = w_obj2
if space.is_w(w_typ1, w_typ2):
w_right_impl = None
else:
w_right_src, w_right_impl = space.lookup_in_type_where(w_typ2, right)
if (w_left_src is not w_right_src # XXX see binop_impl
and space.is_true(space.issubtype(w_typ2, w_typ1))):
w_obj1, w_obj2 = w_obj2, w_obj1
w_left_impl, w_right_impl = w_right_impl, w_left_impl
w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2)
if w_res is not None:
return w_res
w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1)
if w_res is not None:
return w_res
# fallback: lt(a, b) <= lt(cmp(a, b), 0) ...
w_res = _cmp(space, w_first, w_second)
res = space.int_w(w_res)
return space.wrap(op(res, 0))
return func_with_new_name(comparison_impl, 'comparison_%s_impl'%left.strip('_'))
def _make_inplace_impl(symbol, specialnames):
specialname, = specialnames
assert specialname.startswith('__i') and specialname.endswith('__')
noninplacespacemethod = specialname[3:-2]
if noninplacespacemethod in ['or', 'and']:
noninplacespacemethod += '_' # not too clean
def inplace_impl(space, w_lhs, w_rhs):
w_impl = space.lookup(w_lhs, specialname)
if w_impl is not None:
w_res = space.get_and_call_function(w_impl, w_lhs, w_rhs)
if _check_notimplemented(space, w_res):
return w_res
# XXX fix the error message we get here
return getattr(space, noninplacespacemethod)(w_lhs, w_rhs)
return func_with_new_name(inplace_impl, 'inplace_%s_impl'%specialname.strip('_'))
def _make_unaryop_impl(symbol, specialnames):
specialname, = specialnames
def unaryop_impl(space, w_obj):
w_impl = space.lookup(w_obj, specialname)
if w_impl is None:
raise OperationError(space.w_TypeError,
space.wrap("operand does not support unary %s" % symbol))
return space.get_and_call_function(w_impl, w_obj)
return func_with_new_name(unaryop_impl, 'unaryop_%s_impl'%specialname.strip('_'))
# the following seven operations are really better to generate with
# string-templating (and maybe we should consider this for
# more of the above manually-coded operations as well)
for targetname, specialname, checkerspec in [
('int', '__int__', ("space.w_int", "space.w_long")),
('index', '__index__', ("space.w_int", "space.w_long")),
('long', '__long__', ("space.w_int", "space.w_long")),
('float', '__float__', ("space.w_float",))]:
l = ["space.is_true(space.isinstance(w_result, %s))" % x
for x in checkerspec]
checker = " or ".join(l)
source = """if 1:
def %(targetname)s(space, w_obj):
w_impl = space.lookup(w_obj, %(specialname)r)
if w_impl is None:
raise OperationError(space.w_TypeError,
space.wrap("operand does not support unary %(targetname)s"))
w_result = space.get_and_call_function(w_impl, w_obj)
if %(checker)s:
return w_result
typename = space.str_w(space.getattr(space.type(w_result),
space.wrap('__name__')))
msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,)
raise OperationError(space.w_TypeError, space.wrap(msg))
assert not hasattr(DescrOperation, %(targetname)r)
DescrOperation.%(targetname)s = %(targetname)s
del %(targetname)s
\n""" % locals()
exec compile2(source)
for targetname, specialname in [
('str', '__str__'),
('repr', '__repr__'),
('oct', '__oct__'),
('hex', '__hex__')]:
source = """if 1:
def %(targetname)s(space, w_obj):
w_impl = space.lookup(w_obj, %(specialname)r)
if w_impl is None:
raise OperationError(space.w_TypeError,
space.wrap("operand does not support unary %(targetname)s"))
w_result = space.get_and_call_function(w_impl, w_obj)
if space.is_true(space.isinstance(w_result, space.w_str)):
return w_result
try:
result = space.str_w(w_result)
except OperationError, e:
if not e.match(space, space.w_TypeError):
raise
typename = space.str_w(space.getattr(space.type(w_result),
space.wrap('__name__')))
msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,)
raise OperationError(space.w_TypeError, space.wrap(msg))
else:
# re-wrap the result as a real string
return space.wrap(result)
assert not hasattr(DescrOperation, %(targetname)r)
DescrOperation.%(targetname)s = %(targetname)s
del %(targetname)s
\n""" % locals()
exec compile2(source)
# add default operation implementations for all still missing ops
for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable:
if not hasattr(DescrOperation, _name):
_impl_maker = None
if _arity == 2 and _name in ['lt', 'le', 'gt', 'ge', 'ne', 'eq']:
#print "comparison", _specialnames
_impl_maker = _make_comparison_impl
elif _arity == 2 and _name.startswith('inplace_'):
#print "inplace", _specialnames
_impl_maker = _make_inplace_impl
elif _arity == 2 and len(_specialnames) == 2:
#print "binop", _specialnames
_impl_maker = _make_binop_impl
elif _arity == 1 and len(_specialnames) == 1:
#print "unaryop", _specialnames
_impl_maker = _make_unaryop_impl
if _impl_maker:
setattr(DescrOperation,_name,_impl_maker(_symbol,_specialnames))
elif _name not in ['is_', 'id','type','issubtype',
# not really to be defined in DescrOperation
'ord']:
raise Exception, "missing def for operation %s" % _name
| Python |
"""
Trace object space traces operations and bytecode execution
in frames.
"""
from pypy.tool import pydis
from pypy.rlib.rarithmetic import intmask
# __________________________________________________________________________
#
# Tracing Events
# __________________________________________________________________________
#
class ExecBytecode(object):
""" bytecode trace. """
def __init__(self, frame):
self.frame = frame
self.code = frame.pycode
self.index = intmask(frame.last_instr)
class EnterFrame(object):
def __init__(self, frame):
self.frame = frame
class LeaveFrame(object):
def __init__(self, frame):
self.frame = frame
class CallInfo(object):
""" encapsulates a function call with its arguments. """
def __init__(self, name, func, args, kwargs):
self.name = name
self.func = func
self.args = args
self.kwargs = kwargs
class CallBegin(object):
def __init__(self, callinfo):
self.callinfo = callinfo
class CallFinished(object):
def __init__(self, callinfo, res):
self.callinfo = callinfo
self.res = res
class CallException(object):
def __init__(self, callinfo, e):
self.callinfo = callinfo
self.ex = e
class TraceResult(object):
""" This is the state of tracing-in-progress. """
def __init__(self, tracespace, **printer_options):
self.events = []
self.reentrant = True
self.tracespace = tracespace
result_printer_clz = printer_options["result_printer_clz"]
self.printer = result_printer_clz(**printer_options)
self._cache = {}
def append(self, event):
if self.reentrant:
self.reentrant = False
self.events.append(event)
self.printer.print_event(self.tracespace, self, event)
self.reentrant = True
def getbytecodes(self):
for event in self.events:
if isinstance(event, ExecBytecode):
disres = self.getdisresult(event.frame)
yield disres.getbytecode(event.index)
def getoperations(self):
for event in self.events:
if isinstance(event, (CallBegin, CallFinished, CallException)):
yield event
def getevents(self):
for event in self.events:
yield event
def getdisresult(self, frame):
""" return (possibly cached) pydis result for the given frame. """
try:
return self._cache[id(frame.pycode)]
except KeyError:
res = self._cache[id(frame.pycode)] = pydis.pydis(frame.pycode)
assert res is not None
return res
# __________________________________________________________________________
#
# Tracer Proxy objects
# __________________________________________________________________________
#
class ExecutionContextTracer(object):
def __init__(self, result, ec):
self.ec = ec
self.result = result
def __getattr__(self, name):
""" generically pass through everything else ... """
return getattr(self.ec, name)
def enter(self, frame):
""" called just before (continuing to) evaluating a frame. """
self.result.append(EnterFrame(frame))
self.ec.enter(frame)
def leave(self, frame):
""" called just after evaluating of a frame is suspended/finished. """
self.result.append(LeaveFrame(frame))
self.ec.leave(frame)
def bytecode_trace(self, frame):
""" called just before execution of a bytecode. """
self.result.append(ExecBytecode(frame))
self.ec.bytecode_trace(frame)
class CallableTracer(object):
def __init__(self, result, name, func):
self.result = result
self.name = name
self.func = func
def __call__(self, *args, **kwargs):
callinfo = CallInfo(self.name, self.func, args, kwargs)
self.result.append(CallBegin(callinfo))
try:
res = self.func(*args, **kwargs)
except Exception, e:
self.result.append(CallException(callinfo, e))
raise
else:
self.result.append(CallFinished(callinfo, res))
return res
def __getattr__(self, name):
""" generically pass through everything we don't intercept. """
return getattr(self.func, name)
def __str__(self):
return "%s - CallableTracer(%s)" % (self.name, self.func)
__repr__ = __str__
# __________________________________________________________________________
#
# Tracer factory
# __________________________________________________________________________
#
def create_trace_space(space):
""" Will turn the supplied into a traceable space by extending its class."""
# Don't trace an already traceable space
if hasattr(space, "__pypytrace__"):
return space
class Trace(space.__class__):
def __getattribute__(self, name):
obj = super(Trace, self).__getattribute__(name)
if name in ["_result", "_in_cache",
"_tracing", "_config_options"]:
return obj
if not self._tracing or self._in_cache:
return obj
if name in self._config_options["operations"]:
assert callable(obj)
obj = CallableTracer(self._result, name, obj)
return obj
def __pypytrace__(self):
pass
def enter_cache_building_mode(self):
self._in_cache += 1
def leave_cache_building_mode(self, val):
self._in_cache -= 1
def settrace(self):
self._result = TraceResult(self, **self._config_options)
self._tracing = True
def unsettrace(self):
self._tracing = False
def getresult(self):
return self._result
def getexecutioncontext(self):
ec = super(Trace, self).getexecutioncontext()
if not self._in_cache:
assert not isinstance(ec, ExecutionContextTracer)
ec = ExecutionContextTracer(self._result, ec)
return ec
# XXX Rename
def reset_trace(self):
""" Returns the class to its original form. """
space.__class__ = space.__oldclass__
del space.__oldclass__
for k in ["_result", "_in_cache", "_config_options", "_operations"]:
if hasattr(self, k):
delattr(self, k)
trace_clz = type("Trace%s" % repr(space), (Trace,), {})
space.__oldclass__, space.__class__ = space.__class__, trace_clz
# Do config
from pypy.tool.traceconfig import config
space._tracing = False
space._result = None
space._in_cache = 0
space._config_options = config
space.settrace()
return space
# ______________________________________________________________________
# End of trace.py
| Python |
import os
from pypy.objspace.proxy import patch_space_in_place
from pypy.objspace.std.objspace import StdObjSpace, W_Object
from pypy.interpreter.error import OperationError
from pypy.interpreter import baseobjspace
DUMP_FILE_NAME = 'pypy-space-dump'
DUMP_FILE_MODE = 0600
class Dumper(object):
dump_fd = -1
def __init__(self, space):
self.space = space
self.dumpspace_reprs = {}
def open(self):
space = self.space
self.dumpspace_reprs.update({
space.w_None: 'None',
space.w_False: 'False',
space.w_True: 'True',
})
if self.dump_fd < 0:
self.dump_fd = os.open(DUMP_FILE_NAME,
os.O_WRONLY|os.O_CREAT|os.O_TRUNC,
DUMP_FILE_MODE)
def close(self):
if self.dump_fd >= 0:
os.close(self.dump_fd)
self.dump_fd = -1
self.dumpspace_reprs.clear()
def dump_get_repr(self, w_obj):
try:
return self.dumpspace_reprs[w_obj]
except KeyError:
saved_fd = self.dump_fd
try:
self.dump_fd = -1
space = self.space
if isinstance(w_obj, W_Object):
w_type = space.type(w_obj)
else:
w_type = None
if w_type is space.w_int:
n = space.int_w(w_obj)
s = str(n)
elif w_type is space.w_str:
s = space.str_w(w_obj)
digit2hex = '0123456789abcdef'
lst = ["'"]
for c in s:
if c == '\\':
lst.append('\\')
if c >= ' ':
lst.append(c)
else:
lst.append('\\')
if c == '\n':
lst.append('n')
elif c == '\t':
lst.append('t')
else:
lst.append('x')
lst.append(digit2hex[ord(c) >> 4])
lst.append(digit2hex[ord(c) & 0xf])
lst.append("'")
s = ''.join(lst)
elif w_type is space.w_float:
n = space.float_w(w_obj)
s = str(n)
else:
s = '%s at 0x%x' % (w_obj, id(w_obj))
self.dumpspace_reprs[w_obj] = s
finally:
self.dump_fd = saved_fd
return s
def dump_enter(self, opname, args_w):
if self.dump_fd >= 0:
text = '\t'.join([self.dump_get_repr(w_arg) for w_arg in args_w])
os.write(self.dump_fd, '%s CALL %s\n' % (opname, text))
def dump_returned_wrapped(self, opname, w_obj):
if self.dump_fd >= 0:
s = self.dump_get_repr(w_obj)
os.write(self.dump_fd, '%s RETURN %s\n' % (opname, s))
def dump_returned(self, opname):
if self.dump_fd >= 0:
os.write(self.dump_fd, '%s RETURN\n' % (opname,))
def dump_raised(self, opname, e):
if self.dump_fd >= 0:
if isinstance(e, OperationError):
s = e.errorstr(self.space)
else:
s = '%s' % (e,)
os.write(self.dump_fd, '%s RAISE %s\n' % (opname, s))
# for now, always make up a wrapped StdObjSpace
class DumpSpace(StdObjSpace):
def __init__(self, *args, **kwds):
self.dumper = Dumper(self)
StdObjSpace.__init__(self, *args, **kwds)
patch_space_in_place(self, 'dump', proxymaker)
def _freeze_(self):
# remove strange things from the caches of self.dumper
# before we annotate
self.dumper.close()
return StdObjSpace._freeze_(self)
def startup(self):
StdObjSpace.startup(self)
self.dumper.open()
def finish(self):
self.dumper.close()
StdObjSpace.finish(self)
def wrap(self, x):
w_res = StdObjSpace.wrap(self, x)
self.dumper.dump_returned_wrapped(' wrap', w_res)
return w_res
wrap._annspecialcase_ = "specialize:wrap"
Space = DumpSpace
# __________________________________________________________________________
nb_args = {}
op_returning_wrapped = {}
def setup():
nb_args.update({
# ---- irregular operations ----
'wrap': 0,
'str_w': 1,
'int_w': 1,
'float_w': 1,
'uint_w': 1,
'unichars_w': 1,
'bigint_w': 1,
'interpclass_w': 1,
'unwrap': 1,
'is_true': 1,
'is_w': 2,
'newtuple': 0,
'newlist': 0,
'newstring': 0,
'newunicode': 0,
'newdict': 0,
'newslice': 0,
'call_args': 1,
'marshal_w': 1,
'log': 1,
})
op_returning_wrapped.update({
'wrap': True,
'newtuple': True,
'newlist': True,
'newstring': True,
'newunicode': True,
'newdict': True,
'newslice': True,
'call_args': True,
})
for opname, _, arity, _ in baseobjspace.ObjSpace.MethodTable:
nb_args.setdefault(opname, arity)
op_returning_wrapped[opname] = True
for opname in baseobjspace.ObjSpace.IrregularOpTable:
assert opname in nb_args, "missing %r" % opname
setup()
del setup
# __________________________________________________________________________
def proxymaker(space, opname, parentfn):
if opname == 'wrap':
return None
returns_wrapped = opname in op_returning_wrapped
aligned_opname = '%15s' % opname
n = nb_args[opname]
def proxy(*args, **kwds):
dumper = space.dumper
args_w = list(args[:n])
dumper.dump_enter(aligned_opname, args_w)
try:
res = parentfn(*args, **kwds)
except Exception, e:
dumper.dump_raised(aligned_opname, e)
raise
else:
if returns_wrapped:
dumper.dump_returned_wrapped(aligned_opname, res)
else:
dumper.dump_returned(aligned_opname)
return res
proxy.func_name = 'proxy_%s' % (opname,)
return proxy
| Python |
from pypy.interpreter.baseobjspace import ObjSpace
# __________________________________________________________________________
def get_operations():
return [r[0] for r in ObjSpace.MethodTable] + ObjSpace.IrregularOpTable
def patch_space_in_place(space, proxyname, proxymaker, operations=None):
"""Patches the supplied space."""
if operations is None:
operations = get_operations()
for name in operations:
parentfn = getattr(space, name)
proxy = proxymaker(space, name, parentfn)
if proxy:
setattr(space, name, proxy)
prevrepr = repr(space)
space._this_space_repr_ = '%s(%s)' % (proxyname, prevrepr)
# __________________________________________________________________________
| Python |
from pypy.interpreter.baseobjspace import ObjSpace, Wrappable, W_Root
from pypy.rlib.nonconst import NonConstant
from pypy.rlib.rarithmetic import r_uint
from pypy.rlib.rbigint import rbigint
class W_Type(W_Root):
pass
class W_Object(W_Root):
pass
W_Object.typedef = W_Type()
def make_dummy(a=W_Object(), b=W_Object()):
def fn(*args):
if NonConstant(True):
return a
else:
return b
return fn
int_dummy = make_dummy(42, 43)
float_dummy = make_dummy(42.0, 42.1)
uint_dummy = make_dummy(r_uint(42), r_uint(43))
str_dummy = make_dummy('foo', 'bar')
bool_dummy = make_dummy(True, False)
unichars_dummy = make_dummy([u'a', u'b'], [u'c', u'd'])
bigint_dummy = make_dummy(rbigint([0]), rbigint([1]))
class FakeObjSpace(ObjSpace):
w_None = W_Object()
w_False = W_Object()
w_True = W_Object()
w_Ellipsis = W_Object()
w_NotImplemented = W_Object()
w_int = W_Object()
w_dict = W_Object()
w_float = W_Object()
w_long = W_Object()
w_tuple = W_Object()
w_str = W_Object()
w_basestring = W_Object()
w_unicode = W_Object()
w_type = W_Object()
w_instance = W_Object()
w_slice = W_Object()
w_hex = W_Object()
w_oct = W_Object()
def initialize(self):
self.config.objspace.geninterp = False
self.wrap_cache = {}
self.make_builtins()
def _freeze_(self):
return True
def wrap(self, x):
if isinstance(x, Wrappable):
w_result = x.__spacebind__(self)
return w_result
return W_Object()
wrap._annspecialcase_ = "specialize:argtype(1)"
def unwrap(self, w_obj):
assert isinstance(w_obj, W_Object)
return None
lookup = make_dummy()
allocate_instance = make_dummy()
getattr = make_dummy()
setattr = make_dummy()
getitem = make_dummy()
setitem = make_dummy()
delitem = make_dummy()
int_w = int_dummy
uint_w = uint_dummy
float_w = float_dummy
unichars_w = unichars_dummy
bigint_w = bigint_dummy
iter = make_dummy()
type = make_dummy()
str = make_dummy()
int = make_dummy()
float = make_dummy()
repr = make_dummy()
id = make_dummy()
len = make_dummy()
str_w = str_dummy
call_args = make_dummy()
new_interned_str = make_dummy()
newstring = make_dummy()
newunicode = make_dummy()
newint = make_dummy()
newlong = make_dummy()
newfloat = make_dummy()
def newdict(self, track_builtin_shadowing=False):
return self.newfloat()
newlist = make_dummy()
emptylist = make_dummy()
newtuple = make_dummy()
newslice = make_dummy()
lt = make_dummy()
le = make_dummy()
eq = make_dummy()
ne = make_dummy()
gt = make_dummy()
ge = make_dummy()
lt_w = bool_dummy
le_w = bool_dummy
eq_w = bool_dummy
ne_w = bool_dummy
gt_w = bool_dummy
ge_w = bool_dummy
is_w = bool_dummy
is_ = make_dummy()
next = make_dummy()
is_true = bool_dummy
nonzero = make_dummy()
issubtype = make_dummy()
ord = make_dummy()
hash = make_dummy()
delattr = make_dummy() # should return None?
contains = make_dummy()
hex = make_dummy()
oct = make_dummy()
pow = make_dummy()
inplace_pow = make_dummy()
cmp = make_dummy()
# XXsX missing operations
def coerce(self, *args): raise NotImplementedError("space.coerce()")
def get(self, *args): raise NotImplementedError("space.get()")
def set(self, *args): raise NotImplementedError("space.set()")
def delete(self, *args): raise NotImplementedError("space.delete()")
def userdel(self, *args): raise NotImplementedError("space.userdel()")
def marshal_w(self, *args):raise NotImplementedError("space.marshal_w()")
gettypefor = make_dummy()
gettypeobject = make_dummy()
unpackiterable = make_dummy([W_Object()], [W_Object()])
## Register all exceptions
import exceptions
for name in ObjSpace.ExceptionTable:
exc = getattr(exceptions, name)
setattr(FakeObjSpace, 'w_' + name, W_Object())
| Python |
from copy import copy
from pypy.tool.error import debug
from pypy.interpreter.argument import AbstractArguments
from pypy.interpreter.gateway import interp2app
from pypy.rlib.nonconst import NonConstant
def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def find_gateways(modname, basepath, module):
res = []
for name in module.interpleveldefs.values():
submod_name, obj_name = name.split('.')
submod_name = '%s.%s.%s' % (basepath, modname, submod_name)
submod = my_import(submod_name)
obj = getattr(submod, obj_name)
res += find_gw_in_obj(obj)
return res
def find_gw_in_obj(obj):
if hasattr(obj, 'typedef'):
typedef = obj.typedef
return typedef.rawdict.values() # XXX: check they are interp2app
elif hasattr(obj, 'func_code'):
return [interp2app(obj)]
else:
assert False
## Since the fake objspace is more a hack than a real object space, it
## happens that the annotator complains about operations that cannot
## succeed because it knows too much about the objects involved. For
## example, if it knows that a list is always empty, it will block
## each operations that tries to access that list. This is not what we
## want, because we know that with real objectspaces that operations
## will succeed.
## As a workaround, we insert dummy rpython code (the function
## dummy_rpython) that manipulates the variables in order to give
## them a more sensible annotation. This is the preferred way to solve
## the problems so far.
## If the solution above doesn't work, the alternative is to
## substitute the interpreter code with something that doesn't hurt
## the annotator. It's a very ugly hack, better solutions are welcome
## :-)
# dummy rpython code to give some variables more sensible annotations
def dummy_rpython(dummy_function):
# to make the annotator flow-in without executing the code
if NonConstant(False):
dummy_function.defs_w = [None] # else the annotator would see an always empty list
def patch_pypy():
from pypy.interpreter.baseobjspace import W_Root
def descr_call_mismatch(self, space, opname, RequiredClass, args):
from pypy.interpreter.error import OperationError
msg = 'This message will never be displayed :-)'
raise OperationError(space.w_TypeError, space.wrap(msg))
W_Root.descr_call_mismatch = descr_call_mismatch
def checkmodule(modname, backend, interactive=False, basepath='pypy.module'):
"Compile a fake PyPy module."
from pypy.objspace.fake.objspace import FakeObjSpace, W_Object
from pypy.translator.driver import TranslationDriver
space = FakeObjSpace()
space.config.translating = True
ModuleClass = __import__(basepath + '.%s' % modname,
None, None, ['Module']).Module
module = ModuleClass(space, space.wrap(modname))
w_moduledict = module.getdict()
gateways = find_gateways(modname, basepath, module)
functions = [gw.__spacebind__(space) for gw in gateways]
arguments = AbstractArguments.frompacked(space, W_Object(), W_Object())
dummy_function = copy(functions[0])
def main(argv): # use the standalone mode not to allow SomeObject
dummy_rpython(dummy_function)
for func in functions:
func.call_args(arguments)
return 0
patch_pypy()
driver = TranslationDriver()
driver.setup(main, None)
try:
driver.proceed(['compile_' + backend])
except SystemExit:
raise
except:
if not interactive:
raise
debug(driver)
raise SystemExit(1)
| Python |
from objspace import FakeObjSpace
Space = FakeObjSpace
| Python |
"""
Just an experiment.
"""
import os
from pypy.objspace.std.objspace import StdObjSpace
from pypy.objspace.proxy import patch_space_in_place
from pypy.objspace.thunk import nb_forcing_args
from pypy.interpreter.error import OperationError
from pypy.interpreter import baseobjspace, gateway, executioncontext
from pypy.interpreter.function import Method
from pypy.interpreter.pyframe import PyFrame
from pypy.tool.sourcetools import func_with_new_name
from pypy.rlib.unroll import unrolling_iterable
class W_Tainted(baseobjspace.W_Root):
def __init__(self, w_obj):
self.w_obj = w_obj
## def getdict(self):
## return taint(self.w_obj.getdict())
## def getdictvalue_w(self, space, attr):
## return taint(self.w_obj.getdictvalue_w(space, attr))
## def getdictvalue(self, space, w_attr):
## return taint(self.w_obj.getdictvalue(space, w_attr))
## def setdictvalue(self, space, w_attr, w_value):
## return self.w_obj.setdictvalue(space, w_attr, w_value)
## ...
class W_TaintBomb(baseobjspace.W_Root):
filename = '?'
codename = '?'
codeline = 0
def __init__(self, space, operr):
self.space = space
self.operr = operr
self.record_debug_info()
def record_debug_info(self):
ec = self.space.getexecutioncontext()
try:
frame = ec.framestack.top()
except IndexError:
pass
else:
if isinstance(frame, PyFrame):
self.filename = frame.pycode.co_filename
self.codename = frame.pycode.co_name
self.codeline = frame.get_last_lineno()
if get_debug_level(self.space) > 0:
self.debug_dump()
def debug_dump(self):
os.write(2, 'Taint Bomb from file "%s", line %d, in %s\n %s\n' % (
self.filename, self.codeline, self.codename,
self.operr.errorstr(self.space)))
def explode(self):
#msg = self.operr.errorstr(space)
raise OperationError(self.space.w_TaintError, self.space.w_None)
def taint(w_obj):
"""Return a tainted version of the argument."""
if w_obj is None or isinstance(w_obj, W_Tainted):
return w_obj
else:
return W_Tainted(w_obj)
taint.unwrap_spec = [gateway.W_Root]
app_taint = gateway.interp2app(taint)
def is_tainted(space, w_obj):
"""Return whether the argument is tainted."""
res = isinstance(w_obj, W_Tainted) or isinstance(w_obj, W_TaintBomb)
return space.wrap(res)
app_is_tainted = gateway.interp2app(is_tainted)
def untaint(space, w_expectedtype, w_obj):
"""untaint(expectedtype, tainted_obj) -> obj
Untaint untainted_obj and return it. If the result is not of expectedtype,
raise a type error."""
if (isinstance(w_expectedtype, W_Tainted) or
isinstance(w_expectedtype, W_TaintBomb)):
raise OperationError(space.w_TypeError,
space.wrap("untaint() arg 1 must be an untainted type"))
if not space.is_true(space.isinstance(w_expectedtype, space.w_type)):
raise OperationError(space.w_TypeError,
space.wrap("untaint() arg 1 must be a type"))
if isinstance(w_obj, W_Tainted):
w_obj = w_obj.w_obj
elif isinstance(w_obj, W_TaintBomb):
w_obj.explode()
#if isinstance(w_expectedtype, W_Tainted):
# w_expectedtype = w_expectedtype.w_obj
w_realtype = space.type(w_obj)
if not space.is_w(w_realtype, w_expectedtype):
#msg = "expected an object of type '%s'" % (
# w_expectedtype.getname(space, '?'),)
# #w_realtype.getname(space, '?'))
raise OperationError(space.w_TaintError, space.w_None)
return w_obj
app_untaint = gateway.interp2app(untaint)
# ____________________________________________________________
def taint_atomic_function(space, w_func, args_w):
newargs_w = []
tainted = False
for w_arg in args_w:
if isinstance(w_arg, W_Tainted):
tainted = True
w_arg = w_arg.w_obj
elif isinstance(w_arg, W_TaintBomb):
return w_arg
newargs_w.append(w_arg)
w_newargs = space.newtuple(newargs_w)
try:
w_res = space.call(w_func, w_newargs)
except OperationError, operr:
if not tainted:
raise
return W_TaintBomb(space, operr)
if tainted:
w_res = taint(w_res)
return w_res
app_taint_atomic_function = gateway.interp2app(
taint_atomic_function,
unwrap_spec=[gateway.ObjSpace, gateway.W_Root, 'args_w'])
def taint_atomic(space, w_callable):
"""decorator to make a callable "taint-atomic": if the function is called
with tainted arguments, those are untainted. The result of the function is
tainted again. All exceptions that the callable raises are turned into
taint bombs."""
meth = Method(space, space.w_fn_taint_atomic_function,
w_callable, space.type(w_callable))
return space.wrap(meth)
app_taint_atomic = gateway.interp2app(taint_atomic)
# ____________________________________________________________
executioncontext.ExecutionContext.taint_debug = 0
def taint_debug(space, level):
"""Set the debug level. If the debug level is greater than 0, the creation
of taint bombs will print debug information. For debugging purposes
only!"""
space.getexecutioncontext().taint_debug = level
app_taint_debug = gateway.interp2app(taint_debug,
unwrap_spec=[gateway.ObjSpace, int])
def taint_look(space, w_obj):
"""Print some info about the taintedness of an object. For debugging
purposes only!"""
if isinstance(w_obj, W_Tainted):
info = space.type(w_obj.w_obj).getname(space, '?')
msg = space.str_w(w_obj.w_obj.getrepr(space, info))
msg = 'Taint Box %s\n' % msg
os.write(2, msg)
elif isinstance(w_obj, W_TaintBomb):
w_obj.debug_dump()
else:
os.write(2, 'not tainted\n')
app_taint_look = gateway.interp2app(taint_look)
def get_debug_level(space):
return space.getexecutioncontext().taint_debug
def debug_bomb(space, operr):
ec = space.getexecutioncontext()
filename = '?'
codename = '?'
codeline = 0
try:
frame = ec.framestack.top()
except IndexError:
pass
else:
if isinstance(frame, PyFrame):
filename = frame.pycode.co_filename
codename = frame.pycode.co_name
codeline = frame.get_last_lineno()
os.write(2, 'Taint Bomb in file "%s", line %d, in %s\n %s\n' % (
filename, codeline, codename, operr.errorstr(space)))
# ____________________________________________________________
class TaintSpace(StdObjSpace):
def __init__(self, *args, **kwds):
StdObjSpace.__init__(self, *args, **kwds)
w_dict = self.newdict()
self.setitem(w_dict, self.wrap("__doc__"), self.wrap("""\
Exception that is raised when an operation revealing information on a tainted
object is performed."""))
self.w_TaintError = self.call_function(
self.w_type,
self.wrap("TaintError"),
self.newtuple([self.w_Exception]),
w_dict
)
w___pypy__ = self.getbuiltinmodule("__pypy__")
self.setattr(w___pypy__, self.wrap('taint'),
self.wrap(app_taint))
self.setattr(w___pypy__, self.wrap('is_tainted'),
self.wrap(app_is_tainted))
self.setattr(w___pypy__, self.wrap('untaint'),
self.wrap(app_untaint))
self.w_fn_taint_atomic_function = self.wrap(app_taint_atomic_function)
self.setattr(w___pypy__, self.wrap('taint_atomic'),
self.wrap(app_taint_atomic))
self.setattr(w___pypy__, self.wrap('TaintError'),
self.w_TaintError)
self.setattr(w___pypy__, self.wrap('_taint_debug'),
self.wrap(app_taint_debug))
self.setattr(w___pypy__, self.wrap('_taint_look'),
self.wrap(app_taint_look))
patch_space_in_place(self, 'taint', proxymaker)
# XXX may leak info, perfomance hit, what about taint bombs?
from pypy.objspace.std.typeobject import W_TypeObject
def taint_lookup(w_obj, name):
if isinstance(w_obj, W_Tainted):
w_obj = w_obj.w_obj
w_type = self.type(w_obj)
assert isinstance(w_type, W_TypeObject)
return w_type.lookup(name)
def taint_lookup_in_type_where(w_obj, name):
if isinstance(w_obj, W_Tainted):
w_type = w_obj.w_obj
else:
w_type = w_obj
assert isinstance(w_type, W_TypeObject)
return w_type.lookup_where(name)
self.lookup = taint_lookup
self.lookup_in_type_where = taint_lookup_in_type_where
Space = TaintSpace
def tainted_error(space, name):
#msg = "operation '%s' forbidden on tainted object" % (name,)
raise OperationError(space.w_TaintError, space.w_None)# space.wrap(msg))
RegularMethods = dict.fromkeys(
[name for name, _, _, _ in baseobjspace.ObjSpace.MethodTable])
TaintResultIrregularMethods = dict.fromkeys(
['wrap', 'call_args'] +
[name for name in baseobjspace.ObjSpace.IrregularOpTable
if name.startswith('new')])
def proxymaker(space, name, parentfn):
arity = nb_forcing_args[name]
indices = unrolling_iterable(range(arity))
if name in RegularMethods:
def proxy(*args_w):
newargs_w = ()
tainted = False
for i in indices:
w_arg = args_w[i]
if isinstance(w_arg, W_Tainted):
tainted = True
w_arg = w_arg.w_obj
elif isinstance(w_arg, W_TaintBomb):
return w_arg
newargs_w += (w_arg,)
newargs_w += args_w[arity:]
try:
w_res = parentfn(*newargs_w)
except OperationError, operr:
if not tainted:
raise
return W_TaintBomb(space, operr)
if tainted:
w_res = taint(w_res)
return w_res
elif arity == 0:
return None
else:
def proxy(*args_w):
for i in indices:
w_arg = args_w[i]
if isinstance(w_arg, W_Tainted):
tainted_error(space, name)
elif isinstance(w_arg, W_TaintBomb):
w_arg.explode()
return parentfn(*args_w)
proxy = func_with_new_name(proxy, '%s_proxy' % name)
return proxy
| Python |
from pypy.interpreter.executioncontext import ExecutionContext
from pypy.interpreter.error import OperationError
from pypy.interpreter import pyframe
from pypy.objspace.flow.model import *
from pypy.objspace.flow.framestate import FrameState
class OperationThatShouldNotBePropagatedError(OperationError):
pass
class ImplicitOperationError(OperationError):
pass
class StopFlowing(Exception):
pass
class MergeBlock(Exception):
def __init__(self, block, currentstate):
self.block = block
self.currentstate = currentstate
class PyFrame(pyframe.PyFrame):
def LOOKUP_METHOD(f, nameindex, *ignored):
space = f.space
w_obj = f.popvalue()
w_name = f.getname_w(nameindex)
w_value = space.getattr(w_obj, w_name)
f.pushvalue(w_value)
#f.pushvalue(None)
def CALL_METHOD(f, nargs, *ignored):
# 'nargs' is the argument count excluding the implicit 'self'
w_callable = f.peekvalue(nargs)
try:
w_result = f.space.call_valuestack(w_callable, nargs, f)
finally:
f.dropvalues(nargs + 1)
f.pushvalue(w_result)
class SpamBlock(Block):
# make slots optional, for debugging
if hasattr(Block, '__slots__'):
__slots__ = "dead framestate".split()
def __init__(self, framestate):
Block.__init__(self, framestate.getvariables())
self.framestate = framestate
self.dead = False
def patchframe(self, frame):
if self.dead:
raise StopFlowing
self.framestate.restoreframe(frame)
return BlockRecorder(self)
class EggBlock(Block):
# make slots optional, for debugging
if hasattr(Block, '__slots__'):
__slots__ = "prevblock booloutcome last_exception".split()
def __init__(self, inputargs, prevblock, booloutcome):
Block.__init__(self, inputargs)
self.prevblock = prevblock
self.booloutcome = booloutcome
def patchframe(self, frame):
parentblocks = []
block = self
while isinstance(block, EggBlock):
block = block.prevblock
parentblocks.append(block)
# parentblocks = [Egg, Egg, ..., Egg, Spam] not including self
block.patchframe(frame)
recorder = BlockRecorder(self)
prevblock = self
for block in parentblocks:
recorder = Replayer(block, prevblock.booloutcome, recorder)
prevblock = block
return recorder
def extravars(self, last_exception=None, last_exc_value=None):
self.last_exception = last_exception
# ____________________________________________________________
class Recorder:
def append(self, operation):
raise NotImplementedError
def bytecode_trace(self, ec, frame):
pass
def guessbool(self, ec, w_condition, **kwds):
raise AssertionError, "cannot guessbool(%s)" % (w_condition,)
class BlockRecorder(Recorder):
# Records all generated operations into a block.
def __init__(self, block):
self.crnt_block = block
# saved state at the join point most recently seen
self.last_join_point = None
self.enterspamblock = isinstance(block, SpamBlock)
def append(self, operation):
if self.last_join_point is not None:
# only add operations corresponding to the first bytecode
raise MergeBlock(self.crnt_block, self.last_join_point)
self.crnt_block.operations.append(operation)
def bytecode_trace(self, ec, frame):
assert frame is ec.crnt_frame, "seeing an unexpected frame!"
ec.crnt_offset = frame.last_instr # save offset for opcode
if self.enterspamblock:
# If we have a SpamBlock, the first call to bytecode_trace()
# occurs as soon as frame.resume() starts, before interpretation
# really begins.
varnames = frame.pycode.getvarnames()
for name, w_value in zip(varnames, frame.getfastscope()):
if isinstance(w_value, Variable):
w_value.rename(name)
self.enterspamblock = False
else:
# At this point, we progress to the next bytecode. When this
# occurs, we no longer allow any more operations to be recorded in
# the same block. We will continue, to figure out where the next
# such operation *would* appear, and we make a join point just
# before.
self.last_join_point = FrameState(frame)
def guessbool(self, ec, w_condition, cases=[False,True],
replace_last_variable_except_in_first_case = None):
block = self.crnt_block
bvars = vars = vars2 = block.getvariables()
links = []
first = True
attach = {}
for case in cases:
if first:
first = False
elif replace_last_variable_except_in_first_case is not None:
assert block.operations[-1].result is bvars[-1]
vars = bvars[:-1]
vars2 = bvars[:-1]
for name, newvar in replace_last_variable_except_in_first_case(case):
attach[name] = newvar
vars.append(newvar)
vars2.append(Variable())
egg = EggBlock(vars2, block, case)
ec.pendingblocks.append(egg)
link = ec.make_link(vars, egg, case)
if attach:
link.extravars(**attach)
egg.extravars(**attach) # xxx
links.append(link)
block.exitswitch = w_condition
block.closeblock(*links)
# forked the graph. Note that False comes before True by default
# in the exits tuple so that (just in case we need it) we
# actually have block.exits[False] = elseLink and
# block.exits[True] = ifLink.
raise StopFlowing
class Replayer(Recorder):
def __init__(self, block, booloutcome, nextreplayer):
self.crnt_block = block
self.listtoreplay = block.operations
self.booloutcome = booloutcome
self.nextreplayer = nextreplayer
self.index = 0
def append(self, operation):
operation.result = self.listtoreplay[self.index].result
assert operation == self.listtoreplay[self.index], (
'\n'.join(["Not generating the same operation sequence:"] +
[str(s) for s in self.listtoreplay[:self.index]] +
[" ---> | while repeating we see here"] +
[" | %s" % operation] +
[str(s) for s in self.listtoreplay[self.index:]]))
self.index += 1
def guessbool(self, ec, w_condition, **kwds):
assert self.index == len(self.listtoreplay)
ec.recorder = self.nextreplayer
return self.booloutcome
class ConcreteNoOp(Recorder):
# In "concrete mode", no SpaceOperations between Variables are allowed.
# Concrete mode is used to precompute lazily-initialized caches,
# when we don't want this precomputation to show up on the flow graph.
def append(self, operation):
raise AssertionError, "concrete mode: cannot perform %s" % operation
# ____________________________________________________________
class FlowExecutionContext(ExecutionContext):
def __init__(self, space, code, globals, constargs={}, closure=None,
name=None):
ExecutionContext.__init__(self, space)
self.code = code
self.w_globals = w_globals = space.wrap(globals)
self.crnt_offset = -1
self.crnt_frame = None
if closure is None:
self.closure = None
else:
from pypy.interpreter.nestedscope import Cell
self.closure = [Cell(Constant(value)) for value in closure]
frame = self.create_frame()
formalargcount = code.getformalargcount()
arg_list = [Variable() for i in range(formalargcount)]
for position, value in constargs.items():
arg_list[position] = Constant(value)
frame.setfastscope(arg_list)
self.joinpoints = {}
#for joinpoint in code.getjoinpoints():
# self.joinpoints[joinpoint] = [] # list of blocks
initialblock = SpamBlock(FrameState(frame).copy())
self.pendingblocks = [initialblock]
self.graph = FunctionGraph(name or code.co_name, initialblock)
make_link = Link # overridable for transition tracking
def create_frame(self):
# create an empty frame suitable for the code object
# while ignoring any operation like the creation of the locals dict
self.recorder = []
frame = PyFrame(self.space, self.code,
self.w_globals, self.closure)
frame.last_instr = 0
return frame
def bytecode_trace(self, frame):
self.recorder.bytecode_trace(self, frame)
def guessbool(self, w_condition, **kwds):
return self.recorder.guessbool(self, w_condition, **kwds)
def guessexception(self, *classes):
def replace_exc_values(case):
if case is not Exception:
yield 'last_exception', Constant(case)
yield 'last_exc_value', Variable('last_exc_value')
else:
yield 'last_exception', Variable('last_exception')
yield 'last_exc_value', Variable('last_exc_value')
outcome = self.guessbool(c_last_exception,
cases = [None] + list(classes),
replace_last_variable_except_in_first_case = replace_exc_values)
if outcome is None:
w_exc_cls, w_exc_value = None, None
else:
egg = self.recorder.crnt_block
w_exc_cls, w_exc_value = egg.inputargs[-2:]
if isinstance(egg.last_exception, Constant):
w_exc_cls = egg.last_exception
return outcome, w_exc_cls, w_exc_value
def build_flow(self):
while self.pendingblocks:
block = self.pendingblocks.pop(0)
frame = self.create_frame()
try:
self.recorder = block.patchframe(frame)
except StopFlowing:
continue # restarting a dead SpamBlock
try:
self.framestack.push(frame)
self.crnt_frame = frame
try:
w_result = frame.dispatch(frame.pycode,
frame.last_instr,
self)
finally:
self.crnt_frame = None
self.framestack.pop()
except OperationThatShouldNotBePropagatedError, e:
raise Exception(
'found an operation that always raises %s: %s' % (
self.space.unwrap(e.w_type).__name__,
self.space.unwrap(e.w_value)))
except ImplicitOperationError, e:
if isinstance(e.w_type, Constant):
exc_cls = e.w_type.value
else:
exc_cls = Exception
msg = "implicit %s shouldn't occur" % exc_cls.__name__
w_type = Constant(AssertionError)
w_value = Constant(AssertionError(msg))
link = self.make_link([w_type, w_value], self.graph.exceptblock)
self.recorder.crnt_block.closeblock(link)
except OperationError, e:
#print "OE", e.w_type, e.w_value
if (self.space.do_imports_immediately and
e.w_type is self.space.w_ImportError):
raise ImportError('import statement always raises %s' % (
e,))
link = self.make_link([e.w_type, e.w_value], self.graph.exceptblock)
self.recorder.crnt_block.closeblock(link)
except StopFlowing:
pass
except MergeBlock, e:
self.mergeblock(e.block, e.currentstate)
else:
assert w_result is not None
link = self.make_link([w_result], self.graph.returnblock)
self.recorder.crnt_block.closeblock(link)
del self.recorder
self.fixeggblocks()
def fixeggblocks(self):
# EggBlocks reuse the variables of their previous block,
# which is deemed not acceptable for simplicity of the operations
# that will be performed later on the flow graph.
def fixegg(link):
if isinstance(link, Link):
block = link.target
if isinstance(block, EggBlock):
if (not block.operations and len(block.exits) == 1 and
link.args == block.inputargs): # not renamed
# if the variables are not renamed across this link
# (common case for EggBlocks) then it's easy enough to
# get rid of the empty EggBlock.
link2 = block.exits[0]
link.args = list(link2.args)
link.target = link2.target
assert link2.exitcase is None
fixegg(link)
else:
mapping = {}
for a in block.inputargs:
mapping[a] = Variable(a)
block.renamevariables(mapping)
elif isinstance(link, SpamBlock):
del link.framestate # memory saver
traverse(fixegg, self.graph)
def mergeblock(self, currentblock, currentstate):
next_instr = currentstate.next_instr
# can 'currentstate' be merged with one of the blocks that
# already exist for this bytecode position?
candidates = self.joinpoints.setdefault(next_instr, [])
for block in candidates:
newstate = block.framestate.union(currentstate)
if newstate is not None:
# yes
finished = newstate == block.framestate
break
else:
# no
newstate = currentstate.copy()
finished = False
block = None
if finished:
newblock = block
else:
newblock = SpamBlock(newstate)
# unconditionally link the current block to the newblock
outputargs = currentstate.getoutputargs(newstate)
link = self.make_link(outputargs, newblock)
currentblock.closeblock(link)
# phew
if not finished:
if block is not None:
# to simplify the graph, we patch the old block to point
# directly at the new block which is its generalization
block.dead = True
block.operations = ()
block.exitswitch = None
outputargs = block.framestate.getoutputargs(newstate)
block.recloseblock(self.make_link(outputargs, newblock))
candidates.remove(block)
candidates.insert(0, newblock)
self.pendingblocks.append(newblock)
def sys_exc_info(self):
operr = ExecutionContext.sys_exc_info(self)
if isinstance(operr, ImplicitOperationError):
# re-raising an implicit operation makes it an explicit one
operr = OperationError(operr.w_type, operr.w_value)
return operr
# hack for unrolling iterables, don't use this
def replace_in_stack(self, oldvalue, newvalue):
w_new = Constant(newvalue)
stack_items_w = self.crnt_frame.valuestack_w
for i in range(self.crnt_frame.valuestackdepth):
w_v = stack_items_w[i]
if isinstance(w_v, Constant):
if w_v.value is oldvalue:
stack_items_w[i] = w_new
| Python |
# The model produced by the flowobjspace
# this is to be used by the translator mainly.
#
# the below object/attribute model evolved from
# a discussion in Berlin, 4th of october 2003
from __future__ import generators
import py
from pypy.tool.uid import uid, Hashable
from pypy.tool.sourcetools import PY_IDENTIFIER, nice_repr_for_func
"""
memory size before and after introduction of __slots__
using targetpypymain with -no-c
slottified annotation ann+genc
-------------------------------------------
nothing 321 MB 442 MB
Var/Const/SpaceOp 205 MB 325 MB
+ Link 189 MB 311 MB
+ Block 185 MB 304 MB
Dropping Variable.instances and using
just an instancenames dict brought
annotation down to 160 MB.
Computing the Variable.renamed attribute
and dropping Variable.instancenames
got annotation down to 109 MB.
Probably an effect of less fragmentation.
"""
__metaclass__ = type
class roproperty(object):
def __init__(self, getter):
self.getter = getter
def __get__(self, obj, cls=None):
if obj is None:
return self
else:
return self.getter(obj)
class FunctionGraph(object):
__slots__ = ['startblock', 'returnblock', 'exceptblock', '__dict__']
def __init__(self, name, startblock, return_var=None):
self.name = name # function name (possibly mangled already)
self.startblock = startblock
self.startblock.isstartblock = True
# build default returnblock
self.returnblock = Block([return_var or Variable()])
self.returnblock.operations = ()
self.returnblock.exits = ()
# block corresponding to exception results
self.exceptblock = Block([Variable('etype'), # exception class
Variable('evalue')]) # exception value
self.exceptblock.operations = ()
self.exceptblock.exits = ()
self.tag = None
def getargs(self):
return self.startblock.inputargs
def getreturnvar(self):
return self.returnblock.inputargs[0]
def getsource(self):
from pypy.tool.sourcetools import getsource
func = self.func # can raise AttributeError
src = getsource(self.func)
if src is None:
raise AttributeError('source not found')
return src
source = roproperty(getsource)
def getstartline(self):
return self.func.func_code.co_firstlineno
startline = roproperty(getstartline)
def getfilename(self):
return self.func.func_code.co_filename
filename = roproperty(getfilename)
def __str__(self):
if hasattr(self, 'func'):
return nice_repr_for_func(self.func, self.name)
else:
return self.name
def __repr__(self):
return '<FunctionGraph of %s at 0x%x>' % (self, uid(self))
def iterblocks(self):
block = self.startblock
yield block
seen = {block: True}
stack = list(block.exits[::-1])
while stack:
block = stack.pop().target
if block not in seen:
yield block
seen[block] = True
stack += block.exits[::-1]
def iterlinks(self):
block = self.startblock
seen = {block: True}
stack = list(block.exits[::-1])
while stack:
link = stack.pop()
yield link
block = link.target
if block not in seen:
seen[block] = True
stack += block.exits[::-1]
def iterblockops(self):
for block in self.iterblocks():
for op in block.operations:
yield block, op
def show(self, t=None):
from pypy.translator.tool.graphpage import FlowGraphPage
FlowGraphPage(t, [self]).display()
class Link(object):
__slots__ = """args target exitcase llexitcase prevblock
last_exception last_exc_value""".split()
def __init__(self, args, target, exitcase=None):
if target is not None:
assert len(args) == len(target.inputargs), "output args mismatch"
self.args = list(args) # mixed list of var/const
self.target = target # block
self.exitcase = exitcase # this is a concrete value
self.prevblock = None # the block this Link is an exit of
# exception passing vars
self.last_exception = None
self.last_exc_value = None
# right now only exception handling needs to introduce new variables on the links
def extravars(self, last_exception=None, last_exc_value=None):
self.last_exception = last_exception
self.last_exc_value = last_exc_value
def getextravars(self):
"Return the extra vars created by this Link."
result = []
if isinstance(self.last_exception, Variable):
result.append(self.last_exception)
if isinstance(self.last_exc_value, Variable):
result.append(self.last_exc_value)
return result
def copy(self, rename=lambda x: x):
newargs = [rename(a) for a in self.args]
newlink = Link(newargs, self.target, self.exitcase)
newlink.prevblock = self.prevblock
newlink.last_exception = rename(self.last_exception)
newlink.last_exc_value = rename(self.last_exc_value)
if hasattr(self, 'llexitcase'):
newlink.llexitcase = self.llexitcase
return newlink
def settarget(self, targetblock):
assert len(self.args) == len(targetblock.inputargs), (
"output args mismatch")
self.target = targetblock
def __repr__(self):
return "link from %s to %s" % (str(self.prevblock), str(self.target))
def show(self):
from pypy.translator.tool.graphpage import try_show
try_show(self)
class Block(object):
__slots__ = """isstartblock inputargs operations exitswitch
exits blockcolor""".split()
def __init__(self, inputargs):
self.isstartblock = False
self.inputargs = list(inputargs) # mixed list of variable/const XXX
self.operations = [] # list of SpaceOperation(s)
self.exitswitch = None # a variable or
# Constant(last_exception), see below
self.exits = [] # list of Link(s)
def at(self):
if self.operations and self.operations[0].offset >= 0:
return "@%d" % self.operations[0].offset
else:
return ""
def __str__(self):
if self.operations:
txt = "block@%d" % self.operations[0].offset
else:
txt = "codeless block"
return txt
def __repr__(self):
txt = "%s with %d exits" % (str(self), len(self.exits))
if self.exitswitch:
txt = "%s(%s)" % (txt, self.exitswitch)
return txt
def reallyalloperations(self):
"""Iterate over all operations, including cleanup sub-operations.
XXX remove!"""
for op in self.operations:
yield op
def getvariables(self):
"Return all variables mentioned in this Block."
result = self.inputargs[:]
for op in self.reallyalloperations():
result += op.args
result.append(op.result)
return uniqueitems([w for w in result if isinstance(w, Variable)])
def getconstants(self):
"Return all constants mentioned in this Block."
result = self.inputargs[:]
for op in self.reallyalloperations():
result += op.args
return uniqueitems([w for w in result if isinstance(w, Constant)])
def renamevariables(self, mapping):
for a in mapping:
assert isinstance(a, Variable), a
self.inputargs = [mapping.get(a, a) for a in self.inputargs]
for op in self.reallyalloperations():
op.args = [mapping.get(a, a) for a in op.args]
op.result = mapping.get(op.result, op.result)
self.exitswitch = mapping.get(self.exitswitch, self.exitswitch)
for link in self.exits:
link.args = [mapping.get(a, a) for a in link.args]
def closeblock(self, *exits):
assert self.exits == [], "block already closed"
self.recloseblock(*exits)
def recloseblock(self, *exits):
for exit in exits:
exit.prevblock = self
self.exits = exits
def show(self):
from pypy.translator.tool.graphpage import try_show
try_show(self)
class Variable(object):
__slots__ = ["_name", "_nr", "concretetype"]
## def getter(x): return x._ct
## def setter(x, ct):
## if repr(ct) == '<* PyObject>':
## import pdb; pdb.set_trace()
## x._ct = ct
## concretetype = property(getter, setter)
dummyname = 'v'
namesdict = {dummyname : (dummyname, 0)}
def name(self):
_name = self._name
_nr = self._nr
if _nr == -1:
# consume numbers lazily
nd = self.namesdict
_nr = self._nr = nd[_name][1]
nd[_name] = (_name, _nr + 1)
return "%s%d" % (_name, _nr)
name = property(name)
def renamed(self):
return self._name is not self.dummyname
renamed = property(renamed)
def __init__(self, name=None):
self._name = self.dummyname
self._nr = -1
# numbers are bound lazily, when the name is requested
if name is not None:
self.rename(name)
def __repr__(self):
return self.name
def rename(self, name):
if self._name is not self.dummyname: # don't rename several times
return
if type(name) is not str:
#assert isinstance(name, Variable) -- disabled for speed reasons
name = name._name
if name is self.dummyname: # the other Variable wasn't renamed either
return
else:
# remove strange characters in the name
name = name.translate(PY_IDENTIFIER) + '_'
if name[0] <= '9': # skipped the '0' <= which is always true
name = '_' + name
name = self.namesdict.setdefault(name, (name, 0))[0]
self._name = name
self._nr = -1
def set_name_from(self, v):
# this is for SSI_to_SSA only which should not know about internals
v.name # make sure v's name is finalized
self._name = v._name
self._nr = v._nr
def set_name(self, name, nr):
# this is for wrapper.py which wants to assign a name explicitly
self._name = intern(name)
self._nr = nr
def __reduce_ex__(self, *args):
if hasattr(self, 'concretetype'):
return _bv, (self._name, self._nr, self.concretetype)
else:
return _bv, (self._name, self._nr)
__reduce__ = __reduce_ex__
def _bv(_name, _nr, concretetype=None):
v = Variable.__new__(Variable, object)
v._name = _name
v._nr = _nr
if concretetype is not None:
v.concretetype = concretetype
nd = v.namesdict
if _nr >= nd.get(_name, 0):
nd[_name] = _nr + 1
return v
class Constant(Hashable):
__slots__ = ["concretetype"]
def __init__(self, value, concretetype = None):
Hashable.__init__(self, value)
if concretetype is not None:
self.concretetype = concretetype
def __reduce_ex__(self, *args):
if hasattr(self, 'concretetype'):
return Constant, (self.value, self.concretetype)
else:
return Constant, (self.value,)
__reduce__ = __reduce_ex__
class SpaceOperation(object):
__slots__ = "opname args result offset".split()
def __init__(self, opname, args, result, offset=-1):
self.opname = intern(opname) # operation name
self.args = list(args) # mixed list of var/const
self.result = result # either Variable or Constant instance
self.offset = offset # offset in code string
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.opname == other.opname and
self.args == other.args and
self.result == other.result)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash((self.opname,tuple(self.args),self.result))
def __repr__(self):
return "%r = %s(%s)" % (self.result, self.opname,
", ".join(map(repr, self.args)))
def __reduce_ex__(self, *args):
# avoid lots of useless list entities
return _sop, (self.opname, self.result, self.offset) + tuple(self.args)
__reduce__ = __reduce_ex__
# a small and efficient restorer
def _sop(opname, result, offset, *args):
return SpaceOperation(opname, args, result, offset)
class Atom:
def __init__(self, name):
self.__name__ = name # make save_global happy
def __repr__(self):
return self.__name__
last_exception = Atom('last_exception')
c_last_exception = Constant(last_exception)
# if Block().exitswitch == Constant(last_exception), it means that we are
# interested in catching the exception that the *last operation* of the
# block could raise. The exitcases of the links are None for no exception
# or XxxError classes to catch the matching exceptions.
def uniqueitems(lst):
"Returns a list with duplicate elements removed."
result = []
seen = {}
for item in lst:
if item not in seen:
result.append(item)
seen[item] = True
return result
#_________________________________________________________
# a visitor for easy traversal of the above model
##import inspect # for getmro
##class traverse:
## def __init__(self, visitor, functiongraph):
## """ send the visitor over all (reachable) nodes.
## the visitor needs to have either callable attributes 'visit_typename'
## or otherwise is callable itself.
## """
## self.visitor = visitor
## self.visitor_cache = {}
## self.seen = {}
## self.visit(functiongraph)
## def visit(self, node):
## if id(node) in self.seen:
## return
## # do the visit
## cls = node.__class__
## try:
## consume = self.visitor_cache[cls]
## except KeyError:
## for subclass in inspect.getmro(cls):
## consume = getattr(self.visitor, "visit_" + subclass.__name__, None)
## if consume:
## break
## else:
## consume = getattr(self.visitor, 'visit', self.visitor)
## assert callable(consume), "visitor not found for %r on %r" % (cls, self.visitor)
## self.visitor_cache[cls] = consume
## self.seen[id(node)] = consume(node)
## # recurse
## if isinstance(node, Block):
## for obj in node.exits:
## self.visit(obj)
## elif isinstance(node, Link):
## self.visit(node.target)
## elif isinstance(node, FunctionGraph):
## self.visit(node.startblock)
## else:
## raise ValueError, "could not dispatch %r" % cls
def traverse(visit, functiongraph):
block = functiongraph.startblock
visit(block)
seen = {id(block): True}
stack = list(block.exits[::-1])
while stack:
link = stack.pop()
visit(link)
block = link.target
if id(block) not in seen:
visit(block)
seen[id(block)] = True
stack += block.exits[::-1]
def flatten(funcgraph):
l = []
traverse(l.append, funcgraph)
return l
def flattenobj(*args):
for arg in args:
try:
for atom in flattenobj(*arg):
yield atom
except: yield arg
def mkentrymap(funcgraph):
"Returns a dict mapping Blocks to lists of Links."
startlink = Link(funcgraph.getargs(), funcgraph.startblock)
result = {funcgraph.startblock: [startlink]}
for link in funcgraph.iterlinks():
lst = result.setdefault(link.target, [])
lst.append(link)
return result
def copygraph(graph, shallow=False, varmap={}):
"Make a copy of a flow graph."
blockmap = {}
varmap = varmap.copy()
def copyvar(v):
if shallow:
return v
try:
return varmap[v]
except KeyError:
if isinstance(v, Variable):
v2 = varmap[v] = Variable(v)
if hasattr(v, 'concretetype'):
v2.concretetype = v.concretetype
return v2
else:
return v
def copyblock(block):
newblock = Block([copyvar(v) for v in block.inputargs])
if block.operations == ():
newblock.operations = ()
else:
def copyoplist(oplist):
if shallow:
return oplist[:]
result = []
for op in oplist:
copyop = SpaceOperation(op.opname,
[copyvar(v) for v in op.args],
copyvar(op.result), op.offset)
#copyop.offset = op.offset
result.append(copyop)
return result
newblock.operations = copyoplist(block.operations)
newblock.exitswitch = copyvar(block.exitswitch)
return newblock
for block in graph.iterblocks():
blockmap[block] = copyblock(block)
if graph.returnblock not in blockmap:
blockmap[graph.returnblock] = copyblock(graph.returnblock)
if graph.exceptblock not in blockmap:
blockmap[graph.exceptblock] = copyblock(graph.exceptblock)
for block, newblock in blockmap.items():
newlinks = []
for link in block.exits:
newlink = link.copy(copyvar)
newlink.target = blockmap[link.target]
newlinks.append(newlink)
newblock.closeblock(*newlinks)
newstartblock = blockmap[graph.startblock]
newstartblock.isstartblock = True
newgraph = FunctionGraph(graph.name, newstartblock)
newgraph.returnblock = blockmap[graph.returnblock]
newgraph.exceptblock = blockmap[graph.exceptblock]
for key, value in graph.__dict__.items():
newgraph.__dict__.setdefault(key, value)
return newgraph
def checkgraph(graph):
"Check the consistency of a flow graph."
if not __debug__:
return
try:
vars_previous_blocks = {}
exitblocks = {graph.returnblock: 1, # retval
graph.exceptblock: 2} # exc_cls, exc_value
for block, nbargs in exitblocks.items():
assert len(block.inputargs) == nbargs
assert block.operations == ()
assert block.exits == ()
for block in graph.iterblocks():
assert bool(block.isstartblock) == (block is graph.startblock)
assert type(block.exits) is tuple, (
"block.exits is a %s (closeblock() or recloseblock() missing?)"
% (type(block.exits).__name__,))
if not block.exits:
assert block in exitblocks
vars = {}
def definevar(v, only_in_link=None):
assert isinstance(v, Variable)
assert v not in vars, "duplicate variable %r" % (v,)
assert v not in vars_previous_blocks, (
"variable %r used in more than one block" % (v,))
vars[v] = only_in_link
def usevar(v, in_link=None):
assert v in vars
if in_link is not None:
assert vars[v] is None or vars[v] is in_link
for v in block.inputargs:
definevar(v)
for op in block.operations:
for v in op.args:
assert isinstance(v, (Constant, Variable))
if isinstance(v, Variable):
usevar(v)
else:
assert v.value is not last_exception
#assert v.value != last_exc_value
if op.opname == 'direct_call':
assert isinstance(op.args[0], Constant)
definevar(op.result)
exc_links = {}
if block.exitswitch is None:
assert len(block.exits) <= 1
if block.exits:
assert block.exits[0].exitcase is None
elif block.exitswitch == Constant(last_exception):
assert len(block.operations) >= 1
# check if an exception catch is done on a reasonable
# operation
assert block.operations[-1].opname not in ("keepalive",
"cast_pointer",
"same_as")
assert len(block.exits) >= 2
assert block.exits[0].exitcase is None
for link in block.exits[1:]:
assert issubclass(link.exitcase, py.builtin.BaseException)
exc_links[link] = True
else:
assert isinstance(block.exitswitch, Variable)
assert block.exitswitch in vars
if (len(block.exits) == 2 and block.exits[0].exitcase is False
and block.exits[1].exitcase is True):
# a boolean switch
pass
else:
# a multiple-cases switch (or else the False and True
# branches are in the wrong order)
assert len(block.exits) >= 1
cases = [link.exitcase for link in block.exits]
has_default = cases[-1] == 'default'
for n in cases[:len(cases)-has_default]:
if isinstance(n, (int, long)):
continue
if isinstance(n, (str, unicode)) and len(n) == 1:
continue
assert n != 'default', (
"'default' branch of a switch is not the last exit"
)
assert n is not None, (
"exitswitch Variable followed by a None exitcase")
raise AssertionError(
"switch on a non-primitive value %r" % (n,))
allexitcases = {}
for link in block.exits:
assert len(link.args) == len(link.target.inputargs)
assert link.prevblock is block
exc_link = link in exc_links
if exc_link:
for v in [link.last_exception, link.last_exc_value]:
assert isinstance(v, (Variable, Constant))
if isinstance(v, Variable):
definevar(v, only_in_link=link)
else:
assert link.last_exception is None
assert link.last_exc_value is None
for v in link.args:
assert isinstance(v, (Constant, Variable))
if isinstance(v, Variable):
usevar(v, in_link=link)
if exc_link:
assert v != block.operations[-1].result
#else:
# if not exc_link:
# assert v.value is not last_exception
# #assert v.value != last_exc_value
allexitcases[link.exitcase] = True
assert len(allexitcases) == len(block.exits)
vars_previous_blocks.update(vars)
except AssertionError, e:
# hack for debug tools only
#graph.show() # <== ENABLE THIS TO SEE THE BROKEN GRAPH
if block and not hasattr(e, '__annotator_block'):
setattr(e, '__annotator_block', block)
raise
def summary(graph):
# return a summary of the instructions found in a graph
insns = {}
for block in graph.iterblocks():
for op in block.operations:
if op.opname != 'same_as':
insns[op.opname] = insns.get(op.opname, 0) + 1
return insns
def safe_iterblocks(graph):
# for debugging or displaying broken graphs.
# You still have to check that the yielded blocks are really Blocks.
block = getattr(graph, 'startblock', None)
yield block
seen = {block: True}
stack = list(getattr(block, 'exits', [])[::-1])
while stack:
block = stack.pop().target
if block not in seen:
yield block
seen[block] = True
stack += getattr(block, 'exits', [])[::-1]
def safe_iterlinks(graph):
# for debugging or displaying broken graphs.
# You still have to check that the yielded links are really Links.
block = getattr(graph, 'startblock', None)
seen = {block: True}
stack = list(getattr(block, 'exits', [])[::-1])
while stack:
link = stack.pop()
yield link
block = getattr(link, 'target', None)
if block not in seen:
seen[block] = True
stack += getattr(block, 'exits', [])[::-1]
| Python |
from pypy.objspace.flow.objspace import UnwrapException
from pypy.objspace.flow.model import Constant
from pypy.objspace.flow.operation import OperationName, Arity
from pypy.interpreter.gateway import ApplevelClass
from pypy.interpreter.error import OperationError
from pypy.tool.cache import Cache
def sc_import(space, fn, args):
w_name, w_glob, w_loc, w_frm = args.fixedunpack(4)
if not isinstance(w_loc, Constant):
# import * in a function gives us the locals as Variable
# we always forbid it as a SyntaxError
raise SyntaxError, "RPython: import * is not allowed in functions"
if space.do_imports_immediately:
name, glob, loc, frm = (space.unwrap(w_name), space.unwrap(w_glob),
space.unwrap(w_loc), space.unwrap(w_frm))
try:
mod = __import__(name, glob, loc, frm)
except ImportError, e:
raise OperationError(space.w_ImportError, space.wrap(str(e)))
return space.wrap(mod)
# redirect it, but avoid exposing the globals
w_glob = Constant({})
return space.do_operation('simple_call', Constant(__import__),
w_name, w_glob, w_loc, w_frm)
def sc_operator(space, fn, args):
args_w, kwds_w = args.unpack()
assert kwds_w == {}, "should not call %r with keyword arguments" % (fn,)
opname = OperationName[fn]
if len(args_w) != Arity[opname]:
if opname == 'pow' and len(args_w) == 2:
args_w = args_w + [Constant(None)]
elif opname == 'getattr' and len(args_w) == 3:
return space.do_operation('simple_call', Constant(getattr), *args_w)
else:
raise Exception, "should call %r with exactly %d arguments" % (
fn, Arity[opname])
if space.config.translation.builtins_can_raise_exceptions:
# in this mode, avoid constant folding and raise an implicit Exception
w_result = space.do_operation(opname, *args_w)
space.handle_implicit_exceptions([Exception])
return w_result
else:
# in normal mode, completely replace the call with the underlying
# operation and its limited implicit exceptions semantic
return getattr(space, opname)(*args_w)
# This is not a space cache.
# It is just collecting the compiled functions from all the source snippets.
class FunctionCache(Cache):
"""A cache mapping applevel instances to dicts with simple functions"""
def _build(app):
"""NOT_RPYTHON.
Called indirectly by ApplevelClass.interphook().appcaller()."""
dic = {}
if not app.can_use_geninterp:
return None
if app.filename is not None:
dic['__file__'] = app.filename
dic['__name__'] = app.modname
exec app.code in dic
return dic
_build = staticmethod(_build)
# _________________________________________________________________________
# a simplified version of the basic printing routines, for RPython programs
class StdOutBuffer:
linebuf = []
stdoutbuffer = StdOutBuffer()
def rpython_print_item(s):
buf = stdoutbuffer.linebuf
for c in s:
buf.append(c)
buf.append(' ')
def rpython_print_newline():
buf = stdoutbuffer.linebuf
if buf:
buf[-1] = '\n'
s = ''.join(buf)
del buf[:]
else:
s = '\n'
import os
os.write(1, s)
# _________________________________________________________________________
compiled_funcs = FunctionCache()
def sc_applevel(space, app, name, args_w):
dic = compiled_funcs.getorbuild(app)
if not dic:
return None # signal that this is not RPython
func = dic[name]
if getattr(func, '_annspecialcase_', '').startswith('flowspace:'):
# a hack to replace specific app-level helpers with simplified
# RPython versions
name = func._annspecialcase_[len('flowspace:'):]
if name == 'print_item': # more special cases...
w_s = space.do_operation('str', *args_w)
args_w = (w_s,)
func = globals()['rpython_' + name]
else:
# otherwise, just call the app-level helper and hope that it
# is RPython enough
pass
return space.do_operation('simple_call', Constant(func), *args_w)
def setup(space):
# fn = pyframe.normalize_exception.get_function(space)
# this is now routed through the objspace, directly.
# space.specialcases[fn] = sc_normalize_exception
space.specialcases[__import__] = sc_import
# redirect ApplevelClass for print et al.
space.specialcases[ApplevelClass] = sc_applevel
# turn calls to built-in functions to the corresponding operation,
# if possible
for fn in OperationName:
space.specialcases[fn] = sc_operator
| Python |
from pypy.interpreter.pyframe import PyFrame
from pypy.interpreter.pyopcode import SuspendedUnroller
from pypy.interpreter.error import OperationError
from pypy.rlib.unroll import SpecTag
from pypy.objspace.flow.model import *
class FrameState:
# XXX this class depends on the internal state of PyFrame objects
def __init__(self, state):
if isinstance(state, PyFrame):
# getfastscope() can return real None, for undefined locals
data = state.getfastscope() + state.savevaluestack()
if state.last_exception is None:
data.append(Constant(None))
data.append(Constant(None))
else:
data.append(state.last_exception.w_type)
data.append(state.last_exception.w_value)
recursively_flatten(state.space, data)
self.mergeable = data
self.nonmergeable = (
state.blockstack[:],
state.last_instr, # == next_instr when between bytecodes
state.w_locals,
)
elif isinstance(state, tuple):
self.mergeable, self.nonmergeable = state
else:
raise TypeError("can't get framestate for %r" %
state.__class__.__name__)
self.next_instr = self.nonmergeable[1]
for w1 in self.mergeable:
assert isinstance(w1, (Variable, Constant)) or w1 is None, (
'%r found in frame state' % w1)
def restoreframe(self, frame):
if isinstance(frame, PyFrame):
fastlocals = len(frame.fastlocals_w)
data = self.mergeable[:]
recursively_unflatten(frame.space, data)
frame.setfastscope(data[:fastlocals]) # Nones == undefined locals
frame.restorevaluestack(data[fastlocals:-2])
if data[-2] == Constant(None):
assert data[-1] == Constant(None)
frame.last_exception = None
else:
frame.last_exception = OperationError(data[-2], data[-1])
(
frame.blockstack[:],
frame.last_instr,
frame.w_locals,
) = self.nonmergeable
else:
raise TypeError("can't set framestate for %r" %
frame.__class__.__name__)
def copy(self):
"Make a copy of this state in which all Variables are fresh."
newstate = []
for w in self.mergeable:
if isinstance(w, Variable):
w = Variable()
newstate.append(w)
return FrameState((newstate, self.nonmergeable))
def getvariables(self):
return [w for w in self.mergeable if isinstance(w, Variable)]
def __eq__(self, other):
"""Two states are equal
if they only use different Variables at the same place"""
# safety check, don't try to compare states with different
# nonmergeable states
assert isinstance(other, FrameState)
assert len(self.mergeable) == len(other.mergeable)
assert self.nonmergeable == other.nonmergeable
for w1, w2 in zip(self.mergeable, other.mergeable):
if not (w1 == w2 or (isinstance(w1, Variable) and
isinstance(w2, Variable))):
return False
return True
def __ne__(self, other):
return not (self == other)
def union(self, other):
"""Compute a state that is at least as general as both self and other.
A state 'a' is more general than a state 'b' if all Variables in 'b'
are also Variables in 'a', but 'a' may have more Variables.
"""
newstate = []
try:
for w1, w2 in zip(self.mergeable, other.mergeable):
newstate.append(union(w1, w2))
except UnionError:
return None
return FrameState((newstate, self.nonmergeable))
def getoutputargs(self, targetstate):
"Return the output arguments needed to link self to targetstate."
result = []
for w_output, w_target in zip(self.mergeable, targetstate.mergeable):
if isinstance(w_target, Variable):
result.append(w_output)
return result
class UnionError(Exception):
"The two states should be merged."
def union(w1, w2):
"Union of two variables or constants."
if w1 is None or w2 is None:
return None # if w1 or w2 is an undefined local, we "kill" the value
# coming from the other path and return an undefined local
if isinstance(w1, Variable) or isinstance(w2, Variable):
return Variable() # new fresh Variable
if isinstance(w1, Constant) and isinstance(w2, Constant):
if w1 == w2:
return w1
# SuspendedUnrollers represent stack unrollers in the stack.
# They should not be merged because they will be unwrapped.
# This is needed for try:except: and try:finally:, though
# it makes the control flow a bit larger by duplicating the
# handlers.
dont_merge_w1 = w1 in UNPICKLE_TAGS or isinstance(w1.value, SpecTag)
dont_merge_w2 = w2 in UNPICKLE_TAGS or isinstance(w2.value, SpecTag)
if dont_merge_w1 or dont_merge_w2:
raise UnionError
else:
return Variable() # generalize different constants
raise TypeError('union of %r and %r' % (w1.__class__.__name__,
w2.__class__.__name__))
# ____________________________________________________________
#
# We have to flatten out the state of the frame into a list of
# Variables and Constants. This is done above by collecting the
# locals and the items on the value stack, but the latter may contain
# SuspendedUnroller. We have to handle these specially, because
# some of them hide references to more Variables and Constants.
# The trick is to flatten ("pickle") them into the list so that the
# extra Variables show up directly in the list too.
class PickleTag:
pass
PICKLE_TAGS = {}
UNPICKLE_TAGS = {}
def recursively_flatten(space, lst):
i = 0
while i < len(lst):
item = lst[i]
if not (isinstance(item, Constant) and
isinstance(item.value, SuspendedUnroller)):
i += 1
else:
unroller = item.value
vars = unroller.state_unpack_variables(space)
key = unroller.__class__, len(vars)
try:
tag = PICKLE_TAGS[key]
except:
tag = PICKLE_TAGS[key] = Constant(PickleTag())
UNPICKLE_TAGS[tag] = key
lst[i:i+1] = [tag] + vars
def recursively_unflatten(space, lst):
for i in range(len(lst)-1, -1, -1):
item = lst[i]
if item in UNPICKLE_TAGS:
unrollerclass, argcount = UNPICKLE_TAGS[item]
arguments = lst[i+1: i+1+argcount]
del lst[i+1: i+1+argcount]
unroller = unrollerclass.state_pack_variables(space, *arguments)
lst[i] = space.wrap(unroller)
| Python |
# ______________________________________________________________________
import sys, operator, types
from pypy.interpreter.baseobjspace import ObjSpace, Wrappable
from pypy.interpreter.pycode import PyCode, cpython_code_signature
from pypy.interpreter.module import Module
from pypy.interpreter.error import OperationError
from pypy.objspace.flow.model import *
from pypy.objspace.flow import flowcontext
from pypy.objspace.flow.operation import FunctionByName
from pypy.rlib.unroll import unrolling_iterable, _unroller
debug = 0
class UnwrapException(Exception):
"Attempted to unwrap a Variable."
class WrapException(Exception):
"""Attempted wrapping of a type that cannot sanely appear in flow graph or during its construction"""
# method-wrappers have not enough introspection in CPython
if hasattr(complex.real.__get__, 'im_self'):
type_with_bad_introspection = None # on top of PyPy
else:
type_with_bad_introspection = type(complex.real.__get__)
# ______________________________________________________________________
class FlowObjSpace(ObjSpace):
"""NOT_RPYTHON.
The flow objspace space is used to produce a flow graph by recording
the space operations that the interpreter generates when it interprets
(the bytecode of) some function.
"""
full_exceptions = False
do_imports_immediately = True
def initialize(self):
import __builtin__
self.concrete_mode = 1
self.w_None = Constant(None)
self.builtin = Module(self, Constant('__builtin__'), Constant(__builtin__.__dict__))
def pick_builtin(w_globals):
return self.builtin
self.builtin.pick_builtin = pick_builtin
self.sys = Module(self, Constant('sys'), Constant(sys.__dict__))
self.sys.recursionlimit = 100
self.w_False = Constant(False)
self.w_True = Constant(True)
self.w_type = Constant(type)
self.w_tuple = Constant(tuple)
self.concrete_mode = 0
for exc in [KeyError, ValueError, IndexError, StopIteration,
AssertionError, TypeError, AttributeError, ImportError,
RuntimeError]:
clsname = exc.__name__
setattr(self, 'w_'+clsname, Constant(exc))
# the following exceptions are the ones that should not show up
# during flow graph construction; they are triggered by
# non-R-Pythonic constructs or real bugs like typos.
for exc in [NameError, UnboundLocalError]:
clsname = exc.__name__
setattr(self, 'w_'+clsname, None)
self.specialcases = {}
#self.make_builtins()
#self.make_sys()
# objects which should keep their SomeObjectness
self.not_really_const = NOT_REALLY_CONST
def enter_cache_building_mode(self):
# when populating the caches, the flow space switches to
# "concrete mode". In this mode, only Constants are allowed
# and no SpaceOperation is recorded.
previous_recorder = self.executioncontext.recorder
self.executioncontext.recorder = flowcontext.ConcreteNoOp()
self.concrete_mode += 1
return previous_recorder
def leave_cache_building_mode(self, previous_recorder):
self.executioncontext.recorder = previous_recorder
self.concrete_mode -= 1
def newdict(self):
if self.concrete_mode:
return Constant({})
return self.do_operation('newdict')
def newtuple(self, args_w):
try:
content = [self.unwrap(w_arg) for w_arg in args_w]
except UnwrapException:
return self.do_operation('newtuple', *args_w)
else:
return Constant(tuple(content))
def newlist(self, args_w):
if self.concrete_mode:
content = [self.unwrap(w_arg) for w_arg in args_w]
return Constant(content)
return self.do_operation('newlist', *args_w)
def newslice(self, w_start, w_stop, w_step):
if self.concrete_mode:
return Constant(slice(self.unwrap(w_start),
self.unwrap(w_stop),
self.unwrap(w_step)))
return self.do_operation('newslice', w_start, w_stop, w_step)
def wrap(self, obj):
if isinstance(obj, (Variable, Constant)):
raise TypeError("already wrapped: " + repr(obj))
# method-wrapper have ill-defined comparison and introspection
# to appear in a flow graph
if type(obj) is type_with_bad_introspection:
raise WrapException
return Constant(obj)
def int_w(self, w_obj):
if isinstance(w_obj, Constant):
val = w_obj.value
if type(val) not in (int,long):
raise TypeError("expected integer: " + repr(w_obj))
return val
return self.unwrap(w_obj)
def uint_w(self, w_obj):
if isinstance(w_obj, Constant):
from pypy.rlib.rarithmetic import r_uint
val = w_obj.value
if type(val) is not r_uint:
raise TypeError("expected unsigned: " + repr(w_obj))
return val
return self.unwrap(w_obj)
def str_w(self, w_obj):
if isinstance(w_obj, Constant):
val = w_obj.value
if type(val) is not str:
raise TypeError("expected string: " + repr(w_obj))
return val
return self.unwrap(w_obj)
def float_w(self, w_obj):
if isinstance(w_obj, Constant):
val = w_obj.value
if type(val) is not float:
raise TypeError("expected float: " + repr(w_obj))
return val
return self.unwrap(w_obj)
def unwrap(self, w_obj):
if isinstance(w_obj, Variable):
raise UnwrapException
elif isinstance(w_obj, Constant):
return w_obj.value
else:
raise TypeError("not wrapped: " + repr(w_obj))
def unwrap_for_computation(self, w_obj):
obj = self.unwrap(w_obj)
to_check = obj
if hasattr(to_check, 'im_self'):
to_check = to_check.im_self
if (not isinstance(to_check, (type, types.ClassType, types.ModuleType)) and
# classes/types/modules are assumed immutable
hasattr(to_check, '__class__') and to_check.__class__.__module__ != '__builtin__'):
frozen = hasattr(to_check, '_freeze_') and to_check._freeze_()
if not frozen:
if self.concrete_mode:
# xxx do we want some warning? notice that some stuff is harmless
# like setitem(dict, 'n', mutable)
pass
else: # cannot count on it not mutating at runtime!
raise UnwrapException
return obj
def interpclass_w(self, w_obj):
obj = self.unwrap(w_obj)
if isinstance(obj, Wrappable):
return obj
return None
def getexecutioncontext(self):
return getattr(self, 'executioncontext', None)
def setup_executioncontext(self, ec):
self.executioncontext = ec
from pypy.objspace.flow import specialcase
specialcase.setup(self)
def exception_match(self, w_exc_type, w_check_class):
try:
check_class = self.unwrap(w_check_class)
except UnwrapException:
raise Exception, "non-constant except guard"
if not isinstance(check_class, tuple):
# the simple case
return ObjSpace.exception_match(self, w_exc_type, w_check_class)
# checking a tuple of classes
for w_klass in self.unpacktuple(w_check_class):
if ObjSpace.exception_match(self, w_exc_type, w_klass):
return True
return False
def getconstclass(space, w_cls):
try:
ecls = space.unwrap(w_cls)
except UnwrapException:
pass
else:
if isinstance(ecls, (type, types.ClassType)):
return ecls
return None
def abstract_issubclass(self, w_obj, w_cls, failhard=False):
return self.issubtype(w_obj, w_cls)
def abstract_isinstance(self, w_obj, w_cls):
return self.isinstance(w_obj, w_cls)
def abstract_isclass(self, w_obj):
return self.isinstance(w_obj, self.w_type)
def abstract_getclass(self, w_obj):
return self.type(w_obj)
def build_flow(self, func, constargs={}):
"""
"""
if func.func_doc and func.func_doc.lstrip().startswith('NOT_RPYTHON'):
raise Exception, "%r is tagged as NOT_RPYTHON" % (func,)
code = func.func_code
code = PyCode._from_code(self, code)
if func.func_closure is None:
closure = None
else:
closure = [extract_cell_content(c) for c in func.func_closure]
# CallableFactory.pycall may add class_ to functions that are methods
name = func.func_name
class_ = getattr(func, 'class_', None)
if class_ is not None:
name = '%s.%s' % (class_.__name__, name)
for c in "<>&!":
name = name.replace(c, '_')
ec = flowcontext.FlowExecutionContext(self, code, func.func_globals,
constargs, closure, name)
graph = ec.graph
graph.func = func
# attach a signature and defaults to the graph
# so that it becomes even more interchangeable with the function
# itself
graph.signature = cpython_code_signature(code)
graph.defaults = func.func_defaults or ()
self.setup_executioncontext(ec)
from pypy.tool.error import FlowingError, format_global_error
try:
ec.build_flow()
except FlowingError, a:
# attach additional source info to AnnotatorError
_, _, tb = sys.exc_info()
e = FlowingError(format_global_error(ec.graph, ec.crnt_offset, str(a)))
raise FlowingError, e, tb
checkgraph(graph)
return graph
def unpacktuple(self, w_tuple, expected_length=None):
## # special case to accept either Constant tuples
## # or real tuples of Variables/Constants
## if isinstance(w_tuple, tuple):
## result = w_tuple
## else:
unwrapped = self.unwrap(w_tuple)
result = tuple([Constant(x) for x in unwrapped])
if expected_length is not None and len(result) != expected_length:
raise ValueError, "got a tuple of length %d instead of %d" % (
len(result), expected_length)
return result
def unpackiterable(self, w_iterable, expected_length=None):
if not isinstance(w_iterable, Variable):
l = list(self.unwrap(w_iterable))
if expected_length is not None and len(l) != expected_length:
raise ValueError
return [self.wrap(x) for x in l]
if isinstance(w_iterable, Variable) and expected_length is None:
raise UnwrapException, ("cannot unpack a Variable iterable"
"without knowing its length")
## # XXX TEMPORARY HACK XXX TEMPORARY HACK XXX TEMPORARY HACK
## print ("*** cannot unpack a Variable iterable "
## "without knowing its length,")
## print " assuming a list or tuple with up to 7 items"
## items = []
## w_len = self.len(w_iterable)
## i = 0
## while True:
## w_i = self.wrap(i)
## w_cond = self.eq(w_len, w_i)
## if self.is_true(w_cond):
## break # done
## if i == 7:
## # too many values
## raise OperationError(self.w_AssertionError, self.w_None)
## w_item = self.do_operation('getitem', w_iterable, w_i)
## items.append(w_item)
## i += 1
## return items
## # XXX TEMPORARY HACK XXX TEMPORARY HACK XXX TEMPORARY HACK
elif expected_length is not None:
w_len = self.len(w_iterable)
w_correct = self.eq(w_len, self.wrap(expected_length))
if not self.is_true(w_correct):
e = OperationError(self.w_ValueError, self.w_None)
e.normalize_exception(self)
raise e
return [self.do_operation('getitem', w_iterable, self.wrap(i))
for i in range(expected_length)]
return ObjSpace.unpackiterable(self, w_iterable, expected_length)
# ____________________________________________________________
def do_operation(self, name, *args_w):
spaceop = SpaceOperation(name, args_w, Variable())
if hasattr(self, 'executioncontext'): # not here during bootstrapping
spaceop.offset = self.executioncontext.crnt_offset
self.executioncontext.recorder.append(spaceop)
return spaceop.result
def do_operation_with_implicit_exceptions(self, name, *args_w):
w_result = self.do_operation(name, *args_w)
self.handle_implicit_exceptions(implicit_exceptions.get(name))
return w_result
def is_true(self, w_obj):
try:
obj = self.unwrap_for_computation(w_obj)
except UnwrapException:
pass
else:
return bool(obj)
w_truthvalue = self.do_operation('is_true', w_obj)
context = self.getexecutioncontext()
return context.guessbool(w_truthvalue)
def iter(self, w_iterable):
try:
iterable = self.unwrap(w_iterable)
except UnwrapException:
pass
else:
if isinstance(iterable, unrolling_iterable):
return self.wrap(iterable.get_unroller())
w_iter = self.do_operation("iter", w_iterable)
return w_iter
def next(self, w_iter):
context = self.getexecutioncontext()
try:
it = self.unwrap(w_iter)
except UnwrapException:
pass
else:
if isinstance(it, _unroller):
try:
v, next_unroller = it.step()
except IndexError:
raise OperationError(self.w_StopIteration, self.w_None)
else:
context.replace_in_stack(it, next_unroller)
return self.wrap(v)
w_item = self.do_operation("next", w_iter)
outcome, w_exc_cls, w_exc_value = context.guessexception(StopIteration,
RuntimeError)
if outcome is StopIteration:
raise OperationError(self.w_StopIteration, w_exc_value)
elif outcome is RuntimeError:
raise flowcontext.ImplicitOperationError(self.w_RuntimeError,
w_exc_value)
else:
return w_item
def setitem(self, w_obj, w_key, w_val):
if self.concrete_mode:
try:
obj = self.unwrap_for_computation(w_obj)
key = self.unwrap_for_computation(w_key)
val = self.unwrap_for_computation(w_val)
operator.setitem(obj, key, val)
return self.w_None
except UnwrapException:
pass
return self.do_operation_with_implicit_exceptions('setitem', w_obj,
w_key, w_val)
def call_args(self, w_callable, args):
try:
fn = self.unwrap(w_callable)
sc = self.specialcases[fn] # TypeError if 'fn' not hashable
except (UnwrapException, KeyError, TypeError):
pass
else:
return sc(self, fn, args)
try:
args_w, kwds_w = args.unpack()
except UnwrapException:
args_w, kwds_w = '?', '?'
# NOTE: annrpython needs to know about the following two operations!
if not kwds_w:
# simple case
w_res = self.do_operation('simple_call', w_callable, *args_w)
else:
# general case
shape, args_w = args.flatten()
w_res = self.do_operation('call_args', w_callable, Constant(shape),
*args_w)
# maybe the call has generated an exception (any one)
# but, let's say, not if we are calling a built-in class or function
# because this gets in the way of the special-casing of
#
# raise SomeError(x)
#
# as shown by test_objspace.test_raise3.
exceptions = [Exception] # *any* exception by default
if isinstance(w_callable, Constant):
c = w_callable.value
if not self.config.translation.builtins_can_raise_exceptions:
if (isinstance(c, (types.BuiltinFunctionType,
types.BuiltinMethodType,
types.ClassType,
types.TypeType)) and
c.__module__ in ['__builtin__', 'exceptions']):
exceptions = implicit_exceptions.get(c, None)
self.handle_implicit_exceptions(exceptions)
return w_res
def handle_implicit_exceptions(self, exceptions):
if exceptions:
# catch possible exceptions implicitly. If the OperationError
# below is not caught in the same function, it will produce an
# exception-raising return block in the flow graph. Note that
# even if the interpreter re-raises the exception, it will not
# be the same ImplicitOperationError instance internally.
context = self.getexecutioncontext()
outcome, w_exc_cls, w_exc_value = context.guessexception(*exceptions)
if outcome is not None:
# we assume that the caught exc_cls will be exactly the
# one specified by 'outcome', and not a subclass of it,
# unless 'outcome' is Exception.
#if outcome is not Exception:
#w_exc_cls = Constant(outcome) Now done by guessexception itself
#pass
raise flowcontext.ImplicitOperationError(w_exc_cls,
w_exc_value)
def w_KeyboardInterrupt(self):
# XXX XXX Ha Ha
# the reason to do this is: if you interrupt the flowing of a function
# with <Ctrl-C> the bytecode interpreter will raise an applevel
# KeyboardInterrup and you will get an AttributeError: space does not
# have w_KeyboardInterrupt, which is not very helpful
raise KeyboardInterrupt
w_KeyboardInterrupt = property(w_KeyboardInterrupt)
# the following gives us easy access to declare more for applications:
NOT_REALLY_CONST = {
Constant(sys): {
Constant('maxint'): True,
Constant('maxunicode'): True,
Constant('api_version'): True,
Constant('exit'): True,
Constant('exc_info'): True,
Constant('getrefcount'): True,
Constant('getdefaultencoding'): True,
# this is an incomplete list of true constants.
# if we add much more, a dedicated class
# might be considered for special objects.
}
}
# ______________________________________________________________________
op_appendices = {}
for _name, _exc in(
('ovf', OverflowError),
('idx', IndexError),
('key', KeyError),
('att', AttributeError),
('typ', TypeError),
('zer', ZeroDivisionError),
('val', ValueError),
#('flo', FloatingPointError)
):
op_appendices[_exc] = _name
del _name, _exc
implicit_exceptions = {
int: [ValueError], # built-ins that can always raise exceptions
float: [ValueError],
chr: [ValueError],
unichr: [ValueError],
# specifying IndexError, and KeyError beyond Exception,
# allows the annotator to be more precise, see test_reraiseAnything/KeyError in
# the annotator tests
'getitem': [IndexError, KeyError, Exception],
'setitem': [IndexError, KeyError, Exception],
'delitem': [IndexError, KeyError, Exception],
}
def _add_exceptions(names, exc):
for name in names.split():
lis = implicit_exceptions.setdefault(name, [])
if exc in lis:
raise ValueError, "your list is causing duplication!"
lis.append(exc)
assert exc in op_appendices
def _add_except_ovf(names):
# duplicate exceptions and add OverflowError
for name in names.split():
lis = implicit_exceptions.setdefault(name, [])[:]
lis.append(OverflowError)
implicit_exceptions[name+"_ovf"] = lis
#for _err in IndexError, KeyError:
# _add_exceptions("""getitem setitem delitem""", _err)
for _name in 'getattr', 'delattr':
_add_exceptions(_name, AttributeError)
for _name in 'iter', 'coerce':
_add_exceptions(_name, TypeError)
del _name#, _err
_add_exceptions("""div mod divmod truediv floordiv pow
inplace_div inplace_mod inplace_divmod inplace_truediv
inplace_floordiv inplace_pow""", ZeroDivisionError)
_add_exceptions("""pow inplace_pow lshift inplace_lshift rshift
inplace_rshift""", ValueError)
##_add_exceptions("""add sub mul truediv floordiv div mod divmod pow
## inplace_add inplace_sub inplace_mul inplace_truediv
## inplace_floordiv inplace_div inplace_mod inplace_divmod
## inplace_pow""", FloatingPointError)
_add_exceptions("""truediv divmod
inplace_add inplace_sub inplace_mul inplace_truediv
inplace_floordiv inplace_div inplace_mod inplace_pow
inplace_lshift""", OverflowError) # without a _ovf version
_add_except_ovf("""neg abs add sub mul
floordiv div mod pow lshift""") # with a _ovf version
_add_exceptions("""pow""",
OverflowError) # for the float case
del _add_exceptions, _add_except_ovf
def extract_cell_content(c):
"""Get the value contained in a CPython 'cell', as read through
the func_closure of a function object."""
# yuk! this is all I could come up with that works in Python 2.2 too
class X(object):
def __cmp__(self, other):
self.other = other
return 0
def __eq__(self, other):
self.other = other
return True
x = X()
x_cell, = (lambda: x).func_closure
x_cell == c
return x.other # crashes if the cell is actually empty
def make_op(name, symbol, arity, specialnames):
if hasattr(FlowObjSpace, name):
return # Shouldn't do it
import __builtin__
op = None
skip = False
arithmetic = False
if name.startswith('del') or name.startswith('set') or name.startswith('inplace_'):
# skip potential mutators
if debug: print "Skip", name
skip = True
elif name in ['id', 'hash', 'iter', 'userdel']:
# skip potential runtime context dependecies
if debug: print "Skip", name
skip = True
elif name in ['repr', 'str']:
rep = getattr(__builtin__, name)
def op(obj):
s = rep(obj)
if s.find("at 0x") > -1:
print >>sys.stderr, "Warning: captured address may be awkward"
return s
else:
op = FunctionByName[name]
arithmetic = (name + '_ovf') in FunctionByName
if not op:
if not skip:
if debug: print >> sys.stderr, "XXX missing operator:", name
else:
if debug: print "Can constant-fold operation: %s" % name
def generic_operator(self, *args_w):
assert len(args_w) == arity, name+" got the wrong number of arguments"
if op:
args = []
for w_arg in args_w:
try:
arg = self.unwrap_for_computation(w_arg)
except UnwrapException:
break
else:
args.append(arg)
else:
# All arguments are constants: call the operator now
#print >> sys.stderr, 'Constant operation', op
try:
result = op(*args)
except:
etype, evalue, etb = sys.exc_info()
msg = "generated by a constant operation: %s%r" % (
name, tuple(args))
raise flowcontext.OperationThatShouldNotBePropagatedError(
self.wrap(etype), self.wrap(msg))
else:
# don't try to constant-fold operations giving a 'long'
# result. The result is probably meant to be sent to
# an intmask(), but the 'long' constant confuses the
# annotator a lot.
if arithmetic and type(result) is long:
pass
else:
try:
return self.wrap(result)
except WrapException:
# type cannot sanely appear in flow graph,
# store operation with variable result instead
pass
#print >> sys.stderr, 'Variable operation', name, args_w
w_result = self.do_operation_with_implicit_exceptions(name, *args_w)
return w_result
setattr(FlowObjSpace, name, generic_operator)
for line in ObjSpace.MethodTable:
make_op(*line)
"""
This is just a placeholder for some code I'm checking in elsewhere.
It is provenly possible to determine constantness of certain expressions
a little later. I introduced this a bit too early, together with tieing
this to something being global, which was a bad idea.
The concept is still valid, and it can be used to force something to
be evaluated immediately because it is supposed to be a constant.
One good possible use of this is loop unrolling.
This will be found in an 'experimental' folder with some use cases.
"""
def override():
def getattr(self, w_obj, w_name):
# handling special things like sys
# unfortunately this will never vanish with a unique import logic :-(
if w_obj in self.not_really_const:
const_w = self.not_really_const[w_obj]
if w_name not in const_w:
return self.do_operation_with_implicit_exceptions('getattr', w_obj, w_name)
return self.regular_getattr(w_obj, w_name)
FlowObjSpace.regular_getattr = FlowObjSpace.getattr
FlowObjSpace.getattr = getattr
# protect us from globals write access
def setitem(self, w_obj, w_key, w_val):
ec = self.getexecutioncontext()
if not (ec and w_obj is ec.w_globals):
return self.regular_setitem(w_obj, w_key, w_val)
raise SyntaxError, "attempt to modify global attribute %r in %r" % (w_key, ec.graph.func)
FlowObjSpace.regular_setitem = FlowObjSpace.setitem
FlowObjSpace.setitem = setitem
override()
# ______________________________________________________________________
# End of objspace.py
| Python |
"""
This module defines mappings between operation names and Python's
built-in functions (or type constructors) implementing them.
"""
from pypy.interpreter.baseobjspace import ObjSpace
import operator, types, __future__
from pypy.tool.sourcetools import compile2
from pypy.rlib.rarithmetic import ovfcheck, ovfcheck_lshift
FunctionByName = {} # dict {"operation_name": <built-in function>}
OperationName = {} # dict {<built-in function>: "operation_name"}
Arity = {} # dict {"operation name": number of arguments}
# ____________________________________________________________
def new_style_type(x):
"""Simulate a situation where every class is new-style"""
t = getattr(x, '__class__', type(x))
if t is types.ClassType: # guess who's here? exception classes...
t = type
return t
def do_int(x):
return x.__int__()
def do_index(x):
return x.__index__()
def do_float(x):
return x.__float__()
def do_long(x):
return x.__long__()
def inplace_add(x, y):
x += y
return x
def inplace_sub(x, y):
x -= y
return x
def inplace_mul(x, y):
x *= y
return x
exec compile2("""
def inplace_truediv(x, y):
x /= y
return x
""", flags=__future__.CO_FUTURE_DIVISION, dont_inherit=1)
# makes an INPLACE_TRUE_DIVIDE
def inplace_floordiv(x, y):
x //= y
return x
exec compile2("""
def inplace_div(x, y):
x /= y
return x
""", flags=0, dont_inherit=1) # makes an INPLACE_DIVIDE
def inplace_mod(x, y):
x %= y
return x
def inplace_pow(x, y):
x **= y
return x
def inplace_lshift(x, y):
x <<= y
return x
def inplace_rshift(x, y):
x >>= y
return x
def inplace_and(x, y):
x &= y
return x
def inplace_or(x, y):
x |= y
return x
def inplace_xor(x, y):
x ^= y
return x
def next(x):
return x.next()
def get(x, y, z=None):
return x.__get__(y, z)
def set(x, y, z):
x.__set__(y, z)
def delete(x, y):
x.__delete__(y)
def userdel(x):
x.__del__()
def neg_ovf(x):
return ovfcheck(-x)
def abs_ovf(x):
return ovfcheck(abs(x))
def add_ovf(x, y):
return ovfcheck(x + y)
def sub_ovf(x, y):
return ovfcheck(x - y)
def mul_ovf(x, y):
return ovfcheck(x * y)
def floordiv_ovf(x, y):
return ovfcheck(operator.floordiv(x, y))
def div_ovf(x, y):
return ovfcheck(operator.div(x, y))
def mod_ovf(x, y):
return ovfcheck(x % y)
##def pow_ovf(*two_or_three_args):
## return ovfcheck(pow(*two_or_three_args))
def lshift_ovf(x, y):
return ovfcheck_lshift(x, y)
# ____________________________________________________________
# The following table can list several times the same operation name,
# if multiple built-in functions correspond to it. The first one should
# be picked, though, as the best built-in for the given operation name.
# Lines ('name', operator.name) are added automatically.
# INTERNAL ONLY, use the dicts declared at the top of the file.
Table = [
('id', id),
('type', new_style_type),
('type', type),
('issubtype', issubclass),
('repr', repr),
('str', str),
('len', len),
('hash', hash),
('getattr', getattr),
('setattr', setattr),
('delattr', delattr),
('nonzero', bool),
('nonzero', operator.truth),
('is_true', bool),
('is_true', operator.truth),
('abs' , abs),
('hex', hex),
('oct', oct),
('ord', ord),
('divmod', divmod),
('pow', pow),
('int', do_int),
('index', do_index),
('float', do_float),
('long', do_long),
('inplace_add', inplace_add),
('inplace_sub', inplace_sub),
('inplace_mul', inplace_mul),
('inplace_truediv', inplace_truediv),
('inplace_floordiv',inplace_floordiv),
('inplace_div', inplace_div),
('inplace_mod', inplace_mod),
('inplace_pow', inplace_pow),
('inplace_lshift', inplace_lshift),
('inplace_rshift', inplace_rshift),
('inplace_and', inplace_and),
('inplace_or', inplace_or),
('inplace_xor', inplace_xor),
('cmp', cmp),
('coerce', coerce),
('iter', iter),
('next', next),
('get', get),
('set', set),
('delete', delete),
('userdel', userdel),
# --- operations added by graph transformations ---
('neg_ovf', neg_ovf),
('abs_ovf', abs_ovf),
('add_ovf', add_ovf),
('sub_ovf', sub_ovf),
('mul_ovf', mul_ovf),
('floordiv_ovf', floordiv_ovf),
('div_ovf', div_ovf),
('mod_ovf', mod_ovf),
('lshift_ovf', lshift_ovf),
]
def setup():
if not hasattr(operator, 'is_'): # Python 2.2
Table.append(('is_', lambda x, y: x is y))
# insert all operators
for line in ObjSpace.MethodTable:
name = line[0]
if hasattr(operator, name):
Table.append((name, getattr(operator, name)))
# build the dictionaries
for name, func in Table:
if name not in FunctionByName:
FunctionByName[name] = func
if func not in OperationName:
OperationName[func] = name
# check that the result is complete
for line in ObjSpace.MethodTable:
name = line[0]
Arity[name] = line[2]
assert name in FunctionByName
setup()
del Table # INTERNAL ONLY, use the dicts declared at the top of the file
| Python |
from pypy.objspace.flow.objspace import FlowObjSpace
Space = FlowObjSpace
| Python |
# Empty
| Python |
from pypy.rpython.extregistry import ExtRegistryEntry, lookup_type
from pypy.interpreter.baseobjspace import W_Root, SpaceCache
from pypy.objspace.cpy.ctypes_base import W_Object
# ____________________________________________________________
# Hacks to support the app-level parts of MixedModules
class W_AppLevel(W_Root):
def __init__(self, space, app, name):
self.space = space
self.w_moddict = space.fromcache(AppSupportModuleCache).getorbuild(app)
self.name = name
def force(self):
dict = self.w_moddict.force()
return W_Object(dict[self.name])
class W_AppLevelModDict(W_Root):
def __init__(self, space, app):
self.space = space
self.app = app
self._dict = None
def force(self):
if self._dict is None:
import __builtin__
self._dict = {'__builtins__': __builtin__}
exec self.app.code in self._dict
return self._dict
class AppSupportModuleCache(SpaceCache):
def build(self, app):
return W_AppLevelModDict(self.space, app)
# ____________________________________________________________
class Entry(ExtRegistryEntry):
_type_ = W_AppLevel
def compute_annotation(self):
return lookup_type(W_Object).compute_annotation_bk(self.bookkeeper)
def genc_pyobj(self, pyobjmaker):
dictname = pyobjmaker.nameof(self.instance.w_moddict)
name = pyobjmaker.uniquename('gapp')
pyobjmaker.initcode_python(name, '%s[%r]' % (dictname,
self.instance.name))
return name
class Entry(ExtRegistryEntry):
_type_ = W_AppLevelModDict
def compute_annotation(self):
return lookup_type(W_Object).compute_annotation_bk(self.bookkeeper)
def genc_pyobj(self, pyobjmaker):
import marshal
app = self.instance.app
name = pyobjmaker.uniquename('gappmoddict_' + app.modname)
bytecodedump = marshal.dumps(app.code)
pyobjmaker.initcode.append("import marshal, __builtin__")
pyobjmaker.initcode.append("%s = {'__builtins__': __builtin__}" % (
name,))
pyobjmaker.initcode.append("co = marshal.loads(%s)" % (
pyobjmaker.nameof(bytecodedump),))
pyobjmaker.initcode.append("exec co in %s" % (
name))
return name
| Python |
from pypy.annotation import model as annmodel
from pypy.rpython.extregistry import ExtRegistryEntry
from pypy.objspace.cpy.capi import *
###################################################################
# ____________________ Reference counter hacks ____________________
_XX_PyObject_GetItem = pythonapi.PyObject_GetItem
_XX_PyObject_GetItem.argtypes = [W_Object, W_Object]
_XX_PyObject_GetItem.restype = None # !
_XX_PyList_SetItem = pythonapi.PyList_SetItem
_XX_PyList_SetItem.argtypes = [W_Object, Py_ssize_t, W_Object]
_XX_PyList_SetItem.restype = c_int
def Py_Incref(w):
container = (w.value,)
_XX_PyObject_GetItem(W_Object(container), W_Object(0))
# the new reference returned by PyObject_GetItem is ignored and lost
def Py_Decref(w):
lst = [None]
# consume a reference
_XX_PyList_SetItem(W_Object(lst), 0, w)
def Py_XIncref(w):
if w:
Py_Incref(w)
def Py_XDecref(w):
if w:
Py_Decref(w)
class IncrefFnEntry(ExtRegistryEntry):
"Annotation and specialization of calls to Py_Incref()."
_about_ = Py_Incref
def compute_result_annotation(self, s_arg):
return annmodel.s_None
def specialize_call(self, hop):
from pypy.rpython.lltypesystem import lltype
s_pyobj = annmodel.SomeCTypesObject(W_Object, ownsmemory=False)
r_pyobj = hop.rtyper.getrepr(s_pyobj)
[v_box] = hop.inputargs(r_pyobj)
v_value = r_pyobj.getvalue(hop.llops, v_box)
hop.genop('gc_push_alive_pyobj', [v_value])
return hop.inputconst(lltype.Void, None)
class DecrefFnEntry(ExtRegistryEntry):
"Annotation and specialization of calls to Py_Decref()."
_about_ = Py_Decref
def compute_result_annotation(self, s_arg):
return annmodel.s_None
def specialize_call(self, hop):
from pypy.rpython.lltypesystem import lltype
s_pyobj = annmodel.SomeCTypesObject(W_Object, ownsmemory=False)
r_pyobj = hop.rtyper.getrepr(s_pyobj)
[v_box] = hop.inputargs(r_pyobj)
v_value = r_pyobj.getvalue(hop.llops, v_box)
hop.genop('gc_pop_alive_pyobj', [v_value])
return hop.inputconst(lltype.Void, None)
| Python |
"""
Generic support to turn interpreter objects (subclasses of Wrappable)
into CPython objects (subclasses of W_Object) based on their typedef.
"""
from pypy.objspace.cpy.capi import *
from pypy.interpreter.error import OperationError
from pypy.interpreter.baseobjspace import Wrappable, SpaceCache
from pypy.interpreter.function import Function
from pypy.interpreter.typedef import GetSetProperty
from pypy.rlib.objectmodel import we_are_translated
from pypy.rpython.rcpy import CPyTypeInterface, cpy_export, cpy_import
from pypy.rpython.rcpy import cpy_typeobject, rpython_object, cpy_allocate
from pypy.rpython.rcpy import init_rpython_data, get_rpython_data
from pypy.rpython.lltypesystem import lltype
def rpython2cpython(space, x):
cache = space.fromcache(TypeDefCache)
typeintf = cache.getorbuild(x.typedef)
if we_are_translated():
obj = cpy_export(typeintf, x)
return W_Object(obj)
else:
w_x = x.__cpy_wrapper__
if w_x is None:
w_type = cache.wraptypeintf(x.__class__, typeintf)
w_x = W_Object(rpython_object.__new__(w_type.value))
init_rpython_data(w_x.value, x)
x.__cpy_wrapper__ = w_x
return w_x
rpython2cpython.allow_someobjects = True
rpython2cpython._annspecialcase_ = "specialize:argtype(1)"
def rpython2cpytype(space, Cls):
cache = space.fromcache(TypeDefCache)
typeintf = cache.getorbuild(Cls.typedef)
if we_are_translated():
cpytype = cpy_typeobject(typeintf, Cls)
return W_Object(cpytype)
else:
return cache.wraptypeintf(Cls, typeintf)
rpython2cpytype.allow_someobjects = True
rpython2cpytype._annspecialcase_ = "specialize:arg(1)"
def cpython2rpython_raw(space, w_obj):
"NOT_RPYTHON."
try:
w_obj, result, follow = space.wrap_cache[id(w_obj)]
except KeyError:
if isinstance(w_obj.value, rpython_object):
result = get_rpython_data(w_obj.value)
else:
result = None
return result
def cpython2rpython(space, RequiredClass, w_obj):
if we_are_translated():
cache = space.fromcache(TypeDefCache)
typeintf = cache.getorbuild(RequiredClass.typedef)
cpytype = cpy_typeobject(typeintf, RequiredClass)
w_cpytype = W_Object(cpytype)
if space.is_true(space.isinstance(w_obj, w_cpytype)):
x = w_obj.value
return cpy_import(RequiredClass, x)
else:
result = cpython2rpython_raw(space, w_obj)
if isinstance(result, RequiredClass):
return result
w_objtype = space.type(w_obj)
w_name = space.getattr(w_objtype, space.wrap('__name__'))
typename = space.str_w(w_name)
msg = "'%s' object expected, got '%s' instead" % (
RequiredClass.typedef.name, typename)
raise OperationError(space.w_TypeError, space.wrap(msg))
cpython2rpython._annspecialcase_ = 'specialize:arg(1)'
cpython2rpython.allow_someobjects = True
def cpython_allocate(cls, w_subtype):
return cpy_allocate(cls, w_subtype.value)
cpython_allocate._annspecialcase_ = 'specialize:arg(0)'
cpython_allocate.allow_someobjects = True
# ____________________________________________________________
class TypeDefCache(SpaceCache):
def __init__(self, space):
super(TypeDefCache, self).__init__(space)
self.wrappedtypes = {}
def build(cache, typedef):
if typedef in (Function.typedef, GetSetProperty.typedef):
raise ValueError("cannot wrap at run-time an interpreter object "
"of type %r" % (typedef.name,))
space = cache.space
objects = {}
for name, value in typedef.rawdict.items():
#if name.startswith('__') and name.endswith('__'):
# raise NotImplementedError("missing support for special "
# "attributes in TypeDef-to-CPython "
# "converter (%s.%s)" % (
# typedef.name, name))
w_value = space.wrap(value)
objects[name] = lltype.pyobjectptr(w_value.value)
typeintf = CPyTypeInterface(typedef.name, objects, typedef.acceptable_as_base_class)
return typeintf
def wraptypeintf(cache, cls, typeintf):
"NOT_RPYTHON. Not available after translation."
try:
return cache.wrappedtypes[cls]
except KeyError:
typedef = cls.typedef
space = cache.space
newtype = typeintf.emulate(cls)
w_result = W_Object(newtype)
space.wrap_cache[id(w_result)] = w_result, typedef, follow_annotations
cache.wrappedtypes[cls] = w_result
return w_result
def follow_annotations(bookkeeper, w_type):
pass
# hack!
Wrappable.__cpy_wrapper__ = None
| Python |
"""
Support to turn Function objects into W_Objects containing a built-in
function of CPython.
"""
import py
from pypy.objspace.cpy.capi import *
from pypy.objspace.cpy.refcount import Py_XIncref
from pypy.objspace.cpy.objspace import CPyObjSpace
from pypy.interpreter.error import OperationError
from pypy.interpreter.gateway import BuiltinCode, ObjSpace, W_Root
from pypy.interpreter.gateway import UnwrapSpecRecipe, Signature
from pypy.interpreter.baseobjspace import SpaceCache
from pypy.tool.sourcetools import func_with_new_name
class UnwrapSpec_Trampoline(UnwrapSpecRecipe):
def __init__(self, original_sig):
self.orig_arg = iter(original_sig.argnames).next
self.inputargs = []
self.wrappings = []
self.passedargs = []
self.miniglobals = {}
self.star_arg = False
def visit__ObjSpace(self, el):
argname = self.orig_arg()
assert argname == 'space'
self.passedargs.append('___space')
def visit__W_Root(self, el):
argname = self.orig_arg()
assert argname.startswith('w_')
basename = argname[2:]
self.inputargs.append(basename)
self.wrappings.append('%s = ___W_Object(%s)' % (argname, basename))
self.passedargs.append(argname)
def visit__Wrappable(self, el):
clsname = el.__name__ # XXX name clashes, but in gateway.py too
self.miniglobals[clsname] = el
argname = self.orig_arg()
assert not argname.startswith('w_')
self.inputargs.append(argname)
self.wrappings.append('%s = ___space.interp_w(%s, ___W_Object(%s))'
% (argname,
clsname,
argname))
self.passedargs.append(argname)
def visit__object(self, el):
convertermap = {int: 'int_w',
str: 'str_w',
float: 'float_w',
}
argname = self.orig_arg()
assert not argname.startswith('w_')
self.inputargs.append(argname)
self.wrappings.append('%s = ___space.%s(___W_Object(%s))' %
(argname,
convertermap[el],
argname))
self.passedargs.append(argname)
def visit_index(self, el):
argname = self.orig_arg()
assert not argname.startswith('w_')
self.inputargs.append(argname)
self.wrappings.append('%s = ___space.getindex_w(___W_Object(%s),'
' ___space.w_OverflowError)' %
(argname,
argname))
self.passedargs.append(argname)
def visit_args_w(self, el):
argname = self.orig_arg()
assert argname.endswith('_w')
basename = argname[:-2]
self.inputargs.append('*' + basename)
self.wrappings.append('%s = []' % (argname,))
self.wrappings.append('for ___i in range(len(%s)):' % (basename,))
self.wrappings.append(' %s.append(___W_Object(%s[___i]))' % (
argname, basename))
self.passedargs.append(argname)
self.star_arg = True
def reraise(e):
w_type = e.w_type
w_value = e.w_value
w_traceback = e.application_traceback
if e.application_traceback is None:
w_traceback = W_Object() # NULL
else:
Py_XIncref(w_traceback)
Py_XIncref(w_type)
Py_XIncref(w_value)
RAW_PyErr_Restore(e.w_type, e.w_value, w_traceback)
class FunctionCache(SpaceCache):
def build(cache, func):
space = cache.space
# make a built-in function
assert isinstance(func.code, BuiltinCode) # XXX
bltin = func.code._bltin
unwrap_spec = func.code._unwrap_spec
from pypy.interpreter import pycode
argnames, varargname, kwargname = pycode.cpython_code_signature(
bltin.func_code)
orig_sig = Signature(bltin, argnames, varargname, kwargname)
tramp = UnwrapSpec_Trampoline(orig_sig)
tramp.miniglobals = {
'___space': space,
'___W_Object': CPyObjSpace.W_Object,
'___bltin': bltin,
'___OperationError': OperationError,
'___reraise': reraise,
}
tramp.apply_over(unwrap_spec)
sourcelines = ['def trampoline(%s):' % (', '.join(tramp.inputargs),)]
# this description is to aid viewing in graphviewer
sourcelines.append(' "wrapper for fn: %s"' % func.name)
for line in tramp.wrappings:
sourcelines.append(' ' + line)
sourcelines.append(' try:')
sourcelines.append(' w_result = ___bltin(%s)' % (
', '.join(tramp.passedargs),))
sourcelines.append(' except ___OperationError, e:')
sourcelines.append(' ___reraise(e)')
# the following line is not reached, unless we are translated
# in which case it makes the function return (PyObject*)NULL.
sourcelines.append(' w_result = ___W_Object()')
sourcelines.append(' else:')
# # convert None to Py_None
sourcelines.append(' if w_result is None:')
sourcelines.append(' return None')
sourcelines.append(' return w_result.value')
sourcelines.append('')
miniglobals = tramp.miniglobals
exec py.code.Source('\n'.join(sourcelines)).compile() in miniglobals
trampoline = miniglobals['trampoline']
trampoline = func_with_new_name(trampoline, func.name)
trampoline.nb_args = len(tramp.inputargs)
trampoline.star_arg = tramp.star_arg
trampoline.allow_someobjects = True # annotator hint
trampoline._annspecialcase_ = "specialize:all_someobjects"
if func.defs_w:
trampoline.func_defaults = tuple([space.unwrap(w_x)
for w_x in func.defs_w])
w_result = W_Object(trampoline)
space.wrap_cache[id(w_result)] = w_result, func, follow_annotations
return w_result
def follow_annotations(bookkeeper, w_trampoline):
from pypy.annotation import model as annmodel
trampoline = w_trampoline.value
s_trampoline = bookkeeper.immutablevalue(trampoline)
args_s = [annmodel.SomeObject()] * trampoline.nb_args
if trampoline.star_arg:
args_s[-1] = Ellipsis # hack, see bookkeeper.RPythonCallsSpace
uniquekey = trampoline
bookkeeper.emulate_pbc_call(uniquekey, s_trampoline, args_s)
| Python |
"""
CTypes base classes to support the particularities of the CPyObjSpace
when it uses the CPython API: the W_Object class and the cpyapi accessor.
"""
import sys
from ctypes import *
from pypy.rpython.rctypes import apyobject
from pypy.interpreter.error import OperationError
from pypy.tool.sourcetools import func_with_new_name
class W_Object(py_object):
"""A py_object subclass, representing wrapped objects for the CPyObjSpace.
The reason we don't use py_object directly is that if py_object is
specified as the restype of a function, the function call unwraps it
automatically. With W_Object, however, the function call returns a
W_Object instance.
"""
def __repr__(self):
return 'W_Object(%r)' % (self.value,)
apyobject.register_py_object_subclass(W_Object)
class LevelError(Exception):
pass
def rctypes_pyerrchecker():
from pypy.objspace.cpy.capi import RAW_PyErr_Occurred, RAW_PyErr_Fetch
if RAW_PyErr_Occurred():
w_exc = W_Object()
w_val = W_Object()
w_tb = W_Object()
RAW_PyErr_Fetch(byref(w_exc), byref(w_val), byref(w_tb))
raise OperationError(w_exc, w_val, w_tb)
class CPyAPI(PyDLL):
"""Class of the singleton 'cpyapi' object, out of which C functions
are getattr'd. It returns C function whose exception behavior matches
the one required for the CPyObjSpace: exceptions are wrapped in
OperationErrors.
"""
class _FuncPtr(PyDLL._FuncPtr):
_flags_ = PyDLL._FuncPtr._flags_
_rctypes_pyerrchecker_ = staticmethod(rctypes_pyerrchecker)
def __call__(*args, **kwds):
try:
return PyDLL._FuncPtr.__call__(*args, **kwds)
except OperationError, e:
raise LevelError, "unexpected OperationError: %r" % (e,)
except:
exc, val, tb = sys.exc_info()
raise OperationError(W_Object(exc),
W_Object(val),
W_Object(tb))
cpyapi = CPyAPI.__new__(CPyAPI)
cpyapi.__dict__ = pythonapi.__dict__.copy()
| Python |
import types, sys
from pypy.objspace.cpy.capi import *
from pypy.objspace.cpy.capi import _PyType_Lookup
from pypy.objspace.cpy.capi import _PyLong_Sign, _PyLong_NumBits, _PyLong_AsByteArray
from pypy.objspace.cpy.refcount import Py_Incref
from pypy.objspace.cpy.appsupport import W_AppLevel
from pypy.interpreter import baseobjspace
from pypy.interpreter.error import OperationError
from pypy.interpreter.function import Function
from pypy.interpreter.typedef import GetSetProperty
from pypy.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong
from pypy.rlib.rbigint import rbigint
from pypy.rlib.objectmodel import we_are_translated, instantiate
class CPyObjSpace(baseobjspace.ObjSpace):
from pypy.objspace.cpy.ctypes_base import W_Object
w_None = W_Object(None)
w_False = W_Object(False)
w_True = W_Object(True)
w_Ellipsis = W_Object(Ellipsis)
w_NotImplemented = W_Object(NotImplemented)
w_int = W_Object(int)
w_float = W_Object(float)
w_long = W_Object(long)
w_tuple = W_Object(tuple)
w_str = W_Object(str)
w_unicode = W_Object(unicode)
w_type = W_Object(type)
w_instance = W_Object(types.InstanceType)
w_slice = W_Object(slice)
w_hex = W_Object(hex) # no C API function to do that :-(
w_oct = W_Object(oct)
def initialize(self):
self.config.objspace.geninterp = False
self.wrap_cache = {}
def _freeze_(self):
return True
def getbuiltinmodule(self, name):
return PyImport_ImportModule(name)
def gettypefor(self, Cls):
from pypy.objspace.cpy.typedef import rpython2cpytype
return rpython2cpytype(self, Cls)
gettypefor._annspecialcase_ = 'specialize:arg(1)'
def wrap(self, x):
if isinstance(x, baseobjspace.Wrappable):
# special cases, only when bootstrapping
if not we_are_translated():
x = x.__spacebind__(self)
if isinstance(x, Function):
from pypy.objspace.cpy.function import FunctionCache
return self.fromcache(FunctionCache).getorbuild(x)
if isinstance(x, GetSetProperty):
from pypy.objspace.cpy.property import PropertyCache
return self.fromcache(PropertyCache).getorbuild(x)
# normal case
from pypy.objspace.cpy.typedef import rpython2cpython
return rpython2cpython(self, x)
if x is None:
return self.w_None
if isinstance(x, int):
return PyInt_FromLong(x)
if isinstance(x, str):
return PyString_FromStringAndSize(x, len(x))
if isinstance(x, float):
return PyFloat_FromDouble(x)
if isinstance(x, r_uint):
return PyLong_FromUnsignedLong(x)
if isinstance(x, r_longlong):
return PyLong_FromLongLong(x)
if isinstance(x, r_ulonglong):
return PyLong_FromUnsignedLongLong(x)
# if we arrive here during RTyping, then the problem is *not* the %r
# in the format string, but it's that someone is calling space.wrap()
# on a strange object.
raise TypeError("wrap(%r)" % (x,))
wrap._annspecialcase_ = "specialize:argtype(1)"
def unwrap(self, w_obj):
assert isinstance(w_obj, W_Object)
return w_obj.value
def interpclass_w(self, w_obj):
"NOT_RPYTHON."
if isinstance(w_obj, W_AppLevel):
return None # XXX
from pypy.objspace.cpy.typedef import cpython2rpython_raw
return cpython2rpython_raw(self, w_obj)
def interp_w(self, RequiredClass, w_obj, can_be_None=False):
"""
Unwrap w_obj, checking that it is an instance of the required internal
interpreter class (a subclass of Wrappable).
"""
if can_be_None and self.is_w(w_obj, self.w_None):
return None
from pypy.objspace.cpy.typedef import cpython2rpython
return cpython2rpython(self, RequiredClass, w_obj)
interp_w._annspecialcase_ = 'specialize:arg(1)'
def descr_self_interp_w(self, RequiredClass, w_obj):
return self.interp_w(RequiredClass, w_obj)
descr_self_interp_w._annspecialcase_ = 'specialize:arg(1)'
def lookup(self, w_obj, name):
w_type = self.type(w_obj)
w_name = self.wrap(name)
w_res = _PyType_Lookup(w_type, w_name)
if w_res:
Py_Incref(w_res)
return w_res
else:
return None
def allocate_instance(self, cls, w_subtype):
if we_are_translated():
from pypy.objspace.cpy.typedef import cpython_allocate
obj = cpython_allocate(cls, w_subtype)
else:
assert self.is_w(self.gettypefor(cls), w_subtype)
obj = object.__new__(cls)
return self.wrap(obj)
# __________ operations with a direct CPython equivalent __________
getattr = staticmethod(PyObject_GetAttr)
setattr = staticmethod(PyObject_SetAttr)
getitem = staticmethod(PyObject_GetItem)
setitem = staticmethod(PyObject_SetItem)
delitem = staticmethod(PyObject_DelItem)
int_w = staticmethod(PyInt_AsLong)
uint_w = staticmethod(PyInt_AsUnsignedLongMask)
float_w = staticmethod(PyFloat_AsDouble)
iter = staticmethod(PyObject_GetIter)
type = staticmethod(PyObject_Type)
str = staticmethod(PyObject_Str)
repr = staticmethod(PyObject_Repr)
id = staticmethod(PyLong_FromVoidPtr_PYOBJ)
def index(self, w_obj):
# XXX we do not support 2.5 yet, so we just do some
# hack here to have index working
return self.wrap(self.int_w(w_obj))
def getindex_w(self, w_obj, w_exception, objdescr=None):
# XXX mess with type(w_obj).getname() in the baseobjspace,
# XXX give a simplified naive version
w_index = w_obj
try:
index = self.int_w(w_index)
except OperationError, err:
if not err.match(self, self.w_OverflowError):
raise
if not w_exception:
# w_index should be a long object, but can't be sure of that
if self.is_true(self.lt(w_index, self.wrap(0))):
return -sys.maxint-1
else:
return sys.maxint
else:
raise OperationError(
w_exception, self.wrap(
"cannot fit number into an index-sized integer"))
else:
return index
def bigint_w(self, w_obj):
if self.is_true(self.isinstance(w_obj, self.w_long)):
sign = _PyLong_Sign(w_obj)
#XXX Can throw exception if long larger than size_t bits
numbits = _PyLong_NumBits(w_obj)
numbytes = (numbits+1) / 8 # +1 sign bit cpython always adds
if (numbits+1) % 8 != 0:
numbytes += 1
ByteArray = c_ubyte * numbytes
cbytes = ByteArray()
_PyLong_AsByteArray(w_obj, cbytes, numbytes, 1, 1) # little endian, signed
rdigits = _cpylongarray_to_bigintarray(cbytes, numbytes, numbits, sign)
return rbigint(rdigits, sign)
elif self.is_true(self.isinstance(w_obj, self.w_int)):
value = self.int_w(w_obj)
return rbigint.fromint(value)
else:
raise OperationError(self.w_TypeError, self.wrap("Expected type int or long"))
def len(self, w_obj):
return self.wrap(PyObject_Size(w_obj))
def str_w(self, w_obj):
# XXX inefficient
p = PyString_AsString(w_obj)
length = PyString_Size(w_obj)
buf = create_string_buffer(length)
for i in range(length):
buf[i] = p[i]
return buf.raw
def unichars_w(self, w_obj):
not_implemented_sorry
def call_function(self, w_callable, *args_w):
args_w += (None,)
return PyObject_CallFunctionObjArgs(w_callable, *args_w)
def call_args(self, w_callable, args):
args_w, kwds_w = args.unpack()
w_args = self.newtuple(args_w)
w_kwds = self.newdict()
for key, w_value in kwds_w.items():
w_key = self.wrap(key)
PyDict_SetItem(w_kwds, w_key, w_value)
return PyObject_Call(w_callable, w_args, w_kwds)
def new_interned_str(self, s):
w_s = self.wrap(s)
PyString_InternInPlace(byref(w_s))
return w_s
def newstring(self, bytes_w):
length = len(bytes_w)
buf = ctypes.create_string_buffer(length)
for i in range(length):
buf[i] = chr(self.int_w(bytes_w[i]))
return PyString_FromStringAndSize(buf, length)
def newunicode(self, codes):
# XXX inefficient
lst = [PyUnicode_FromOrdinal(ord(code)) for code in codes]
w_lst = self.newlist(lst)
w_emptyunicode = PyUnicode_FromUnicode(None, 0)
return self.call_method(w_emptyunicode, 'join', w_lst)
def newint(self, intval):
return PyInt_FromLong(intval)
def newlong(self, intval):
return PyLong_FromLong(intval)
def newfloat(self, floatval):
return PyFloat_FromDouble(floatval)
def newdict(self, track_builtin_shadowing=False):
return PyDict_New()
def newlist(self, items_w):
n = len(items_w)
w_list = PyList_New(n)
for i in range(n):
w_item = items_w[i]
Py_Incref(w_item)
PyList_SetItem(w_list, i, w_item)
return w_list
def emptylist(self):
return PyList_New(0)
def newtuple(self, items_w):
# XXX not very efficient, but PyTuple_SetItem complains if the
# refcount of the tuple is not exactly 1
w_list = self.newlist(items_w)
return PySequence_Tuple(w_list)
newslice = staticmethod(PySlice_New)
def lt(self, w1, w2): return PyObject_RichCompare(w1, w2, Py_LT)
def le(self, w1, w2): return PyObject_RichCompare(w1, w2, Py_LE)
def eq(self, w1, w2): return PyObject_RichCompare(w1, w2, Py_EQ)
def ne(self, w1, w2): return PyObject_RichCompare(w1, w2, Py_NE)
def gt(self, w1, w2): return PyObject_RichCompare(w1, w2, Py_GT)
def ge(self, w1, w2): return PyObject_RichCompare(w1, w2, Py_GE)
def lt_w(self, w1, w2): return PyObject_RichCompareBool(w1, w2, Py_LT) != 0
def le_w(self, w1, w2): return PyObject_RichCompareBool(w1, w2, Py_LE) != 0
def eq_w(self, w1, w2): return PyObject_RichCompareBool(w1, w2, Py_EQ) != 0
def ne_w(self, w1, w2): return PyObject_RichCompareBool(w1, w2, Py_NE) != 0
def gt_w(self, w1, w2): return PyObject_RichCompareBool(w1, w2, Py_GT) != 0
def ge_w(self, w1, w2): return PyObject_RichCompareBool(w1, w2, Py_GE) != 0
def is_w(self, w1, w2):
return w1.value is w2.value # XXX any idea not involving SomeObjects?
is_w.allow_someobjects = True
def is_(self, w1, w2):
return self.newbool(self.is_w(w1, w2))
def next(self, w_obj):
w_res = PyIter_Next(w_obj)
if not w_res:
raise OperationError(self.w_StopIteration, self.w_None)
return w_res
def is_true(self, w_obj):
return PyObject_IsTrue(w_obj) != 0
def nonzero(self, w_obj):
return self.newbool(PyObject_IsTrue(w_obj))
def issubtype(self, w_type1, w_type2):
if PyType_IsSubtype(w_type1, w_type2):
return self.w_True
else:
return self.w_False
def ord(self, w_obj):
w_type = self.type(w_obj)
if self.is_true(self.issubtype(w_type, self.w_str)):
length = PyObject_Size(w_obj)
if length == 1:
s = self.str_w(w_obj)
return self.wrap(ord(s[0]))
errtype = 'string of length %d' % length
elif self.is_true(self.issubtype(w_type, self.w_unicode)):
length = PyObject_Size(w_obj)
if length == 1:
p = PyUnicode_AsUnicode(w_obj)
return self.wrap(p[0])
errtype = 'unicode string of length %d' % length
else:
errtype = self.str_w(self.getattr(w_type, self.wrap('__name__')))
msg = 'expected a character, but %s found' % errtype
raise OperationError(self.w_TypeError, self.wrap(msg))
def hash(self, w_obj):
return self.wrap(PyObject_Hash(w_obj))
def delattr(self, w_obj, w_attr):
PyObject_SetAttr(w_obj, w_attr, W_Object())
def contains(self, w_obj, w_item):
return self.newbool(PySequence_Contains(w_obj, w_item))
def hex(self, w_obj):
return self.call_function(self.w_hex, w_obj)
def oct(self, w_obj):
return self.call_function(self.w_oct, w_obj)
def pow(self, w_x, w_y, w_z=None):
if w_z is None:
w_z = self.w_None
return PyNumber_Power(w_x, w_y, w_z)
def inplace_pow(self, w_x, w_y, w_z=None):
if w_z is None:
w_z = self.w_None
return PyNumber_InPlacePower(w_x, w_y, w_z)
def cmp(self, w_x, w_y):
return self.wrap(PyObject_Compare(w_x, w_y))
# XXX missing operations
def coerce(self, *args): raise NotImplementedError("space.coerce()")
def get(self, *args): raise NotImplementedError("space.get()")
def set(self, *args): raise NotImplementedError("space.set()")
def delete(self, *args): raise NotImplementedError("space.delete()")
def userdel(self, *args): raise NotImplementedError("space.userdel()")
def marshal_w(self, *args):raise NotImplementedError("space.marshal_w()")
def exec_(self, statement, w_globals, w_locals, hidden_applevel=False):
"NOT_RPYTHON"
raise NotImplementedError("space.exec_")
#from types import CodeType
#if not isinstance(statement, (str, CodeType)):
# raise TypeError("CPyObjSpace.exec_(): only for CPython code objs")
#exec statement in w_globals.value, w_locals.value
def _applevelclass_hook(self, app, name):
# hackish hook for gateway.py: in a MixedModule, all init-time gets
# from app-level files should arrive here
w_res = W_AppLevel(self, app, name)
if not self.config.translating:
# e.g. when using pypy.interpreter.mixedmodule.testmodule(),
# we can force the object immediately
w_res = w_res.force()
return w_res
def _cpylongarray_to_bigintarray(cbytes, numbytes, numbits, sign):
"""
helper function to convert an array of bytes from a cpython long to
the 15 bit digits needed by the rbigint implementation.
"""
# convert from 2's complement to unsigned
if sign == -1:
add = 1
for i in xrange(numbytes):
cbytes[i] = (cbytes[i] ^ 0xFF) + add
if add and cbytes[i] != 0:
add = 0
elif add and cbytes[i] == 0:
cbytes[i] == 0xFF
# convert 8 bit digits from cpython into 15 bit digits for rbigint
rdigits = []
digitbits = 0
usedbits = r_uint(0) # XXX: Will break on platforms where size_t > uint
digit = 0
for i in xrange(numbytes):
cdigit = cbytes[i]
digit |= (cdigit << digitbits)
digitbits += 8
usedbits += 8
if digitbits >= 15: # XXX: 15 should be the same as rbigint.SHIFT
rdigits.append(digit & 0x7FFF) # need to mask off rbigint.SHIFT bits
digit = 0
digitbits = digitbits-15
usedbits -= digitbits
if digitbits > 0 and usedbits < numbits:
digit = cdigit >> (8-digitbits)
usedbits += digitbits
else:
# digitbits is either zero or we have used all the bits
# set it to zero so we don't append an extra rpython digit
digitbits = 0
if digitbits != 0:
rdigits.append(digit)
return rdigits
# Register add, sub, neg, etc...
for _name, _cname in UnaryOps.items() + BinaryOps.items():
setattr(CPyObjSpace, _name, staticmethod(globals()[_cname]))
# Register all exceptions
import exceptions
for name in baseobjspace.ObjSpace.ExceptionTable:
exc = getattr(exceptions, name)
setattr(CPyObjSpace, 'w_' + name, W_Object(exc))
| Python |
from pypy.translator.goal.ann_override import PyPyAnnotatorPolicy
from pypy.annotation import model as annmodel
from pypy.interpreter.error import OperationError
from pypy.objspace.cpy.ctypes_base import W_Object, rctypes_pyerrchecker
class CPyAnnotatorPolicy(PyPyAnnotatorPolicy):
"""Annotation policy to compile CPython extension modules with
the CPyObjSpace.
"""
def __init__(self, space):
PyPyAnnotatorPolicy.__init__(self, single_space=space)
def no_more_blocks_to_annotate(self, annotator):
PyPyAnnotatorPolicy.no_more_blocks_to_annotate(self, annotator)
# annotate all indirectly reachable call-back functions
space = self.single_space
pending = {}
while True:
nb_done = len(pending)
pending.update(space.wrap_cache)
if len(pending) == nb_done:
break
for w_obj, obj, follow in pending.values():
follow(annotator.bookkeeper, w_obj)
# restart this loop: for all we know follow_annotations()
# could have found new objects
# force w_type/w_value/w_traceback attrs into the OperationError class
bk = annotator.bookkeeper
classdef = bk.getuniqueclassdef(OperationError)
s_instance = annmodel.SomeInstance(classdef=classdef)
for name in ['w_type', 'w_value', 'w_traceback']:
s_instance.setattr(bk.immutablevalue(name),
bk.valueoftype(W_Object))
# annotate rctypes_pyerrchecker()
uniquekey = rctypes_pyerrchecker
s_pyerrchecker = bk.immutablevalue(rctypes_pyerrchecker)
s_result = bk.emulate_pbc_call(uniquekey, s_pyerrchecker, [])
assert annmodel.s_None.contains(s_result)
def specialize__all_someobjects(self, funcdesc, args_s):
return funcdesc.cachedgraph(None)
| Python |
"""
Support to turn GetSetProperty objects into W_Objects containing a
property object of CPython.
"""
from pypy.interpreter.baseobjspace import SpaceCache
from pypy.interpreter.gateway import ObjSpace, W_Root, interp2app
from pypy.interpreter.function import BuiltinFunction
from pypy.objspace.cpy.objspace import W_Object
class PropertyCache(SpaceCache):
def build(cache, prop):
space = cache.space
reslist = []
for f, arity in [(prop.fget, 1),
(prop.fset, 2),
(prop.fdel, 1)]:
if f is None:
res = None
else:
unwrap_spec = [ObjSpace] + [W_Root]*arity
func = interp2app(f, unwrap_spec=unwrap_spec)
func = func.__spacebind__(space)
bltin = BuiltinFunction(func)
res = space.wrap(bltin).value
reslist.append(res)
# make a CPython property
p = property(reslist[0], reslist[1], reslist[2], prop.doc)
w_result = W_Object(p)
space.wrap_cache[id(w_result)] = w_result, p, follow_annotations
return w_result
def follow_annotations(bookkeeper, w_property):
from pypy.annotation import model as annmodel
p = w_property.value
for f, arity, key in [(p.fget, 1, 'get'),
(p.fset, 2, 'set'),
(p.fdel, 1, 'del')]:
if f is not None:
s_func = bookkeeper.immutablevalue(f)
args_s = [annmodel.SomeObject()] * arity
uniquekey = p, key
bookkeeper.emulate_pbc_call(uniquekey, s_func, args_s)
| Python |
try:
import ctypes as _
except ImportError:
CPyObjSpace = None
else:
from objspace import CPyObjSpace
Space = CPyObjSpace
| Python |
"""
CTypes declarations for the CPython API.
"""
import sys
import ctypes
import py
from ctypes import *
from pypy.rpython.rctypes.tool import ctypes_platform
##from pypy.rpython.rctypes.implementation import CALLBACK_FUNCTYPE
from pypy.objspace.cpy.ctypes_base import W_Object, cpyapi
###############################################################
# ____________________ Types and constants ____________________
##PyCFunction = CALLBACK_FUNCTYPE(W_Object, W_Object, W_Object, callconv=PyDLL)
##PyNoArgsFunction = CALLBACK_FUNCTYPE(W_Object, W_Object, callconv=PyDLL)
##PyCFunctionWithKeywords = CALLBACK_FUNCTYPE(W_Object,
## W_Object, W_Object, W_Object,
## callconv=PyDLL)
class CConfig:
_header_ = """
#include <Python.h>
#if PY_VERSION_HEX < 0x02050000 /* < 2.5 */
typedef int Py_ssize_t;
#endif
"""
_include_dirs_ = [ctypes_platform.get_python_include_dir()]
Py_ssize_t = ctypes_platform.SimpleType('Py_ssize_t')
Py_UNICODE = ctypes_platform.SimpleType('Py_UNICODE')
Py_UNICODE_WIDE = ctypes_platform.Defined('Py_UNICODE_WIDE')
Py_LT = ctypes_platform.ConstantInteger('Py_LT')
Py_LE = ctypes_platform.ConstantInteger('Py_LE')
Py_EQ = ctypes_platform.ConstantInteger('Py_EQ')
Py_NE = ctypes_platform.ConstantInteger('Py_NE')
Py_GT = ctypes_platform.ConstantInteger('Py_GT')
Py_GE = ctypes_platform.ConstantInteger('Py_GE')
## PyMethodDef = ctypes_platform.Struct('PyMethodDef',
## [('ml_name', c_char_p),
## ('ml_meth', PyCFunction),
## ('ml_flags', c_int),
## ('ml_doc', c_char_p)])
## METH_VARARGS = ctypes_platform.ConstantInteger('METH_VARARGS')
## # NB. all integers fields can be specified as c_int,
## # which is replaced by the more precise type automatically.
## PyObject_HEAD = [('ob_refcnt', c_int), ('ob_type',
## PyTypeObject = ctypes_platform.Struct('PyTypeObject', [
## ('tp_name', c_char_p),
## ('tp_basicsize', c_int),
## ('tp_flags', c_int),
## ('tp_doc', c_char_p),
## ])
## Py_TPFLAGS_DEFAULT = ctypes_platform.ConstantInteger('Py_TPFLAGS_DEFAULT')
globals().update(ctypes_platform.configure(CConfig))
del CConfig
###########################################################
# ____________________ Object Protocol ____________________
PyObject_Size = cpyapi.PyObject_Size
PyObject_Size.argtypes = [W_Object]
PyObject_Size.restype = Py_ssize_t
PyObject_GetAttr = cpyapi.PyObject_GetAttr
PyObject_GetAttr.argtypes = [W_Object, W_Object]
PyObject_GetAttr.restype = W_Object
PyObject_SetAttr = cpyapi.PyObject_SetAttr
PyObject_SetAttr.argtypes = [W_Object, W_Object, W_Object]
PyObject_SetAttr.restype = c_int
PyObject_GetItem = cpyapi.PyObject_GetItem
PyObject_GetItem.argtypes = [W_Object, W_Object]
PyObject_GetItem.restype = W_Object
PyObject_SetItem = cpyapi.PyObject_SetItem
PyObject_SetItem.argtypes = [W_Object, W_Object, W_Object]
PyObject_SetItem.restype = c_int
PyObject_DelItem = cpyapi.PyObject_DelItem
PyObject_DelItem.argtypes = [W_Object, W_Object]
PyObject_DelItem.restype = c_int
PyObject_Call = cpyapi.PyObject_Call
PyObject_Call.argtypes = [W_Object, W_Object, W_Object]
PyObject_Call.restype = W_Object
PyObject_CallFunctionObjArgs = cpyapi.PyObject_CallFunctionObjArgs
PyObject_CallFunctionObjArgs.restype = W_Object
#PyObject_CallFunctionObjArgs.argtypes = [W_Object, ..., final NULL]
PyObject_RichCompare = cpyapi.PyObject_RichCompare
PyObject_RichCompare.argtypes = [W_Object, W_Object, c_int]
PyObject_RichCompare.restype = W_Object
PyObject_RichCompareBool = cpyapi.PyObject_RichCompareBool
PyObject_RichCompareBool.argtypes = [W_Object, W_Object, c_int]
PyObject_RichCompareBool.restype = c_int
PyObject_Compare = cpyapi.PyObject_Compare
PyObject_Compare.argtypes = [W_Object, W_Object]
PyObject_Compare.restype = c_int
PyObject_GetIter = cpyapi.PyObject_GetIter
PyObject_GetIter.argtypes = [W_Object]
PyObject_GetIter.restype = W_Object
PyIter_Next = cpyapi.PyIter_Next
PyIter_Next.argtypes = [W_Object]
PyIter_Next.restype = W_Object
PyObject_IsTrue = cpyapi.PyObject_IsTrue
PyObject_IsTrue.argtypes = [W_Object]
PyObject_IsTrue.restype = c_int
PyObject_Type = cpyapi.PyObject_Type
PyObject_Type.argtypes = [W_Object]
PyObject_Type.restype = W_Object
PyObject_Str = cpyapi.PyObject_Str
PyObject_Str.argtypes = [W_Object]
PyObject_Str.restype = W_Object
PyObject_Repr = cpyapi.PyObject_Repr
PyObject_Repr.argtypes = [W_Object]
PyObject_Repr.restype = W_Object
PyObject_Hash = cpyapi.PyObject_Hash
PyObject_Hash.argtypes = [W_Object]
PyObject_Hash.restype = c_long
###########################################################
# ____________________ Number Protocol ____________________
UnaryOps = {'pos': 'PyNumber_Positive',
'neg': 'PyNumber_Negative',
'abs': 'PyNumber_Absolute',
'invert': 'PyNumber_Invert',
'int': 'PyNumber_Int',
'long': 'PyNumber_Long',
'float': 'PyNumber_Float',
}
BinaryOps = {'add': 'PyNumber_Add',
'sub': 'PyNumber_Subtract',
'mul': 'PyNumber_Multiply',
'truediv': 'PyNumber_TrueDivide',
'floordiv': 'PyNumber_FloorDivide',
'div': 'PyNumber_Divide',
'mod': 'PyNumber_Remainder',
'divmod': 'PyNumber_Divmod',
'lshift': 'PyNumber_Lshift',
'rshift': 'PyNumber_Rshift',
'and_': 'PyNumber_And',
'or_': 'PyNumber_Or',
'xor': 'PyNumber_Xor',
'inplace_add': 'PyNumber_InPlaceAdd',
'inplace_sub': 'PyNumber_InPlaceSubtract',
'inplace_mul': 'PyNumber_InPlaceMultiply',
'inplace_truediv': 'PyNumber_InPlaceTrueDivide',
'inplace_floordiv': 'PyNumber_InPlaceFloorDivide',
'inplace_div': 'PyNumber_InPlaceDivide',
'inplace_mod': 'PyNumber_InPlaceRemainder',
'inplace_lshift': 'PyNumber_InPlaceLshift',
'inplace_rshift': 'PyNumber_InPlaceRshift',
'inplace_and': 'PyNumber_InPlaceAnd',
'inplace_or': 'PyNumber_InPlaceOr',
'inplace_xor': 'PyNumber_InPlaceXor',
}
for name in UnaryOps.values():
exec py.code.Source("""
%(name)s = cpyapi.%(name)s
%(name)s.argtypes = [W_Object]
%(name)s.restype = W_Object
""" % locals()).compile()
for name in BinaryOps.values():
exec py.code.Source("""
%(name)s = cpyapi.%(name)s
%(name)s.argtypes = [W_Object, W_Object]
%(name)s.restype = W_Object
""" % locals()).compile()
del name
PyNumber_Power = cpyapi.PyNumber_Power
PyNumber_Power.argtypes = [W_Object, W_Object, W_Object]
PyNumber_Power.restype = W_Object
PyNumber_InPlacePower = cpyapi.PyNumber_InPlacePower
PyNumber_InPlacePower.argtypes = [W_Object, W_Object, W_Object]
PyNumber_InPlacePower.restype = W_Object
#############################################################
# ____________________ Sequence Protocol ____________________
PySequence_Tuple = cpyapi.PySequence_Tuple
PySequence_Tuple.argtypes = [W_Object]
PySequence_Tuple.restype = W_Object
PySequence_SetItem = cpyapi.PySequence_SetItem
PySequence_SetItem.argtypes = [W_Object, Py_ssize_t, W_Object]
PySequence_SetItem.restype = c_int
PySequence_Contains = cpyapi.PySequence_Contains
PySequence_Contains.argtypes = [W_Object, W_Object]
PySequence_Contains.restype = c_int
########################################################
# ____________________ Type Objects ____________________
PyType_IsSubtype = cpyapi.PyType_IsSubtype
PyType_IsSubtype.argtypes = [W_Object, W_Object]
PyType_IsSubtype.restype = c_int
_PyType_Lookup = cpyapi._PyType_Lookup
_PyType_Lookup.argtypes = [W_Object, W_Object]
_PyType_Lookup.restype = W_Object
###########################################################
# ____________________ Numeric Objects ____________________
PyInt_FromLong = cpyapi.PyInt_FromLong
PyInt_FromLong.argtypes = [c_long]
PyInt_FromLong.restype = W_Object
PyInt_AsLong = cpyapi.PyInt_AsLong
PyInt_AsLong.argtypes = [W_Object]
PyInt_AsLong.restype = c_long
PyInt_AsUnsignedLongMask = cpyapi.PyInt_AsUnsignedLongMask
PyInt_AsUnsignedLongMask.argtypes = [W_Object]
PyInt_AsUnsignedLongMask.restype = c_ulong
PyFloat_FromDouble = cpyapi.PyFloat_FromDouble
PyFloat_FromDouble.argtypes = [c_double]
PyFloat_FromDouble.restype = W_Object
PyFloat_AsDouble = cpyapi.PyFloat_AsDouble
PyFloat_AsDouble.argtypes = [W_Object]
PyFloat_AsDouble.restype = c_double
PyLong_FromLong = cpyapi.PyLong_FromLong
PyLong_FromLong.argtypes = [c_long]
PyLong_FromLong.restype = W_Object
PyLong_FromUnsignedLong = cpyapi.PyLong_FromUnsignedLong
PyLong_FromUnsignedLong.argtypes = [c_ulong]
PyLong_FromUnsignedLong.restype = W_Object
PyLong_FromLongLong = cpyapi.PyLong_FromLongLong
PyLong_FromLongLong.argtypes = [c_longlong]
PyLong_FromLongLong.restype = W_Object
PyLong_FromUnsignedLongLong = cpyapi.PyLong_FromUnsignedLongLong
PyLong_FromUnsignedLongLong.argtypes = [c_ulonglong]
PyLong_FromUnsignedLongLong.restype = W_Object
_PyLong_Sign = cpyapi._PyLong_Sign
_PyLong_Sign.argtypes = [W_Object]
_PyLong_Sign.restype = c_long
_PyLong_NumBits = cpyapi._PyLong_NumBits
_PyLong_NumBits.argtypes = [W_Object]
_PyLong_NumBits.restype = c_size_t
_PyLong_AsByteArray = cpyapi._PyLong_AsByteArray
_PyLong_AsByteArray.argtypes = [W_Object, POINTER(c_ubyte), c_size_t,
c_long, c_long]
_PyLong_AsByteArray.restype = c_long
# a version of PyLong_FromVoidPtr() that pretends to take a PyObject* arg
PyLong_FromVoidPtr_PYOBJ = cpyapi.PyLong_FromVoidPtr
PyLong_FromVoidPtr_PYOBJ.argtypes = [W_Object]
PyLong_FromVoidPtr_PYOBJ.restype = W_Object
###################################################
# ____________________ Strings ____________________
PyString_FromStringAndSize = cpyapi.PyString_FromStringAndSize
PyString_FromStringAndSize.argtypes = [c_char_p, Py_ssize_t]
PyString_FromStringAndSize.restype = W_Object
PyString_InternInPlace = cpyapi.PyString_InternInPlace
PyString_InternInPlace.argtypes = [POINTER(W_Object)]
PyString_InternInPlace.restype = None
PyString_AsString = cpyapi.PyString_AsString
PyString_AsString.argtypes = [W_Object]
PyString_AsString.restype = POINTER(c_char)
PyString_Size = cpyapi.PyString_Size
PyString_Size.argtypes = [W_Object]
PyString_Size.restype = Py_ssize_t
if Py_UNICODE_WIDE: PyUnicode_AsUnicode = cpyapi.PyUnicodeUCS4_AsUnicode
else: PyUnicode_AsUnicode = cpyapi.PyUnicodeUCS2_AsUnicode
PyUnicode_AsUnicode.argtypes = [W_Object]
PyUnicode_AsUnicode.restype = POINTER(Py_UNICODE)
if Py_UNICODE_WIDE: PyUnicode_FromUnicode = cpyapi.PyUnicodeUCS4_FromUnicode
else: PyUnicode_FromUnicode = cpyapi.PyUnicodeUCS2_FromUnicode
PyUnicode_FromUnicode.argtypes = [POINTER(Py_UNICODE), Py_ssize_t]
PyUnicode_FromUnicode.restype = W_Object
if Py_UNICODE_WIDE: PyUnicode_FromOrdinal = cpyapi.PyUnicodeUCS4_FromOrdinal
else: PyUnicode_FromOrdinal = cpyapi.PyUnicodeUCS2_FromOrdinal
PyUnicode_FromOrdinal.argtypes = [Py_UNICODE]
PyUnicode_FromOrdinal.restype = W_Object
##################################################
# ____________________ Tuples ____________________
PyTuple_New = cpyapi.PyTuple_New
PyTuple_New.argtypes = [Py_ssize_t]
PyTuple_New.restype = W_Object
PyTuple_SetItem = cpyapi.PyTuple_SetItem
PyTuple_SetItem.argtypes = [W_Object, Py_ssize_t, W_Object]
PyTuple_SetItem.restype = c_int
#################################################
# ____________________ Lists ____________________
PyList_New = cpyapi.PyList_New
PyList_New.argtypes = [Py_ssize_t]
PyList_New.restype = W_Object
PyList_Append = cpyapi.PyList_Append
PyList_Append.argtypes = [W_Object, W_Object]
PyList_Append.restype = c_int
PyList_SetItem = cpyapi.PyList_SetItem
PyList_SetItem.argtypes = [W_Object, Py_ssize_t, W_Object]
PyList_SetItem.restype = c_int
########################################################
# ____________________ Dictionaries ____________________
PyDict_New = cpyapi.PyDict_New
PyDict_New.argtypes = []
PyDict_New.restype = W_Object
PyDict_SetItem = cpyapi.PyDict_SetItem
PyDict_SetItem.argtypes = [W_Object, W_Object, W_Object]
PyDict_SetItem.restype = c_int
#####################################################
# ____________________ Utilities ____________________
PyImport_ImportModule = cpyapi.PyImport_ImportModule
PyImport_ImportModule.argtypes = [c_char_p]
PyImport_ImportModule.restype = W_Object
_PyObject_Dump = cpyapi._PyObject_Dump
_PyObject_Dump.argtypes = [W_Object]
_PyObject_Dump.restype = None
################################################
# ____________________ Misc ____________________
PySlice_New = cpyapi.PySlice_New
PySlice_New.argtypes = [W_Object, W_Object, W_Object]
PySlice_New.restype = W_Object
##############################################################
# ____________________ Built-in functions ____________________
PyArg_ParseTuple = cpyapi.PyArg_ParseTuple
PyArg_ParseTuple.restype = c_int
#PyArg_ParseTuple.argtypes = [W_Object, c_char_p, ...]
PyArg_ParseTupleAndKeywords = cpyapi.PyArg_ParseTupleAndKeywords
PyArg_ParseTupleAndKeywords.restype = c_int
#PyArg_ParseTupleAndKeywords.argtypes = [W_Object, W_Object,
# c_char_p, POINTER(c_char_p), ...]
##PyCFunction_NewEx = cpyapi.PyCFunction_NewEx
##PyCFunction_NewEx.argtypes = [POINTER(PyMethodDef), W_Object, W_Object]
##PyCFunction_NewEx.restype = W_Object
##############################################################
# ____________________ Exception handling ____________________
# "RAW" because it comes from pythonapi instead of cpyapi.
# The normal error handling (wrapping CPython exceptions into
# an OperationError) is disabled.
RAW_PyErr_SetObject = pythonapi.PyErr_SetObject
RAW_PyErr_SetObject.argtypes = [W_Object, W_Object]
RAW_PyErr_SetObject.restype = None
RAW_PyErr_SetObject._rctypes_pyerrchecker_ = None
# WARNING: consumes references
RAW_PyErr_Restore = pythonapi.PyErr_Restore
RAW_PyErr_Restore.argtypes = [W_Object, W_Object, W_Object]
RAW_PyErr_Restore.restype = None
RAW_PyErr_Restore._rctypes_pyerrchecker_ = None
RAW_PyErr_Occurred = pythonapi.PyErr_Occurred
RAW_PyErr_Occurred.argtypes = []
RAW_PyErr_Occurred.restype = c_void_p
RAW_PyErr_Occurred._rctypes_pyerrchecker_ = None
RAW_PyErr_Fetch = pythonapi.PyErr_Fetch
RAW_PyErr_Fetch.argtypes = [POINTER(W_Object),
POINTER(W_Object),
POINTER(W_Object)]
RAW_PyErr_Fetch.restype = None
RAW_PyErr_Fetch._rctypes_pyerrchecker_ = None
| Python |
import py
from pypy.tool.pytest.modcheck import skipimporterror
class Directory(py.test.collect.Directory):
def run(self):
skipimporterror("ctypes")
return super(Directory, self).run()
| Python |
"""Example usage:
$ py.py -o thunk
>>> from __pypy__ import thunk, lazy, become
>>> def f():
... print 'computing...'
... return 6*7
...
>>> x = thunk(f)
>>> x
computing...
42
>>> x
42
>>> y = thunk(f)
>>> type(y)
computing...
<pypy type 'int'>
>>> @lazy
... def g(n):
... print 'computing...'
... return n + 5
...
>>> y = g(12)
>>> y
computing...
17
"""
from pypy.objspace.proxy import patch_space_in_place
from pypy.interpreter import gateway, baseobjspace, argument
from pypy.interpreter.error import OperationError
from pypy.interpreter.function import Method
# __________________________________________________________________________
# 'w_obj.w_thunkalias' points to another object that 'w_obj' has turned into
baseobjspace.W_Root.w_thunkalias = None
# adding a name in __slots__ after class creation doesn't "work" in Python,
# but in this case it has the effect of telling the annotator that this
# attribute is allowed to be moved up to this class.
baseobjspace.W_Root.__slots__ += ('w_thunkalias',)
class W_Thunk(baseobjspace.W_Root, object):
def __init__(w_self, w_callable, args):
w_self.w_callable = w_callable
w_self.args = args
w_self.operr = None
# special marker to say that w_self has not been computed yet
w_NOT_COMPUTED_THUNK = W_Thunk(None, None)
W_Thunk.w_thunkalias = w_NOT_COMPUTED_THUNK
def _force(space, w_self):
w_alias = w_self.w_thunkalias
while w_alias is not None:
if w_alias is w_NOT_COMPUTED_THUNK:
assert isinstance(w_self, W_Thunk)
if w_self.operr is not None:
raise w_self.operr
w_callable = w_self.w_callable
args = w_self.args
if w_callable is None or args is None:
raise OperationError(space.w_RuntimeError,
space.wrap("thunk is already being computed"))
w_self.w_callable = None
w_self.args = None
try:
w_alias = space.call_args(w_callable, args)
except OperationError, operr:
w_self.operr = operr
raise
if _is_circular(w_self, w_alias):
operr = OperationError(space.w_RuntimeError,
space.wrap("circular thunk alias"))
w_self.operr = operr
raise operr
w_self.w_thunkalias = w_alias
# XXX do path compression?
w_self = w_alias
w_alias = w_self.w_thunkalias
return w_self
def _is_circular(w_obj, w_alias):
assert (w_obj.w_thunkalias is None or
w_obj.w_thunkalias is w_NOT_COMPUTED_THUNK)
while 1:
if w_obj is w_alias:
return True
w_next = w_alias.w_thunkalias
if w_next is None:
return False
if w_next is w_NOT_COMPUTED_THUNK:
return False
w_alias = w_next
def force(space, w_self):
if w_self.w_thunkalias is not None:
w_self = _force(space, w_self)
return w_self
def thunk(w_callable, __args__):
"""thunk(f, *args, **kwds) -> an object that behaves like the
result of the call f(*args, **kwds). The call is performed lazily."""
return W_Thunk(w_callable, __args__)
app_thunk = gateway.interp2app(thunk, unwrap_spec=[baseobjspace.W_Root,
argument.Arguments])
def is_thunk(space, w_obj):
"""Check if an object is a thunk that has not been computed yet."""
while 1:
w_alias = w_obj.w_thunkalias
if w_alias is None:
return space.w_False
if w_alias is w_NOT_COMPUTED_THUNK:
return space.w_True
w_obj = w_alias
app_is_thunk = gateway.interp2app(is_thunk)
def become(space, w_target, w_source):
"""Globally replace the target object with the source one."""
w_target = force(space, w_target)
if not _is_circular(w_target, w_source):
w_target.w_thunkalias = w_source
return space.w_None
app_become = gateway.interp2app(become)
def lazy(space, w_callable):
"""Decorator to make a callable return its results wrapped in a thunk."""
meth = Method(space, space.w_fn_thunk,
w_callable, space.type(w_callable))
return space.wrap(meth)
app_lazy = gateway.interp2app(lazy)
# __________________________________________________________________________
nb_forcing_args = {}
def setup():
nb_forcing_args.update({
'setattr': 2, # instead of 3
'setitem': 2, # instead of 3
'get': 2, # instead of 3
# ---- irregular operations ----
'wrap': 0,
'str_w': 1,
'int_w': 1,
'float_w': 1,
'uint_w': 1,
'unichars_w': 1,
'bigint_w': 1,
'interpclass_w': 1,
'unwrap': 1,
'is_true': 1,
'is_w': 2,
'newtuple': 0,
'newlist': 0,
'newstring': 0,
'newunicode': 0,
'newdict': 0,
'newslice': 0,
'call_args': 1,
'marshal_w': 1,
'log': 1,
})
for opname, _, arity, _ in baseobjspace.ObjSpace.MethodTable:
nb_forcing_args.setdefault(opname, arity)
for opname in baseobjspace.ObjSpace.IrregularOpTable:
assert opname in nb_forcing_args, "missing %r" % opname
setup()
del setup
# __________________________________________________________________________
def proxymaker(space, opname, parentfn):
nb_args = nb_forcing_args[opname]
if nb_args == 0:
proxy = None
elif nb_args == 1:
def proxy(w1, *extra):
w1 = force(space, w1)
return parentfn(w1, *extra)
elif nb_args == 2:
def proxy(w1, w2, *extra):
w1 = force(space, w1)
w2 = force(space, w2)
return parentfn(w1, w2, *extra)
elif nb_args == 3:
def proxy(w1, w2, w3, *extra):
w1 = force(space, w1)
w2 = force(space, w2)
w3 = force(space, w3)
return parentfn(w1, w2, w3, *extra)
else:
raise NotImplementedError("operation %r has arity %d" %
(opname, nb_args))
return proxy
def Space(*args, **kwds):
# for now, always make up a wrapped StdObjSpace
from pypy.objspace import std
space = std.Space(*args, **kwds)
patch_space_in_place(space, 'thunk', proxymaker)
w___pypy__ = space.getbuiltinmodule("__pypy__")
space.w_fn_thunk = space.wrap(app_thunk)
space.setattr(w___pypy__, space.wrap('thunk'),
space.w_fn_thunk)
space.setattr(w___pypy__, space.wrap('is_thunk'),
space.wrap(app_is_thunk))
space.setattr(w___pypy__, space.wrap('become'),
space.wrap(app_become))
space.setattr(w___pypy__, space.wrap('lazy'),
space.wrap(app_lazy))
return space
| Python |
# empty
| Python |
from pypy.interpreter.error import OperationError
from pypy.objspace.descroperation import Object
from pypy.interpreter import gateway
from pypy.interpreter.typedef import default_identity_hash
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.register_all import register_all
from pypy.objspace.std.objspace import StdObjSpace
def descr__repr__(space, w_obj):
w = space.wrap
classname = space.str_w(space.getattr(space.type(w_obj), w("__name__")))
return w_obj.getrepr(space, '%s object' % (classname,))
def descr__str__(space, w_obj):
return space.repr(w_obj)
def descr__class__(space, w_obj):
return space.type(w_obj)
def descr_set___class__(space, w_obj, w_newcls):
from pypy.objspace.std.typeobject import W_TypeObject
if not isinstance(w_newcls, W_TypeObject):
raise OperationError(space.w_TypeError,
space.wrap("__class__ must be set to new-style class, not '%s' object" %
space.type(w_newcls).getname(space, '?')))
if not w_newcls.is_heaptype():
raise OperationError(space.w_TypeError,
space.wrap("__class__ assignment: only for heap types"))
w_oldcls = space.type(w_obj)
# XXX taint space should raise a TaintError here if w_oldcls is tainted
assert isinstance(w_oldcls, W_TypeObject)
if w_oldcls.get_full_instance_layout() == w_newcls.get_full_instance_layout():
w_obj.setclass(space, w_newcls)
else:
raise OperationError(space.w_TypeError,
space.wrap("__class__ assignment: '%s' object layout differs from '%s'" %
(w_oldcls.getname(space, '?'), w_newcls.getname(space, '?'))))
def descr__new__(space, w_type, __args__):
from pypy.objspace.std.objectobject import W_ObjectObject
from pypy.objspace.std.typetype import _precheck_for_new
# don't allow arguments if the default object.__init__() is about
# to be called
w_type = _precheck_for_new(space, w_type)
w_parentinit, w_ignored = w_type.lookup_where('__init__')
if w_parentinit is space.w_object:
try:
__args__.fixedunpack(0)
except ValueError:
raise OperationError(space.w_TypeError,
space.wrap("default __new__ takes "
"no parameters"))
w_obj = space.allocate_instance(W_ObjectObject, w_type)
#W_ObjectObject.__init__(w_obj)
return w_obj
def descr__init__(space, w_obj, __args__):
pass
def descr__reduce_ex__(space, w_obj, proto=0):
w_st_reduce = space.wrap('__reduce__')
w_reduce = space.findattr(w_obj, w_st_reduce)
if w_reduce is not None:
w_cls = space.getattr(w_obj, space.wrap('__class__'))
w_cls_reduce_meth = space.getattr(w_cls, w_st_reduce)
w_cls_reduce = space.getattr(w_cls_reduce_meth, space.wrap('im_func'))
w_objtype = space.w_object
w_obj_dict = space.getattr(w_objtype, space.wrap('__dict__'))
w_obj_reduce = space.getitem(w_obj_dict, w_st_reduce)
override = space.is_true(space.ne(w_cls_reduce, w_obj_reduce))
# print 'OVR', override, w_cls_reduce, w_obj_reduce
if override:
return space.call(w_reduce, space.newtuple([]))
if proto >= 2:
return reduce_2(space, w_obj)
w_proto = space.wrap(proto)
return reduce_1(space, w_obj, w_proto)
app = gateway.applevel(r'''
def reduce_1(obj, proto):
import copy_reg
return copy_reg._reduce_ex(obj, proto)
def reduce_2(obj):
cls = obj.__class__
try:
getnewargs = obj.__getnewargs__
except AttributeError:
args = ()
else:
args = getnewargs()
if not isinstance(args, tuple):
raise TypeError, "__getnewargs__ should return a tuple"
try:
getstate = obj.__getstate__
except AttributeError:
state = getattr(obj, "__dict__", None)
names = slotnames(cls) # not checking for list
if names is not None:
slots = {}
for name in names:
try:
value = getattr(obj, name)
except AttributeError:
pass
else:
slots[name] = value
if slots:
state = state, slots
else:
state = getstate()
if isinstance(obj, list):
listitems = iter(obj)
else:
listitems = None
if isinstance(obj, dict):
dictitems = obj.iteritems()
else:
dictitems = None
import copy_reg
newobj = copy_reg.__newobj__
args2 = (cls,) + args
return newobj, args2, state, listitems, dictitems
def slotnames(cls):
if not isinstance(cls, type):
return None
try:
return cls.__dict__["__slotnames__"]
except KeyError:
pass
import copy_reg
slotnames = copy_reg._slotnames(cls)
if not isinstance(slotnames, list) and slotnames is not None:
raise TypeError, "copy_reg._slotnames didn't return a list or None"
return slotnames
''', filename=__file__)
reduce_1 = app.interphook('reduce_1')
reduce_2 = app.interphook('reduce_2')
# ____________________________________________________________
object_typedef = StdTypeDef("object",
__getattribute__ = gateway.interp2app(Object.descr__getattribute__.im_func),
__setattr__ = gateway.interp2app(Object.descr__setattr__.im_func),
__delattr__ = gateway.interp2app(Object.descr__delattr__.im_func),
__str__ = gateway.interp2app(descr__str__),
__repr__ = gateway.interp2app(descr__repr__),
__class__ = GetSetProperty(descr__class__, descr_set___class__),
__doc__ = '''The most base type''',
__new__ = newmethod(descr__new__,
unwrap_spec = [gateway.ObjSpace,gateway.W_Root,gateway.Arguments]),
__hash__ = gateway.interp2app(default_identity_hash),
__reduce_ex__ = gateway.interp2app(descr__reduce_ex__,
unwrap_spec=[gateway.ObjSpace,gateway.W_Root,int]),
__reduce__ = gateway.interp2app(descr__reduce_ex__,
unwrap_spec=[gateway.ObjSpace,gateway.W_Root,int]),
__init__ = gateway.interp2app(descr__init__,
unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]),
)
object_typedef.custom_hash = False # object.__hash__ is not a custom hash
| Python |
""" transparent list implementation
"""
from pypy.objspace.std.objspace import *
from pypy.objspace.std.proxy_helpers import register_type
from pypy.interpreter.error import OperationError
from pypy.interpreter import baseobjspace
#class W_Transparent(W_Object):
# def __init__(self, w_controller):
# self.controller = w_controller
#class W_TransparentWrappable(Wrappable):
def transparent_class(name, BaseCls):
class W_Transparent(BaseCls):
def __init__(self, space, w_type, w_controller):
self.w_type = w_type
self.w_controller = w_controller
self.space = space
def descr_call_mismatch(self, space, name, reqcls, args):
_, args = args.popfirst()
args = args.prepend(space.wrap(name))
return space.call_args(self.w_controller, args)
def getclass(self, space):
return self.w_type
def setclass(self, space, w_subtype):
raise OperationError(space.w_TypeError,
space.wrap("You cannot override __class__ for transparent proxies"))
def getdictvalue(self, space, w_attr):
try:
return space.call_function(self.w_controller, space.wrap('__getattribute__'),
w_attr)
except OperationError, e:
if not e.match(space, space.w_AttributeError):
raise
return None
def setdictvalue(self, space, w_attr, w_value, shadows_type=True):
try:
space.call_function(self.w_controller, space.wrap('__setattr__'),
w_attr, w_value)
return True
except OperationError, e:
if not e.match(space, space.w_AttributeError):
raise
return False
def deldictvalue(self, space, w_attr):
try:
space.call_function(self.w_controller, space.wrap('__delattr__'),
w_attr)
return True
except OperationError, e:
if not e.match(space, space.w_AttributeError):
raise
return False
def getdict(self):
return self.getdictvalue(self.space, self.space.wrap('__dict__'))
def setdict(self, space, w_dict):
if not self.setdictvalue(space, space.wrap('__dict__'), w_dict):
baseobjspace.W_Root.setdict(self, space, w_dict)
## def __getattr__(self, attr):
## # NOT_RPYTHON
## try:
## return self.getdictvalue(self.space, self.space.wrap(attr))
## except OperationError, e:
## raise AttributeError(attr)
W_Transparent.__name__ = name
return W_Transparent
W_Transparent = transparent_class('W_Transparent', Wrappable)
W_TransparentObject = transparent_class('W_TransparentObject', W_Object)
from pypy.objspace.std.objecttype import object_typedef
W_TransparentObject.typedef = object_typedef
from pypy.interpreter.typedef import Function, GeneratorIterator, PyTraceback, \
PyFrame, PyCode
class W_TransparentFunction(W_Transparent):
typedef = Function.typedef
class W_TransparentTraceback(W_Transparent):
typedef = PyTraceback.typedef
class W_TransparentCode(W_Transparent):
typedef = PyCode.typedef
class W_TransparentFrame(W_Transparent):
typedef = PyFrame.typedef
class W_TransparentGenerator(W_Transparent):
typedef = GeneratorIterator.typedef
class W_TransparentList(W_TransparentObject):
from pypy.objspace.std.listobject import W_ListObject as original
from pypy.objspace.std.listtype import list_typedef as typedef
class W_TransparentDict(W_TransparentObject):
from pypy.objspace.std.dictobject import W_DictObject as original
from pypy.objspace.std.dicttype import dict_typedef as typedef
registerimplementation(W_TransparentList)
registerimplementation(W_TransparentDict)
register_type(W_TransparentList)
register_type(W_TransparentDict)
| Python |
"""
Implementation of small ints, stored as odd-valued pointers in the
translated PyPy. To enable them, see inttype.py.
"""
from pypy.objspace.std.objspace import *
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.rlib.rarithmetic import ovfcheck, ovfcheck_lshift, LONG_BIT, r_uint
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.intobject import W_IntObject
from pypy.rlib.objectmodel import UnboxedValue
# XXX this is a complete copy of intobject.py. Find a better but still
# XXX annotator-friendly way to share code...
class W_SmallIntObject(W_Object, UnboxedValue):
__slots__ = 'intval'
from pypy.objspace.std.inttype import int_typedef as typedef
def unwrap(w_self, space):
return int(w_self.intval)
registerimplementation(W_SmallIntObject)
def delegate_SmallInt2Int(space, w_small):
return W_IntObject(w_small.intval)
def delegate_SmallInt2Long(space, w_small):
return space.newlong(w_small.intval)
def delegate_SmallInt2Float(space, w_small):
return space.newfloat(float(w_small.intval))
def delegate_SmallInt2Complex(space, w_small):
return space.newcomplex(float(w_small.intval), 0.0)
"""
XXX not implemented:
free list
FromString
FromUnicode
print
"""
def int_w__SmallInt(space, w_int1):
return int(w_int1.intval)
def uint_w__SmallInt(space, w_int1):
intval = w_int1.intval
if intval < 0:
raise OperationError(space.w_ValueError,
space.wrap("cannot convert negative integer to unsigned"))
else:
return r_uint(intval)
def repr__SmallInt(space, w_int1):
a = w_int1.intval
res = str(a)
return space.wrap(res)
str__SmallInt = repr__SmallInt
def lt__SmallInt_SmallInt(space, w_int1, w_int2):
i = w_int1.intval
j = w_int2.intval
return space.newbool( i < j )
def le__SmallInt_SmallInt(space, w_int1, w_int2):
i = w_int1.intval
j = w_int2.intval
return space.newbool( i <= j )
def eq__SmallInt_SmallInt(space, w_int1, w_int2):
i = w_int1.intval
j = w_int2.intval
return space.newbool( i == j )
def ne__SmallInt_SmallInt(space, w_int1, w_int2):
i = w_int1.intval
j = w_int2.intval
return space.newbool( i != j )
def gt__SmallInt_SmallInt(space, w_int1, w_int2):
i = w_int1.intval
j = w_int2.intval
return space.newbool( i > j )
def ge__SmallInt_SmallInt(space, w_int1, w_int2):
i = w_int1.intval
j = w_int2.intval
return space.newbool( i >= j )
def hash__SmallInt(space, w_int1):
# unlike CPython, we don't special-case the value -1 in most of our
# hash functions, so there is not much sense special-casing it here either.
# Make sure this is consistent with the hash of floats and longs.
return int__SmallInt(space, w_int1)
# coerce
def coerce__SmallInt_SmallInt(space, w_int1, w_int2):
return space.newtuple([w_int1, w_int2])
def add__SmallInt_SmallInt(space, w_int1, w_int2):
x = w_int1.intval
y = w_int2.intval
try:
z = ovfcheck(x + y)
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer addition"))
return wrapint(space, z)
def sub__SmallInt_SmallInt(space, w_int1, w_int2):
x = w_int1.intval
y = w_int2.intval
try:
z = ovfcheck(x - y)
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer substraction"))
return wrapint(space, z)
def mul__SmallInt_SmallInt(space, w_int1, w_int2):
x = w_int1.intval
y = w_int2.intval
try:
z = ovfcheck(x * y)
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer multiplication"))
return wrapint(space, z)
def _floordiv(space, w_int1, w_int2):
x = w_int1.intval
y = w_int2.intval
try:
z = ovfcheck(x // y)
except ZeroDivisionError:
raise OperationError(space.w_ZeroDivisionError,
space.wrap("integer division by zero"))
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer division"))
return wrapint(space, z)
def _truediv(space, w_int1, w_int2):
# XXX how to do delegation to float elegantly?
# avoiding a general space.div operation which pulls
# the whole interpreter in.
# Instead, we delegate to long for now.
raise FailedToImplement(space.w_TypeError,
space.wrap("integer division"))
def mod__SmallInt_SmallInt(space, w_int1, w_int2):
x = w_int1.intval
y = w_int2.intval
try:
z = ovfcheck(x % y)
except ZeroDivisionError:
raise OperationError(space.w_ZeroDivisionError,
space.wrap("integer modulo by zero"))
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer modulo"))
return wrapint(space, z)
def divmod__SmallInt_SmallInt(space, w_int1, w_int2):
x = w_int1.intval
y = w_int2.intval
try:
z = ovfcheck(x // y)
except ZeroDivisionError:
raise OperationError(space.w_ZeroDivisionError,
space.wrap("integer divmod by zero"))
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer modulo"))
# no overflow possible
m = x % y
return space.wrap((z,m))
def div__SmallInt_SmallInt(space, w_int1, w_int2):
return _floordiv(space, w_int1, w_int2)
floordiv__SmallInt_SmallInt = _floordiv
truediv__SmallInt_SmallInt = _truediv
# helper for pow()
def _impl_int_int_pow(space, iv, iw, iz=0):
if iw < 0:
if iz != 0:
raise OperationError(space.w_TypeError,
space.wrap("pow() 2nd argument "
"cannot be negative when 3rd argument specified"))
## bounce it, since it always returns float
raise FailedToImplement(space.w_ValueError,
space.wrap("integer exponentiation"))
temp = iv
ix = 1
try:
while iw > 0:
if iw & 1:
ix = ovfcheck(ix*temp)
iw >>= 1 #/* Shift exponent down by 1 bit */
if iw==0:
break
temp = ovfcheck(temp*temp) #/* Square the value of temp */
if iz:
#/* If we did a multiplication, perform a modulo */
ix = ix % iz;
temp = temp % iz;
if iz:
ix = ix % iz
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer exponentiation"))
return wrapint(space, ix)
def pow__SmallInt_SmallInt_SmallInt(space, w_int1, w_int2, w_int3):
x = w_int1.intval
y = w_int2.intval
z = w_int3.intval
if z == 0:
raise OperationError(space.w_ValueError,
space.wrap("pow() 3rd argument cannot be 0"))
return _impl_int_int_pow(space, x, y, z)
def pow__SmallInt_SmallInt_None(space, w_int1, w_int2, w_int3):
x = w_int1.intval
y = w_int2.intval
return _impl_int_int_pow(space, x, y)
def neg__SmallInt(space, w_int1):
a = w_int1.intval
try:
x = ovfcheck(-a)
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer negation"))
return wrapint(space, x)
# pos__SmallInt is supposed to do nothing, unless it has
# a derived integer object, where it should return
# an exact one.
def pos__SmallInt(space, w_int1):
return int__SmallInt(space, w_int1)
def abs__SmallInt(space, w_int1):
if w_int1.intval >= 0:
return pos__SmallInt(space, w_int1)
else:
return neg__SmallInt(space, w_int1)
def nonzero__SmallInt(space, w_int1):
return space.newbool(w_int1.intval != 0)
def invert__SmallInt(space, w_int1):
x = w_int1.intval
a = ~x
return wrapint(space, a)
def lshift__SmallInt_SmallInt(space, w_int1, w_int2):
a = w_int1.intval
b = w_int2.intval
if b < 0:
raise OperationError(space.w_ValueError,
space.wrap("negative shift count"))
if a == 0 or b == 0:
return int__SmallInt(space, w_int1)
if b >= LONG_BIT:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer left shift"))
##
## XXX please! have a look into pyport.h and see how to implement
## the overflow checking, using macro Py_ARITHMETIC_RIGHT_SHIFT
## we *assume* that the overflow checking is done correctly
## in the code generator, which is not trivial!
## XXX also note that Python 2.3 returns a long and never raises
## OverflowError.
try:
c = ovfcheck_lshift(a, b)
## the test in C code is
## if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
## if (PyErr_Warn(PyExc_FutureWarning,
# and so on
except OverflowError:
raise FailedToImplement(space.w_OverflowError,
space.wrap("integer left shift"))
return wrapint(space, c)
def rshift__SmallInt_SmallInt(space, w_int1, w_int2):
a = w_int1.intval
b = w_int2.intval
if b < 0:
raise OperationError(space.w_ValueError,
space.wrap("negative shift count"))
if a == 0 or b == 0:
return int__SmallInt(space, w_int1)
if b >= LONG_BIT:
if a < 0:
a = -1
else:
a = 0
else:
## please look into pyport.h, how >> should be implemented!
## a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
a = a >> b
return wrapint(space, a)
def and__SmallInt_SmallInt(space, w_int1, w_int2):
a = w_int1.intval
b = w_int2.intval
res = a & b
return wrapint(space, res)
def xor__SmallInt_SmallInt(space, w_int1, w_int2):
a = w_int1.intval
b = w_int2.intval
res = a ^ b
return wrapint(space, res)
def or__SmallInt_SmallInt(space, w_int1, w_int2):
a = w_int1.intval
b = w_int2.intval
res = a | b
return wrapint(space, res)
# coerce is not wanted
##
##static int
##coerce__Int(PyObject **pv, PyObject **pw)
##{
## if (PyInt_Check(*pw)) {
## Py_INCREF(*pv);
## Py_INCREF(*pw);
## return 0;
## }
## return 1; /* Can't do it */
##}
# int__SmallInt is supposed to do nothing, unless it has
# a derived integer object, where it should return
# an exact one.
def int__SmallInt(space, w_int1):
if space.is_w(space.type(w_int1), space.w_int):
return w_int1
a = w_int1.intval
return wrapint(space, a)
"""
# Not registered
def long__SmallInt(space, w_int1):
a = w_int1.intval
x = long(a) ## XXX should this really be done so?
return space.newlong(x)
"""
def float__SmallInt(space, w_int1):
a = w_int1.intval
x = float(a)
return space.newfloat(x)
def oct__SmallInt(space, w_int1):
return space.wrap(oct(w_int1.intval))
def hex__SmallInt(space, w_int1):
return space.wrap(hex(w_int1.intval))
def getnewargs__SmallInt(space, w_int1):
return space.newtuple([wrapint(space, w_int1.intval)])
register_all(vars())
| Python |
from pypy.interpreter.error import OperationError
from pypy.interpreter import gateway
from pypy.objspace.std.strutil import interp_string_to_float, ParseStringError
from pypy.objspace.std.objspace import register_all
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.objspace.std.stdtypedef import GetSetProperty, StdTypeDef, newmethod
from pypy.objspace.std.stdtypedef import StdObjSpaceMultiMethod
# ERRORCODES
ERR_WRONG_SECOND = "complex() can't take second arg if first is a string"
ERR_MALFORMED = "complex() arg is a malformed string"
OVERFLOWED_FLOAT = 1e200
OVERFLOWED_FLOAT *= OVERFLOWED_FLOAT
complex_conjugate = StdObjSpaceMultiMethod('conjugate', 1,
doc="(A+Bj).conjugate() -> A-Bj")
register_all(vars(),globals())
def _split_complex(s):
slen = len(s)
if slen == 0:
raise ValueError
realstart = 0
realstop = 0
imagstart = 0
imagstop = 0
imagsign = ' '
i = 0
# ignore whitespace
while i < slen and s[i] == ' ':
i += 1
# extract first number
realstart = i
pc = s[i]
while i < slen and s[i] != ' ':
if s[i] in ('+','-') and pc not in ('e','E') and i != realstart:
break
pc = s[i]
i += 1
realstop = i
# ignore whitespace
while i < slen and s[i] == ' ':
i += 1
# return appropriate strings is only one number is there
if i >= slen:
newstop = realstop - 1
if newstop < 0:
raise ValueError
if s[newstop] in ('j','J'):
if realstart == newstop:
imagpart = '1.0'
else:
imagpart = s[realstart:newstop]
return '0.0', imagpart
else:
return s[realstart:realstop],'0.0'
# find sign for imaginary part
if s[i] == '-' or s[i] == '+':
imagsign = s[i]
if imagsign == ' ':
raise ValueError
i+=1
# whitespace
while i < slen and s[i] == ' ':
i += 1
if i >= slen:
raise ValueError
imagstart = i
pc = s[i]
while i < slen and s[i] != ' ':
if s[i] in ('+','-') and pc not in ('e','E'):
break
pc = s[i]
i += 1
imagstop = i - 1
if imagstop < 0:
raise ValueError
if s[imagstop] not in ('j','J'):
raise ValueError
if imagstop < imagstart:
raise ValueError
while i<slen and s[i] == ' ':
i += 1
if i < slen:
raise ValueError
realpart = s[realstart:realstop]
if imagstart == imagstop:
imagpart = '1.0'
else:
imagpart = s[imagstart:imagstop]
if imagsign == '-':
imagpart = imagsign + imagpart
return realpart, imagpart
def descr__new__(space, w_complextype, w_real=0.0, w_imag=None):
from pypy.objspace.std.complexobject import W_ComplexObject
# if w_real is already a complex number and there is no second
# argument, return it. Note that we cannot return w_real if
# it is an instance of a *subclass* of complex, or if w_complextype
# is itself a subclass of complex.
noarg2 = space.is_w(w_imag, space.w_None)
if (noarg2 and space.is_w(w_complextype, space.w_complex)
and space.is_w(space.type(w_real), space.w_complex)):
return w_real
if space.is_true(space.isinstance(w_real, space.w_str)) or \
space.is_true(space.isinstance(w_real, space.w_unicode)):
# a string argument
if not noarg2:
raise OperationError(space.w_TypeError,
space.wrap("complex() can't take second arg"
" if first is a string"))
try:
realstr, imagstr = _split_complex(space.str_w(w_real))
except ValueError:
raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED))
try:
realval = interp_string_to_float(space, realstr)
imagval = interp_string_to_float(space, imagstr)
except ParseStringError:
raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED))
else:
#check for overflow
if abs(realval) == OVERFLOWED_FLOAT or abs(imagval) == OVERFLOWED_FLOAT:
raise OperationError(space.w_ValueError,space.wrap(
"complex() literal too large to convert"))
else:
# non-string arguments
# test for a '__complex__' method, and call it if found.
# A bit of a hack to support old-style classes: don't use
# space.lookup() (this is similar to CPython).
try:
w_method = space.getattr(w_real, space.wrap('__complex__'))
except OperationError, e:
if not e.match(space, space.w_AttributeError):
raise
else:
w_real = space.call_function(w_method)
# __complex__() could return a string, which space.float()
# could accept below... Let's catch this case.
if space.is_true(space.isinstance(w_imag, space.w_str)) or \
space.is_true(space.isinstance(w_imag, space.w_unicode)):
raise OperationError(space.w_TypeError,
space.wrap("__complex__() cannot return"
" a string"))
# at this point w_real can be an instance of 'complex',
# either because it is the result of __complex__() or because
# the shortcut at the beginning of the function didn't match
if space.is_true(space.isinstance(w_real, space.w_complex)):
# note that we are unwrapping the complex for the rest of
# the code. This also ensures that we eventually return
# an object of the correct subclass of complex.
realval = space.float_w(space.getattr(w_real, space.wrap('real')))
imagval = space.float_w(space.getattr(w_real, space.wrap('imag')))
else:
realval = space.float_w(space.float(w_real))
imagval = 0.0
# now take w_imag into account
if not noarg2:
if space.is_true(space.isinstance(w_imag, space.w_complex)):
# complex(x, y) == x+y*j, even if 'y' is already a complex.
# say y == a+b*j:
a = space.float_w(space.getattr(w_imag, space.wrap('real')))
b = space.float_w(space.getattr(w_imag, space.wrap('imag')))
realval -= b
imagval += a
elif space.is_true(space.isinstance(w_imag, space.w_str)) or \
space.is_true(space.isinstance(w_imag, space.w_unicode)):
# prevent space.float(w_imag) from succeeding
raise OperationError(space.w_TypeError,
space.wrap("complex() second arg"
" can't be a string"))
else:
imagval += space.float_w(space.float(w_imag))
# done
w_obj = space.allocate_instance(W_ComplexObject, w_complextype)
W_ComplexObject.__init__(w_obj, realval, imagval)
return w_obj
def complexwprop(name):
def fget(space, w_obj):
from pypy.objspace.std.complexobject import W_ComplexObject
if not isinstance(w_obj, W_ComplexObject):
raise OperationError(space.w_TypeError,
space.wrap("descriptor is for 'complex'"))
return space.newfloat(getattr(w_obj, name))
return GetSetProperty(fget)
def descr___getnewargs__(space, w_self):
from pypy.objspace.std.complexobject import W_ComplexObject
assert isinstance(w_self, W_ComplexObject)
return space.newtuple([space.newcomplex(w_self.realval,w_self.imagval)])
complex_typedef = StdTypeDef("complex",
__doc__ = """complex(real[, imag]) -> complex number
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.""",
__new__ = newmethod(descr__new__),
__getnewargs__ = newmethod(descr___getnewargs__),
real = complexwprop('realval'),
imag = complexwprop('imagval'),
)
complex_typedef.custom_hash = True
complex_typedef.registermethods(globals())
| Python |
from pypy.objspace.std.objspace import W_Object, OperationError
from pypy.objspace.std.objspace import registerimplementation, register_all
from pypy.rlib.objectmodel import r_dict
from pypy.rlib.rarithmetic import intmask, r_uint
from pypy.interpreter import gateway
class W_BaseSetObject(W_Object):
def __init__(w_self, space, setdata=None):
if setdata is None:
w_self.setdata = r_dict(space.eq_w, space.hash_w)
else:
w_self.setdata = setdata.copy()
def __repr__(w_self):
"""representation for debugging purposes"""
reprlist = [repr(w_item) for w_item in w_self.setdata.keys()]
return "<%s(%s)>" % (w_self.__class__.__name__, ', '.join(reprlist))
def _newobj(w_self, space, rdict_w=None):
#return space.call(space.type(w_self),W_SetIterObject(rdict_w))
objtype = type(w_self)
if objtype is W_SetObject:
obj = W_SetObject(space, rdict_w)
elif objtype is W_FrozensetObject:
obj = W_FrozensetObject(space, rdict_w)
else:
itemiterator = space.iter(W_SetIterObject(rdict_w))
obj = space.call_function(space.type(w_self),itemiterator)
return obj
class W_SetObject(W_BaseSetObject):
from pypy.objspace.std.settype import set_typedef as typedef
class W_FrozensetObject(W_BaseSetObject):
from pypy.objspace.std.frozensettype import frozenset_typedef as typedef
def __init__(w_self, space, setdata):
W_BaseSetObject.__init__(w_self, space, setdata)
w_self.hash = -1
registerimplementation(W_SetObject)
registerimplementation(W_FrozensetObject)
class W_SetIterObject(W_Object):
from pypy.objspace.std.settype import setiter_typedef as typedef
def __init__(w_self, setdata):
w_self.content = content = setdata
w_self.len = len(content)
w_self.pos = 0
w_self.iterator = w_self.content.iterkeys()
def next_entry(w_self):
for w_key in w_self.iterator:
return w_key
else:
return None
registerimplementation(W_SetIterObject)
def iter__SetIterObject(space, w_setiter):
return w_setiter
def next__SetIterObject(space, w_setiter):
content = w_setiter.content
if content is not None:
if w_setiter.len != len(content):
w_setiter.len = -1 # Make this error state sticky
raise OperationError(space.w_RuntimeError,
space.wrap("dictionary changed size during iteration"))
# look for the next entry
w_result = w_setiter.next_entry()
if w_result is not None:
w_setiter.pos += 1
return w_result
# no more entries
w_setiter.content = None
raise OperationError(space.w_StopIteration, space.w_None)
def len__SetIterObject(space, w_setiter):
content = w_setiter.content
if content is None or w_setiter.len == -1:
return space.wrap(0)
return space.wrap(w_setiter.len - w_setiter.pos)
# some helper functions
def make_setdata_from_w_iterable(space, w_iterable=None):
data = r_dict(space.eq_w, space.hash_w)
if w_iterable is not None:
w_iterator = space.iter(w_iterable)
while True:
try:
w_item = space.next(w_iterator)
except OperationError, e:
if not e.match(space, space.w_StopIteration):
raise
break
data[w_item] = None
return data
def _initialize_set(space, w_obj, w_iterable=None):
w_obj.setdata.clear()
if w_iterable is not None:
w_obj.setdata.update(make_setdata_from_w_iterable(space, w_iterable))
# helper functions for set operation on dicts
def _is_frozenset_exact(w_obj):
if (w_obj is not None) and (type(w_obj) is W_FrozensetObject):
return True
else:
return False
def _is_eq(w_left, w_right):
if len(w_left.setdata) != len(w_right.setdata):
return False
for w_key in w_left.setdata:
if w_key not in w_right.setdata:
return False
return True
def _union_dict(ldict, rdict, isupdate):
if isupdate:
ld = ldict
else:
ld = ldict.copy()
ld.update(rdict)
return ld, rdict
def _difference_dict(ldict, rdict, isupdate):
if isupdate:
ld = ldict
else:
ld = ldict.copy()
del_list_w = []
for w_key in ld:
if w_key in rdict:
del_list_w.append(w_key)
for w_key in del_list_w:
del ld[w_key]
return ld, rdict
def _intersection_dict(ldict, rdict, isupdate):
if isupdate:
ld = ldict
else:
ld = ldict.copy()
del_list_w = []
for w_key in ld:
if w_key not in rdict:
del_list_w.append(w_key)
for w_key in del_list_w:
del ld[w_key]
return ld, rdict
def _symmetric_difference_dict(ldict, rdict, isupdate):
if isupdate:
ld = ldict
else:
ld = ldict.copy()
del_list_w = []
add_list_w = []
for w_key in ld:
if w_key in rdict:
del_list_w.append(w_key)
for w_key in rdict:
if w_key not in ld:
add_list_w.append(w_key)
for w_key in del_list_w:
del ld[w_key]
for w_key in add_list_w:
ld[w_key] = None
return ld, rdict
#end helper functions
def set_update__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _union_dict(ld, rd, True)
return space.w_None
set_update__Set_Frozenset = set_update__Set_Set
def set_update__Set_ANY(space, w_left, w_other):
"""Update a set with the union of itself and another."""
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _union_dict(ld, rd, True)
return space.w_None
def inplace_or__Set_Set(space, w_left, w_other):
set_update__Set_Set(space, w_left, w_other)
return w_left
inplace_or__Set_Frozenset = inplace_or__Set_Set
def set_add__Set_ANY(space, w_left, w_other):
"""Add an element to a set.
This has no effect if the element is already present.
"""
w_left.setdata[w_other] = None
return space.w_None
def set_copy__Set(space, w_set):
return w_set._newobj(space,w_set.setdata)
def frozenset_copy__Frozenset(space, w_left):
if _is_frozenset_exact(w_left):
return w_left
else:
return set_copy__Set(space,w_left)
def set_clear__Set(space, w_left):
w_left.setdata.clear()
return space.w_None
def set_difference__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _difference_dict(ld, rd, False)
return w_left._newobj(space, new_ld)
set_difference__Set_Frozenset = set_difference__Set_Set
frozenset_difference__Frozenset_Set = set_difference__Set_Set
frozenset_difference__Frozenset_Frozenset = set_difference__Set_Set
sub__Set_Set = set_difference__Set_Set
sub__Set_Frozenset = set_difference__Set_Set
sub__Frozenset_Set = set_difference__Set_Set
sub__Frozenset_Frozenset = set_difference__Set_Set
def set_difference__Set_ANY(space, w_left, w_other):
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _difference_dict(ld, rd, False)
return w_left._newobj(space, new_ld)
frozenset_difference__Frozenset_ANY = set_difference__Set_ANY
def set_difference_update__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _difference_dict(ld, rd, True)
return space.w_None
set_difference_update__Set_Frozenset = set_difference_update__Set_Set
def set_difference_update__Set_ANY(space, w_left, w_other):
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _difference_dict(ld, rd, True)
return space.w_None
def inplace_sub__Set_Set(space, w_left, w_other):
set_difference_update__Set_Set(space, w_left, w_other)
return w_left
inplace_sub__Set_Frozenset = inplace_sub__Set_Set
def eq__Set_Set(space, w_left, w_other):
return space.wrap(_is_eq(w_left, w_other))
eq__Set_Frozenset = eq__Set_Set
eq__Frozenset_Frozenset = eq__Set_Set
eq__Frozenset_Set = eq__Set_Set
def eq__Set_ANY(space, w_left, w_other):
return space.w_False
eq__Frozenset_ANY = eq__Set_ANY
def contains__Set_Set(space, w_left, w_other):
w_f = space.newfrozenset(w_other.setdata)
return space.newbool(w_f in w_left.setdata)
contains__Frozenset_Set = contains__Set_Set
def contains__Set_ANY(space, w_left, w_other):
return space.newbool(w_other in w_left.setdata)
contains__Frozenset_ANY = contains__Set_ANY
def set_issubset__Set_Set(space, w_left, w_other):
if space.is_w(w_left, w_other):
return space.w_True
ld, rd = w_left.setdata, w_other.setdata
if len(ld) > len(rd):
return space.w_False
for w_key in ld:
if w_key not in rd:
return space.w_False
return space.w_True
set_issubset__Set_Frozenset = set_issubset__Set_Set
frozenset_issubset__Frozenset_Set = set_issubset__Set_Set
frozenset_issubset__Frozenset_Frozenset = set_issubset__Set_Set
def set_issubset__Set_ANY(space, w_left, w_other):
if space.is_w(w_left, w_other):
return space.w_True
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
if len(ld) > len(rd):
return space.w_False
for w_key in ld:
if w_key not in rd:
return space.w_False
return space.w_True
frozenset_issubset__Frozenset_ANY = set_issubset__Set_ANY
le__Set_Set = set_issubset__Set_Set
le__Set_Frozenset = set_issubset__Set_Set
le__Frozenset_Frozenset = set_issubset__Set_Set
def set_issuperset__Set_Set(space, w_left, w_other):
if space.is_w(w_left, w_other):
return space.w_True
ld, rd = w_left.setdata, w_other.setdata
if len(ld) < len(rd):
return space.w_False
for w_key in rd:
if w_key not in ld:
return space.w_False
return space.w_True
set_issuperset__Set_Frozenset = set_issuperset__Set_Set
set_issuperset__Frozenset_Set = set_issuperset__Set_Set
set_issuperset__Frozenset_Frozenset = set_issuperset__Set_Set
def set_issuperset__Set_ANY(space, w_left, w_other):
if space.is_w(w_left, w_other):
return space.w_True
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
if len(ld) < len(rd):
return space.w_False
for w_key in rd:
if w_key not in ld:
return space.w_False
return space.w_True
frozenset_issuperset__Frozenset_ANY = set_issuperset__Set_ANY
ge__Set_Set = set_issuperset__Set_Set
ge__Set_Frozenset = set_issuperset__Set_Set
ge__Frozenset_Frozenset = set_issuperset__Set_Set
def set_discard__Set_Set(space, w_left, w_item):
w_f = space.newfrozenset(w_item.setdata)
if w_f in w_left.setdata:
del w_left.setdata[w_f]
def set_discard__Set_ANY(space, w_left, w_item):
if w_item in w_left.setdata:
del w_left.setdata[w_item]
def set_remove__Set_Set(space, w_left, w_item):
w_f = space.newfrozenset(w_item.setdata)
try:
del w_left.setdata[w_f]
except KeyError:
raise OperationError(space.w_KeyError,
space.call_method(w_item,'__repr__'))
def set_remove__Set_ANY(space, w_left, w_item):
try:
del w_left.setdata[w_item]
except KeyError:
raise OperationError(space.w_KeyError,
space.call_method(w_item,'__repr__'))
def hash__Frozenset(space, w_set):
multi = r_uint(1822399083) + r_uint(1822399083) + 1
if w_set.hash != -1:
return space.wrap(w_set.hash)
hash = 1927868237
hash *= (len(w_set.setdata) + 1)
for w_item in w_set.setdata:
h = space.hash_w(w_item)
value = ((h ^ (h << 16) ^ 89869747) * multi)
hash = intmask(hash ^ value)
hash = hash * 69069 + 907133923
if hash == -1:
hash = 590923713
hash = intmask(hash)
w_set.hash = hash
return space.wrap(hash)
def set_pop__Set(space, w_left):
if len(w_left.setdata) == 0:
raise OperationError(space.w_KeyError,
space.wrap('pop from an empty set'))
w_keys = w_left.setdata.keys()
w_value = w_keys[0]
del w_left.setdata[w_value]
return w_value
def set_intersection__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _intersection_dict(ld, rd, False)
return w_left._newobj(space,new_ld)
set_intersection__Set_Frozenset = set_intersection__Set_Set
set_intersection__Frozenset_Frozenset = set_intersection__Set_Set
set_intersection__Frozenset_Set = set_intersection__Set_Set
def set_intersection__Set_ANY(space, w_left, w_other):
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _intersection_dict(ld, rd, False)
return w_left._newobj(space,new_ld)
frozenset_intersection__Frozenset_ANY = set_intersection__Set_ANY
and__Set_Set = set_intersection__Set_Set
and__Set_Frozenset = set_intersection__Set_Set
and__Frozenset_Set = set_intersection__Set_Set
and__Frozenset_Frozenset = set_intersection__Set_Set
def set_intersection_update__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _intersection_dict(ld, rd, True)
return space.w_None
set_intersection_update__Set_Frozenset = set_intersection_update__Set_Set
def set_intersection_update__Set_ANY(space, w_left, w_other):
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _intersection_dict(ld, rd, True)
return space.w_None
def inplace_and__Set_Set(space, w_left, w_other):
set_intersection_update__Set_Set(space, w_left, w_other)
return w_left
inplace_and__Set_Frozenset = inplace_and__Set_Set
def set_symmetric_difference__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _symmetric_difference_dict(ld, rd, False)
return w_left._newobj(space, new_ld)
set_symmetric_difference__Set_Frozenset = set_symmetric_difference__Set_Set
set_symmetric_difference__Frozenset_Set = set_symmetric_difference__Set_Set
set_symmetric_difference__Frozenset_Frozenset = \
set_symmetric_difference__Set_Set
xor__Set_Set = set_symmetric_difference__Set_Set
xor__Set_Frozenset = set_symmetric_difference__Set_Set
xor__Frozenset_Set = set_symmetric_difference__Set_Set
xor__Frozenset_Frozenset = set_symmetric_difference__Set_Set
def set_symmetric_difference__Set_ANY(space, w_left, w_other):
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _symmetric_difference_dict(ld, rd, False)
return w_left._newobj(space, new_ld)
frozenset_symmetric_difference__Frozenset_ANY = \
set_symmetric_difference__Set_ANY
def set_symmetric_difference_update__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _symmetric_difference_dict(ld, rd, True)
return space.w_None
set_symmetric_difference_update__Set_Frozenset = \
set_symmetric_difference_update__Set_Set
def set_symmetric_difference_update__Set_ANY(space, w_left, w_other):
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _symmetric_difference_dict(ld, rd, True)
return space.w_None
def inplace_xor__Set_Set(space, w_left, w_other):
set_symmetric_difference_update__Set_Set(space, w_left, w_other)
return w_left
inplace_xor__Set_Frozenset = inplace_xor__Set_Set
def set_union__Set_Set(space, w_left, w_other):
ld, rd = w_left.setdata, w_other.setdata
new_ld, rd = _union_dict(ld, rd, False)
return w_left._newobj(space, new_ld)
set_union__Set_Frozenset = set_union__Set_Set
set_union__Frozenset_Set = set_union__Set_Set
set_union__Frozenset_Frozenset = set_union__Set_Set
or__Set_Set = set_union__Set_Set
or__Set_Frozenset = set_union__Set_Set
or__Frozenset_Set = set_union__Set_Set
or__Frozenset_Frozenset = set_union__Set_Set
def set_union__Set_ANY(space, w_left, w_other):
ld, rd = w_left.setdata, make_setdata_from_w_iterable(space, w_other)
new_ld, rd = _union_dict(ld, rd, False)
return w_left._newobj(space, new_ld)
frozenset_union__Frozenset_ANY = set_union__Set_ANY
def len__Set(space, w_left):
return space.newint(len(w_left.setdata))
len__Frozenset = len__Set
def iter__Set(space, w_left):
return W_SetIterObject(w_left.setdata)
iter__Frozenset = iter__Set
def cmp__Set_Set(space, w_left, w_other):
raise OperationError(space.w_TypeError,
space.wrap('cannot compare sets using cmp()'))
cmp__Set_Frozenset = cmp__Set_Set
cmp__Frozenset_Frozenset = cmp__Set_Set
cmp__Frozenset_Set = cmp__Set_Set
def init__Set(space, w_set, __args__):
w_iterable, = __args__.parse('set',
(['some_iterable'], None, None),
[space.newtuple([])])
_initialize_set(space, w_set, w_iterable)
def init__Frozenset(space, w_set, __args__):
w_iterable, = __args__.parse('set',
(['some_iterable'], None, None),
[space.newtuple([])])
if w_set.hash == -1:
_initialize_set(space, w_set, w_iterable)
hash__Frozenset(space, w_set)
app = gateway.applevel("""
def ne__Set_ANY(s, o):
return not s == o
def gt__Set_Set(s, o):
return s != o and s.issuperset(o)
def lt__Set_Set(s, o):
return s != o and s.issubset(o)
def repr__Set(s):
return '%s(%s)' % (s.__class__.__name__, [x for x in s])
def reduce__Set(s):
dict = getattr(s,'__dict__', None)
return (s.__class__, (tuple(s),), dict)
""", filename=__file__)
ne__Set_ANY = app.interphook("ne__Set_ANY")
ne__Frozenset_ANY = ne__Set_ANY
gt__Set_Set = app.interphook("gt__Set_Set")
gt__Set_Frozenset = gt__Set_Set
gt__Frozenset_Set = gt__Set_Set
gt__Frozenset_Frozenset = gt__Set_Set
lt__Set_Set = app.interphook("lt__Set_Set")
lt__Set_Frozenset = lt__Set_Set
lt__Frozenset_Set = lt__Set_Set
lt__Frozenset_Frozenset = lt__Set_Set
repr__Set = app.interphook('repr__Set')
repr__Frozenset = app.interphook('repr__Set')
set_reduce__Set = app.interphook('reduce__Set')
frozenset_reduce__Frozenset = app.interphook('reduce__Set')
from pypy.objspace.std import frozensettype
from pypy.objspace.std import settype
register_all(vars(), settype, frozensettype)
| Python |
"""
Reviewed 03-06-21
slice object construction tested, OK
indices method tested, OK
"""
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
from pypy.objspace.std.slicetype import _Eval_SliceIndex
class W_SliceObject(W_Object):
from pypy.objspace.std.slicetype import slice_typedef as typedef
def __init__(w_self, w_start, w_stop, w_step):
assert w_start is not None
assert w_stop is not None
assert w_step is not None
w_self.w_start = w_start
w_self.w_stop = w_stop
w_self.w_step = w_step
def unwrap(w_slice, space):
return slice(space.unwrap(w_slice.w_start), space.unwrap(w_slice.w_stop), space.unwrap(w_slice.w_step))
def indices3(w_slice, space, length):
if space.is_w(w_slice.w_step, space.w_None):
step = 1
else:
step = _Eval_SliceIndex(space, w_slice.w_step)
if step == 0:
raise OperationError(space.w_ValueError,
space.wrap("slice step cannot be zero"))
if space.is_w(w_slice.w_start, space.w_None):
if step < 0:
start = length - 1
else:
start = 0
else:
start = _Eval_SliceIndex(space, w_slice.w_start)
if start < 0:
start += length
if start < 0:
if step < 0:
start = -1
else:
start = 0
elif start >= length:
if step < 0:
start = length - 1
else:
start = length
if space.is_w(w_slice.w_stop, space.w_None):
if step < 0:
stop = -1
else:
stop = length
else:
stop = _Eval_SliceIndex(space, w_slice.w_stop)
if stop < 0:
stop += length
if stop < 0:
stop =-1
elif stop > length:
stop = length
return start, stop, step
def indices4(w_slice, space, length):
start, stop, step = w_slice.indices3(space, length)
if (step < 0 and stop >= start) or (step > 0 and start >= stop):
slicelength = 0
elif step < 0:
slicelength = (stop - start + 1) / step + 1
else:
slicelength = (stop - start - 1) / step + 1
return start, stop, step, slicelength
registerimplementation(W_SliceObject)
repr__Slice = gateway.applevel("""
def repr__Slice(aslice):
return 'slice(%r, %r, %r)' % (aslice.start, aslice.stop, aslice.step)
""", filename=__file__).interphook("repr__Slice")
def eq__Slice_Slice(space, w_slice1, w_slice2):
# We need this because CPython considers that slice1 == slice1
# is *always* True (e.g. even if slice1 was built with non-comparable
# parameters
if space.is_w(w_slice1, w_slice2):
return space.w_True
if space.eq_w(w_slice1.w_start, w_slice2.w_start) and \
space.eq_w(w_slice1.w_stop, w_slice2.w_stop) and \
space.eq_w(w_slice1.w_step, w_slice2.w_step):
return space.w_True
else:
return space.w_False
def lt__Slice_Slice(space, w_slice1, w_slice2):
if space.is_w(w_slice1, w_slice2):
return space.w_False # see comments in eq__Slice_Slice()
if space.eq_w(w_slice1.w_start, w_slice2.w_start):
if space.eq_w(w_slice1.w_stop, w_slice2.w_stop):
return space.lt(w_slice1.w_step, w_slice2.w_step)
else:
return space.lt(w_slice1.w_stop, w_slice2.w_stop)
else:
return space.lt(w_slice1.w_start, w_slice2.w_start)
# indices impl
def slice_indices__Slice_ANY(space, w_slice, w_length):
length = space.getindex_w(w_length, space.w_OverflowError)
start, stop, step = w_slice.indices3(space, length)
return space.newtuple([space.wrap(start), space.wrap(stop),
space.wrap(step)])
# register all methods
from pypy.objspace.std import slicetype
register_all(vars(), slicetype)
| Python |
from pypy.interpreter.error import OperationError, debug_print
from pypy.interpreter import baseobjspace
from pypy.interpreter import eval
from pypy.interpreter.function import Function, BuiltinFunction
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.model import W_Object, UnwrapError
from pypy.interpreter.baseobjspace import Wrappable
from pypy.interpreter.typedef import TypeDef
from pypy.interpreter import gateway, argument
# this file automatically generates non-reimplementations of CPython
# types that we do not yet implement in the standard object space
# (files being the biggy)
def fake_object(space, x):
if isinstance(x, file):
debug_print("fake-wrapping interp file %s" % x)
if isinstance(x, type):
ft = fake_type(x)
return space.gettypeobject(ft.typedef)
#debug_print("faking obj %s" % x)
ft = fake_type(type(x))
return ft(space, x)
fake_object._annspecialcase_ = "override:fake_object"
import sys
_fake_type_cache = {}
# real-to-wrapped exceptions
def wrap_exception(space):
"""NOT_RPYTHON"""
exc, value, tb = sys.exc_info()
if exc is OperationError:
raise exc, value, tb # just re-raise it
name = exc.__name__
if hasattr(space, 'w_' + name):
w_exc = getattr(space, 'w_' + name)
w_value = space.call_function(w_exc,
*[space.wrap(a) for a in value.args])
for key, value in value.__dict__.items():
if not key.startswith('_'):
space.setattr(w_value, space.wrap(key), space.wrap(value))
else:
debug_print('likely crashes because of faked exception %s: %s' % (
exc.__name__, value))
w_exc = space.wrap(exc)
w_value = space.wrap(value)
raise OperationError, OperationError(w_exc, w_value), tb
wrap_exception._annspecialcase_ = "override:ignore"
def fake_type(cpy_type):
assert type(cpy_type) is type
try:
return _fake_type_cache[cpy_type]
except KeyError:
faked_type = really_build_fake_type(cpy_type)
_fake_type_cache[cpy_type] = faked_type
return faked_type
def really_build_fake_type(cpy_type):
"NOT_RPYTHON (not remotely so!)."
#assert not issubclass(cpy_type, file), cpy_type
debug_print('faking %r'%(cpy_type,))
kw = {}
if cpy_type.__name__ == 'SRE_Pattern':
import re
import __builtin__
p = re.compile("foo")
for meth_name in p.__methods__:
kw[meth_name] = EvenMoreObscureWrapping(__builtin__.eval("lambda p,*args,**kwds: p.%s(*args,**kwds)" % meth_name))
elif cpy_type.__name__ == 'SRE_Match':
import re
import __builtin__
m = re.compile("foo").match('foo')
for meth_name in m.__methods__:
kw[meth_name] = EvenMoreObscureWrapping(__builtin__.eval("lambda m,*args,**kwds: m.%s(*args,**kwds)" % meth_name))
else:
for s, v in cpy_type.__dict__.items():
if not (cpy_type is unicode and s in ['__add__', '__contains__']):
if s != '__getattribute__' or cpy_type is type(sys) or cpy_type is type(Exception):
kw[s] = v
kw['__module__'] = cpy_type.__module__
def fake__new__(space, w_type, __args__):
args_w, kwds_w = __args__.unpack()
args = [space.unwrap(w_arg) for w_arg in args_w]
kwds = {}
for (key, w_value) in kwds_w.items():
kwds[key] = space.unwrap(w_value)
try:
r = apply(cpy_type.__new__, [cpy_type]+args, kwds)
except:
wrap_exception(space)
raise
w_obj = space.allocate_instance(W_Fake, w_type)
W_Fake.__init__(w_obj, space, r)
return w_obj
kw['__new__'] = gateway.interp2app(fake__new__,
unwrap_spec=[baseobjspace.ObjSpace,
baseobjspace.W_Root,
argument.Arguments])
if cpy_type.__base__ is not object:
assert cpy_type.__base__ is basestring
from pypy.objspace.std.basestringtype import basestring_typedef
base = basestring_typedef
else:
base = None
class W_Fake(W_Object):
typedef = StdTypeDef(
cpy_type.__name__, base, **kw)
def __init__(w_self, space, val):
w_self.val = val
def unwrap(w_self, space):
return w_self.val
# cannot write to W_Fake.__name__ in Python 2.2!
W_Fake = type(W_Object)('W_Fake%s'%(cpy_type.__name__.capitalize()),
(W_Object,),
dict(W_Fake.__dict__.items()))
W_Fake.typedef.fakedcpytype = cpy_type
return W_Fake
# ____________________________________________________________
#
# Special case for built-in functions, methods, and slot wrappers.
class CPythonFakeCode(eval.Code):
def __init__(self, cpy_callable):
eval.Code.__init__(self, getattr(cpy_callable, '__name__', '?'))
self.cpy_callable = cpy_callable
assert callable(cpy_callable), cpy_callable
def signature(self):
return [], 'args', 'kwds'
class CPythonFakeFrame(eval.Frame):
def __init__(self, space, code, w_globals=None, numlocals=-1):
self.fakecode = code
eval.Frame.__init__(self, space, w_globals, numlocals)
def getcode(self):
return self.fakecode
def setfastscope(self, scope_w):
w_args, w_kwds = scope_w
try:
self.unwrappedargs = self.space.unwrap(w_args)
self.unwrappedkwds = self.space.unwrap(w_kwds)
except UnwrapError, e:
code = self.fakecode
assert isinstance(code, CPythonFakeCode)
raise UnwrapError('calling %s: %s' % (code.cpy_callable, e))
def getfastscope(self):
raise OperationError(self.space.w_TypeError,
self.space.wrap("cannot get fastscope of a CPythonFakeFrame"))
def run(self):
code = self.fakecode
assert isinstance(code, CPythonFakeCode)
fn = code.cpy_callable
try:
result = apply(fn, self.unwrappedargs, self.unwrappedkwds)
except:
wrap_exception(self.space)
raise
return self.space.wrap(result)
class EvenMoreObscureWrapping(baseobjspace.Wrappable):
def __init__(self, val):
self.val = val
def __spacebind__(self, space):
return fake_builtin_callable(space, self.val)
def fake_builtin_callable(space, val):
return Function(space, CPythonFakeCode(val))
def fake_builtin_function(space, fn):
func = fake_builtin_callable(space, fn)
if fn.__self__ is None:
func = BuiltinFunction(func)
return func
_fake_type_cache[type(len)] = fake_builtin_function
_fake_type_cache[type(list.append)] = fake_builtin_callable
_fake_type_cache[type(type(None).__repr__)] = fake_builtin_callable
class W_FakeDescriptor(Wrappable):
# Mimics pypy.interpreter.typedef.GetSetProperty.
def __init__(self, space, d):
self.name = d.__name__
def descr_descriptor_get(space, descr, w_obj, w_cls=None):
# XXX HAAAAAAAAAAAACK (but possibly a good one)
if (space.is_w(w_obj, space.w_None)
and not space.is_w(w_cls, space.type(space.w_None))):
#print descr, w_obj, w_cls
return space.wrap(descr)
else:
name = descr.name
obj = space.unwrap(w_obj)
try:
val = getattr(obj, name) # this gives a "not RPython" warning
except:
wrap_exception(space)
raise
return space.wrap(val)
def descr_descriptor_set(space, descr, w_obj, w_value):
name = descr.name
obj = space.unwrap(w_obj)
val = space.unwrap(w_value)
try:
setattr(obj, name, val) # this gives a "not RPython" warning
except:
wrap_exception(space)
def descr_descriptor_del(space, descr, w_obj):
name = descr.name
obj = space.unwrap(w_obj)
try:
delattr(obj, name)
except:
wrap_exception(space)
W_FakeDescriptor.typedef = TypeDef(
"FakeDescriptor",
__get__ = gateway.interp2app(W_FakeDescriptor.descr_descriptor_get.im_func,
unwrap_spec = [baseobjspace.ObjSpace, W_FakeDescriptor,
baseobjspace.W_Root,
baseobjspace.W_Root]),
__set__ = gateway.interp2app(W_FakeDescriptor.descr_descriptor_set.im_func,
unwrap_spec = [baseobjspace.ObjSpace, W_FakeDescriptor,
baseobjspace.W_Root, baseobjspace.W_Root]),
__delete__ = gateway.interp2app(W_FakeDescriptor.descr_descriptor_del.im_func,
unwrap_spec = [baseobjspace.ObjSpace, W_FakeDescriptor,
baseobjspace.W_Root]),
)
if hasattr(file, 'softspace'): # CPython only
_fake_type_cache[type(file.softspace)] = W_FakeDescriptor
_fake_type_cache[type(type.__dict__['__dict__'])] = W_FakeDescriptor
| Python |
from pypy.objspace.std.objspace import *
from pypy.interpreter.function import Function, StaticMethod
from pypy.interpreter.argument import Arguments
from pypy.interpreter import gateway
from pypy.interpreter.typedef import weakref_descr
from pypy.objspace.std.stdtypedef import std_dict_descr, issubtypedef, Member
from pypy.objspace.std.objecttype import object_typedef
from pypy.objspace.std.dictproxyobject import W_DictProxyObject
from pypy.rlib.objectmodel import we_are_translated
from pypy.rlib.jit import hint
from pypy.rlib.rarithmetic import intmask, r_uint
from copy_reg import _HEAPTYPE
# from compiler/misc.py
MANGLE_LEN = 256 # magic constant from compile.c
def _mangle(name, klass):
if not name.startswith('__'):
return name
if len(name) + 2 >= MANGLE_LEN:
return name
if name.endswith('__'):
return name
try:
i = 0
while klass[i] == '_':
i = i + 1
except IndexError:
return name
klass = klass[i:]
tlen = len(klass) + len(name)
if tlen > MANGLE_LEN:
end = len(klass) + MANGLE_LEN-tlen
if end < 0:
klass = '' # annotator hint
else:
klass = klass[:end]
return "_%s%s" % (klass, name)
class VersionTag(object):
pass
class W_TypeObject(W_Object):
from pypy.objspace.std.typetype import type_typedef as typedef
lazyloaders = {} # can be overridden by specific instances
def __init__(w_self, space, name, bases_w, dict_w,
overridetypedef=None):
w_self.space = space
w_self.name = name
w_self.bases_w = bases_w
w_self.dict_w = dict_w
w_self.ensure_static__new__()
w_self.nslots = 0
w_self.needsdel = False
w_self.w_bestbase = None
w_self.weak_subclasses_w = []
# make sure there is a __doc__ in dict_w
if '__doc__' not in dict_w:
dict_w['__doc__'] = space.w_None
if overridetypedef is not None:
w_self.instancetypedef = overridetypedef
w_self.hasdict = overridetypedef.hasdict
w_self.weakrefable = overridetypedef.weakrefable
w_self.__flags__ = 0 # not a heaptype
if overridetypedef.base is not None:
w_self.w_bestbase = space.gettypeobject(overridetypedef.base)
else:
w_self.__flags__ = _HEAPTYPE
# initialize __module__ in the dict
if '__module__' not in dict_w:
try:
caller = space.getexecutioncontext().framestack.top()
except IndexError:
w_globals = w_locals = space.newdict()
else:
w_globals = caller.w_globals
w_str_name = space.wrap('__name__')
w_name = space.finditem(w_globals, w_str_name)
if w_name is not None:
dict_w['__module__'] = w_name
# find the most specific typedef
instancetypedef = object_typedef
for w_base in bases_w:
if not isinstance(w_base, W_TypeObject):
continue
if issubtypedef(w_base.instancetypedef, instancetypedef):
if instancetypedef is not w_base.instancetypedef:
instancetypedef = w_base.instancetypedef
w_self.w_bestbase = w_base
elif not issubtypedef(instancetypedef, w_base.instancetypedef):
raise OperationError(space.w_TypeError,
space.wrap("instance layout conflicts in "
"multiple inheritance"))
if not instancetypedef.acceptable_as_base_class:
raise OperationError(space.w_TypeError,
space.wrap("type '%s' is not an "
"acceptable base class" %
instancetypedef.name))
w_self.instancetypedef = instancetypedef
w_self.hasdict = False
w_self.weakrefable = False
hasoldstylebase = False
w_most_derived_base_with_slots = None
w_newstyle = None
for w_base in bases_w:
if not isinstance(w_base, W_TypeObject):
hasoldstylebase = True
continue
if not w_newstyle:
w_newstyle = w_base
if w_base.nslots != 0:
if w_most_derived_base_with_slots is None:
w_most_derived_base_with_slots = w_base
else:
if space.is_true(space.issubtype(w_base, w_most_derived_base_with_slots)):
w_most_derived_base_with_slots = w_base
elif not space.is_true(space.issubtype(w_most_derived_base_with_slots, w_base)):
raise OperationError(space.w_TypeError,
space.wrap("instance layout conflicts in "
"multiple inheritance"))
w_self.hasdict = w_self.hasdict or w_base.hasdict
w_self.needsdel = w_self.needsdel or w_base.needsdel
w_self.weakrefable = w_self.weakrefable or w_base.weakrefable
if not w_newstyle: # only classic bases
raise OperationError(space.w_TypeError,
space.wrap("a new-style class can't have only classic bases"))
if w_most_derived_base_with_slots:
nslots = w_most_derived_base_with_slots.nslots
w_self.w_bestbase = w_most_derived_base_with_slots
else:
nslots = 0
if w_self.w_bestbase is None:
w_self.w_bestbase = w_newstyle
wantdict = True
wantweakref = True
if '__slots__' in dict_w:
wantdict = False
wantweakref = False
w_slots = dict_w['__slots__']
if space.is_true(space.isinstance(w_slots, space.w_str)):
if space.int_w(space.len(w_slots)) == 0:
raise OperationError(space.w_TypeError,
space.wrap('__slots__ must be identifiers'))
slot_names_w = [w_slots]
else:
slot_names_w = space.unpackiterable(w_slots)
for w_slot_name in slot_names_w:
slot_name = space.str_w(w_slot_name)
# slot_name should be a valid identifier
if len(slot_name) == 0:
raise OperationError(space.w_TypeError,
space.wrap('__slots__ must be identifiers'))
first_char = slot_name[0]
if not first_char.isalpha() and first_char != '_':
raise OperationError(space.w_TypeError,
space.wrap('__slots__ must be identifiers'))
for c in slot_name:
if not c.isalnum() and c!= '_':
raise OperationError(space.w_TypeError,
space.wrap('__slots__ must be identifiers'))
if slot_name == '__dict__':
if wantdict or w_self.hasdict:
raise OperationError(space.w_TypeError,
space.wrap("__dict__ slot disallowed: we already got one"))
wantdict = True
elif slot_name == '__weakref__':
if wantweakref or w_self.weakrefable:
raise OperationError(space.w_TypeError,
space.wrap("__weakref__ slot disallowed: we already got one"))
wantweakref = True
else:
# create member
slot_name = _mangle(slot_name, name)
# Force interning of slot names.
slot_name = space.str_w(space.new_interned_str(slot_name))
w_self.dict_w[slot_name] = space.wrap(Member(nslots, slot_name, w_self))
nslots += 1
w_self.nslots = nslots
wantdict = wantdict or hasoldstylebase
if wantdict and not w_self.hasdict:
w_self.dict_w['__dict__'] = space.wrap(std_dict_descr)
w_self.hasdict = True
if '__del__' in dict_w:
w_self.needsdel = True
if wantweakref and not w_self.weakrefable:
w_self.dict_w['__weakref__'] = space.wrap(weakref_descr)
w_self.weakrefable = True
w_type = space.type(w_self)
if not space.is_w(w_type, space.w_type):
if space.config.objspace.std.withtypeversion:
w_self.version_tag = None
w_self.mro_w = []
mro_func = space.lookup(w_self, 'mro')
mro_func_args = Arguments(space, [w_self])
w_mro = space.call_args(mro_func, mro_func_args)
w_self.mro_w = space.unpackiterable(w_mro)
return
w_self.mro_w = w_self.compute_mro()
if space.config.objspace.std.withtypeversion:
if w_self.instancetypedef.hasdict:
w_self.version_tag = None
else:
w_self.version_tag = VersionTag()
def mutated(w_self):
space = w_self.space
assert space.config.objspace.std.withtypeversion
if w_self.version_tag is not None:
w_self.version_tag = VersionTag()
subclasses_w = w_self.get_subclasses()
for w_subclass in subclasses_w:
assert isinstance(w_subclass, W_TypeObject)
w_subclass.mutated()
def ready(w_self):
for w_base in w_self.bases_w:
if not isinstance(w_base, W_TypeObject):
continue
w_base.add_subclass(w_self)
# compute the most parent class with the same layout as us
def get_layout(w_self):
w_bestbase = w_self.w_bestbase
if w_bestbase is None: # object
return w_self
if w_self.instancetypedef is not w_bestbase.instancetypedef:
return w_self
if w_self.nslots == w_bestbase.nslots:
return w_bestbase.get_layout()
return w_self
# compute a tuple that fully describes the instance layout
def get_full_instance_layout(w_self):
w_layout = w_self.get_layout()
return (w_layout, w_self.hasdict, w_self.needsdel, w_self.weakrefable)
def compute_mro(w_self):
return compute_C3_mro(w_self.space, w_self)
def ensure_static__new__(w_self):
# special-case __new__, as in CPython:
# if it is a Function, turn it into a static method
if '__new__' in w_self.dict_w:
w_new = w_self.dict_w['__new__']
if isinstance(w_new, Function):
w_self.dict_w['__new__'] = StaticMethod(w_new)
def getdictvalue(w_self, space, w_attr):
return w_self.getdictvalue_w(space, space.str_w(w_attr))
def getdictvalue_w(w_self, space, attr):
w_value = w_self.dict_w.get(attr, None)
if w_self.lazyloaders and w_value is None:
if attr in w_self.lazyloaders:
# very clever next line: it forces the attr string
# to be interned.
w_attr = space.new_interned_str(attr)
loader = w_self.lazyloaders[attr]
del w_self.lazyloaders[attr]
w_value = loader()
if w_value is not None: # None means no such attribute
w_self.dict_w[attr] = w_value
return w_value
return w_value
def lookup(w_self, name):
# note that this doesn't call __get__ on the result at all
space = w_self.space
if space.config.objspace.std.withmethodcache:
return w_self.lookup_where_with_method_cache(name)[1]
return w_self._lookup(name)
def lookup_where(w_self, name):
space = w_self.space
if space.config.objspace.std.withmethodcache:
return w_self.lookup_where_with_method_cache(name)
return w_self._lookup_where(name)
def _lookup(w_self, key):
space = w_self.space
for w_class in w_self.mro_w:
w_value = w_class.getdictvalue_w(space, key)
if w_value is not None:
return w_value
return None
def _lookup_where(w_self, key):
# like lookup() but also returns the parent class in which the
# attribute was found
space = w_self.space
for w_class in w_self.mro_w:
w_value = w_class.getdictvalue_w(space, key)
if w_value is not None:
return w_class, w_value
return None, None
def lookup_where_with_method_cache(w_self, name):
space = w_self.space
assert space.config.objspace.std.withmethodcache
ec = space.getexecutioncontext()
version_tag = w_self.version_tag
if version_tag is None:
tup = w_self._lookup_where(name)
return tup
SHIFT = r_uint.BITS - space.config.objspace.std.methodcachesizeexp
method_hash = r_uint(intmask(id(version_tag) * hash(name))) >> SHIFT
cached_version_tag = ec.method_cache_versions[method_hash]
if cached_version_tag is version_tag:
cached_name = ec.method_cache_names[method_hash]
if cached_name is name:
tup = ec.method_cache_lookup_where[method_hash]
if space.config.objspace.std.withmethodcachecounter:
ec.method_cache_hits[name] = \
ec.method_cache_hits.get(name, 0) + 1
# print "hit", w_self, name
return tup
tup = w_self._lookup_where(name)
ec.method_cache_versions[method_hash] = version_tag
ec.method_cache_names[method_hash] = name
ec.method_cache_lookup_where[method_hash] = tup
if space.config.objspace.std.withmethodcachecounter:
ec.method_cache_misses[name] = \
ec.method_cache_misses.get(name, 0) + 1
# print "miss", w_self, name
return tup
def check_user_subclass(w_self, w_subtype):
space = w_self.space
if not isinstance(w_subtype, W_TypeObject):
raise OperationError(space.w_TypeError,
space.wrap("X is not a type object (%s)" % (
space.type(w_subtype).getname(space, '?'))))
if not space.is_true(space.issubtype(w_subtype, w_self)):
raise OperationError(space.w_TypeError,
space.wrap("%s.__new__(%s): %s is not a subtype of %s" % (
w_self.name, w_subtype.name, w_subtype.name, w_self.name)))
if w_self.instancetypedef is not w_subtype.instancetypedef:
raise OperationError(space.w_TypeError,
space.wrap("%s.__new__(%s) is not safe, use %s.__new__()" % (
w_self.name, w_subtype.name, w_subtype.name)))
return w_subtype
def _freeze_(w_self):
"NOT_RPYTHON. Forces the lazy attributes to be computed."
if 'lazyloaders' in w_self.__dict__:
for attr in w_self.lazyloaders.keys():
w_self.getdictvalue_w(w_self.space, attr)
del w_self.lazyloaders
return False
def getdict(w_self): # returning a dict-proxy!
if w_self.lazyloaders:
w_self._freeze_() # force un-lazification
space = w_self.space
dictspec = []
for key, w_value in w_self.dict_w.items():
dictspec.append((space.wrap(key), w_value))
newdic = space.newdict()
newdic.initialize_content(dictspec)
return W_DictProxyObject(newdic)
def unwrap(w_self, space):
if w_self.instancetypedef.fakedcpytype is not None:
return w_self.instancetypedef.fakedcpytype
from pypy.objspace.std.model import UnwrapError
raise UnwrapError(w_self)
def is_heaptype(w_self):
w_self = hint(w_self, deepfreeze=True)
return w_self.__flags__&_HEAPTYPE
def get_module(w_self):
space = w_self.space
if w_self.is_heaptype() and '__module__' in w_self.dict_w:
return w_self.dict_w['__module__']
else:
# for non-heap types, CPython checks for a module.name in the
# type name. That's a hack, so we're allowed to use a different
# hack...
if ('__module__' in w_self.dict_w and
space.is_true(space.isinstance(w_self.dict_w['__module__'],
space.w_str))):
return w_self.dict_w['__module__']
return space.wrap('__builtin__')
def add_subclass(w_self, w_subclass):
space = w_self.space
from pypy.module._weakref.interp__weakref import basic_weakref
w_newref = basic_weakref(space, w_subclass)
for i in range(len(w_self.weak_subclasses_w)):
w_ref = w_self.weak_subclasses_w[i]
ob = space.call_function(w_ref)
if space.is_w(ob, space.w_None):
w_self.weak_subclasses_w[i] = w_newref
return
else:
w_self.weak_subclasses_w.append(w_newref)
def remove_subclass(w_self, w_subclass):
space = w_self.space
for i in range(len(w_self.weak_subclasses_w)):
w_ref = w_self.weak_subclasses_w[i]
ob = space.call_function(w_ref)
if space.is_w(ob, w_subclass):
del w_self.weak_subclasses_w[i]
return
def get_subclasses(w_self):
space = w_self.space
subclasses_w = []
for w_ref in w_self.weak_subclasses_w:
w_ob = space.call_function(w_ref)
if not space.is_w(w_ob, space.w_None):
subclasses_w.append(w_ob)
return subclasses_w
# for now, weakref support for W_TypeObject is hard to get automatically
_lifeline_ = None
def getweakref(self):
return self._lifeline_
def setweakref(self, space, weakreflifeline):
self._lifeline_ = weakreflifeline
def call__Type(space, w_type, __args__):
# special case for type(x)
if space.is_w(w_type, space.w_type):
try:
w_obj, = __args__.fixedunpack(1)
except ValueError:
pass
else:
return space.type(w_obj)
# invoke the __new__ of the type
w_newfunc = space.getattr(w_type, space.wrap('__new__'))
w_newobject = space.call_args(w_newfunc, __args__.prepend(w_type))
# maybe invoke the __init__ of the type
if space.is_true(space.isinstance(w_newobject, w_type)):
w_descr = space.lookup(w_newobject, '__init__')
w_result = space.get_and_call_args(w_descr, w_newobject, __args__)
## if not space.is_w(w_result, space.w_None):
## raise OperationError(space.w_TypeError,
## space.wrap("__init__() should return None"))
return w_newobject
def issubtype__Type_Type(space, w_type1, w_type2):
return space.newbool(w_type2 in w_type1.mro_w)
def repr__Type(space, w_obj):
w_mod = w_obj.get_module()
if not space.is_true(space.isinstance(w_mod, space.w_str)):
mod = None
else:
mod = space.str_w(w_mod)
if not w_obj.is_heaptype() or (mod is not None and mod == '__builtin__'):
kind = 'type'
else:
kind = 'class'
if mod is not None and mod !='__builtin__':
return space.wrap("<%s '%s.%s'>" % (kind, mod, w_obj.name))
else:
return space.wrap("<%s '%s'>" % (kind, w_obj.name))
def getattr__Type_ANY(space, w_type, w_name):
name = space.str_w(w_name)
w_descr = space.lookup(w_type, name)
if w_descr is not None:
if space.is_data_descr(w_descr):
return space.get(w_descr,w_type)
w_value = w_type.lookup(name)
if w_value is not None:
# __get__(None, type): turns e.g. functions into unbound methods
return space.get(w_value, space.w_None, w_type)
if w_descr is not None:
return space.get(w_descr,w_type)
msg = "type object '%s' has no attribute '%s'" %(w_type.name, name)
raise OperationError(space.w_AttributeError, space.wrap(msg))
def setattr__Type_ANY_ANY(space, w_type, w_name, w_value):
# Note. This is exactly the same thing as descroperation.descr__setattr__,
# but it is needed at bootstrap to avoid a call to w_type.getdict() which
# would un-lazify the whole type.
if space.config.objspace.std.withtypeversion:
w_type.mutated()
name = space.str_w(w_name)
w_descr = space.lookup(w_type, name)
if w_descr is not None:
if space.is_data_descr(w_descr):
space.set(w_descr, w_type, w_value)
return
if not w_type.is_heaptype():
msg = "can't set attributes on type object '%s'" %(w_type.name,)
raise OperationError(space.w_TypeError, space.wrap(msg))
w_type.dict_w[name] = w_value
def delattr__Type_ANY(space, w_type, w_name):
if space.config.objspace.std.withtypeversion:
w_type.mutated()
if w_type.lazyloaders:
w_type._freeze_() # force un-lazification
name = space.str_w(w_name)
w_descr = space.lookup(w_type, name)
if w_descr is not None:
if space.is_data_descr(w_descr):
space.delete(w_descr, w_type)
return
if not w_type.is_heaptype():
msg = "can't delete attributes on type object '%s'" %(w_type.name,)
raise OperationError(space.w_TypeError, space.wrap(msg))
try:
del w_type.dict_w[name]
return
except KeyError:
raise OperationError(space.w_AttributeError, w_name)
# ____________________________________________________________
abstract_mro = gateway.applevel("""
def abstract_mro(klass):
# abstract/classic mro
mro = []
stack = [klass]
while stack:
klass = stack.pop()
if klass not in mro:
mro.append(klass)
if not isinstance(klass.__bases__, tuple):
raise TypeError, '__bases__ must be a tuple'
stack += klass.__bases__[::-1]
return mro
""", filename=__file__).interphook("abstract_mro")
def get_mro(space, klass):
if isinstance(klass, W_TypeObject):
return list(klass.mro_w)
else:
return space.unpackiterable(abstract_mro(space, klass))
def compute_C3_mro(space, cls):
order = []
orderlists = [get_mro(space, base) for base in cls.bases_w]
orderlists.append([cls] + cls.bases_w)
while orderlists:
for candidatelist in orderlists:
candidate = candidatelist[0]
if mro_blockinglist(candidate, orderlists) is GOODCANDIDATE:
break # good candidate
else:
return mro_error(space, orderlists) # no candidate found
assert candidate not in order
order.append(candidate)
for i in range(len(orderlists)-1, -1, -1):
if orderlists[i][0] == candidate:
del orderlists[i][0]
if len(orderlists[i]) == 0:
del orderlists[i]
return order
GOODCANDIDATE = []
def mro_blockinglist(candidate, orderlists):
for lst in orderlists:
if candidate in lst[1:]:
return lst
return GOODCANDIDATE # good candidate
def mro_error(space, orderlists):
cycle = []
candidate = orderlists[-1][0]
if candidate in orderlists[-1][1:]:
# explicit error message for this specific case
raise OperationError(space.w_TypeError,
space.wrap("duplicate base class " + candidate.getname(space,"?")))
while candidate not in cycle:
cycle.append(candidate)
nextblockinglist = mro_blockinglist(candidate, orderlists)
candidate = nextblockinglist[0]
del cycle[:cycle.index(candidate)]
cycle.append(candidate)
cycle.reverse()
names = [cls.getname(space, "?") for cls in cycle]
raise OperationError(space.w_TypeError,
space.wrap("cycle among base classes: " + ' < '.join(names)))
# ____________________________________________________________
register_all(vars())
| Python |
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.ropeobject import W_RopeObject
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std.tupleobject import W_TupleObject
from pypy.rlib.rarithmetic import intmask, ovfcheck
from pypy.module.unicodedata import unicodedb_3_2_0 as unicodedb
from pypy.objspace.std.formatting import mod_format
class W_UnicodeObject(W_Object):
from pypy.objspace.std.unicodetype import unicode_typedef as typedef
def __init__(w_self, unicodechars):
w_self._value = unicodechars
w_self.w_hash = None
def __repr__(w_self):
""" representation for debugging purposes """
return "%s(%r)" % (w_self.__class__.__name__, w_self._value)
def unwrap(w_self, space):
# For faked functions taking unicodearguments.
# Remove when we no longer need faking.
return u''.join(w_self._value)
registerimplementation(W_UnicodeObject)
# Helper for converting int/long
def unicode_to_decimal_w(space, w_unistr):
if not isinstance(w_unistr, W_UnicodeObject):
raise OperationError(space.w_TypeError,
space.wrap("expected unicode"))
unistr = w_unistr._value
result = ['\0'] * len(unistr)
digits = [ '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9']
for i in xrange(len(unistr)):
uchr = ord(unistr[i])
if unicodedb.isspace(uchr):
result[i] = ' '
continue
try:
result[i] = digits[unicodedb.decimal(uchr)]
except KeyError:
if 0 < uchr < 256:
result[i] = chr(uchr)
else:
w_encoding = space.wrap('decimal')
w_start = space.wrap(i)
w_end = space.wrap(i+1)
w_reason = space.wrap('invalid decimal Unicode string')
raise OperationError(space.w_UnicodeEncodeError,space.newtuple ([w_encoding, w_unistr, w_start, w_end, w_reason]))
return ''.join(result)
# string-to-unicode delegation
def delegate_String2Unicode(space, w_str):
w_uni = space.call_function(space.w_unicode, w_str)
assert isinstance(w_uni, W_UnicodeObject) # help the annotator!
return w_uni
def str_w__Unicode(space, w_uni):
return space.str_w(space.str(w_uni))
def unichars_w__Unicode(space, w_uni):
return w_uni._value
def str__Unicode(space, w_uni):
return space.call_method(w_uni, 'encode')
def eq__Unicode_Unicode(space, w_left, w_right):
return space.newbool(w_left._value == w_right._value)
def lt__Unicode_Unicode(space, w_left, w_right):
left = w_left._value
right = w_right._value
for i in range(min(len(left), len(right))):
if left[i] != right[i]:
return space.newbool(ord(left[i]) < ord(right[i]))
# NB. 'unichar < unichar' is not RPython at the moment
return space.newbool(len(left) < len(right))
def ord__Unicode(space, w_uni):
if len(w_uni._value) != 1:
raise OperationError(space.w_TypeError, space.wrap('ord() expected a character'))
return space.wrap(ord(w_uni._value[0]))
def getnewargs__Unicode(space, w_uni):
return space.newtuple([W_UnicodeObject(w_uni._value)])
def add__Unicode_Unicode(space, w_left, w_right):
left = w_left._value
right = w_right._value
leftlen = len(left)
rightlen = len(right)
result = [u'\0'] * (leftlen + rightlen)
for i in range(leftlen):
result[i] = left[i]
for i in range(rightlen):
result[i + leftlen] = right[i]
return W_UnicodeObject(result)
def add__String_Unicode(space, w_left, w_right):
return space.add(space.call_function(space.w_unicode, w_left) , w_right)
add__Rope_Unicode = add__String_Unicode
def add__Unicode_String(space, w_left, w_right):
return space.add(w_left, space.call_function(space.w_unicode, w_right))
add__Unicode_Rope = add__Unicode_String
def contains__String_Unicode(space, w_container, w_item):
return space.contains(space.call_function(space.w_unicode, w_container), w_item )
contains__Rope_Unicode = contains__String_Unicode
def _find(self, sub, start, end):
if len(sub) == 0:
return start
if start >= end:
return -1
for i in range(start, end - len(sub) + 1):
for j in range(len(sub)):
if self[i + j] != sub[j]:
break
else:
return i
return -1
def _rfind(self, sub, start, end):
if len(sub) == 0:
return end
if end - start < len(sub):
return -1
for i in range(end - len(sub), start - 1, -1):
for j in range(len(sub)):
if self[i + j] != sub[j]:
break
else:
return i
return -1
def contains__Unicode_Unicode(space, w_container, w_item):
item = w_item._value
container = w_container._value
return space.newbool(_find(container, item, 0, len(container)) >= 0)
def unicode_join__Unicode_ANY(space, w_self, w_list):
list = space.unpackiterable(w_list)
delim = w_self._value
totlen = 0
if len(list) == 0:
return W_UnicodeObject([])
if (len(list) == 1 and
space.is_w(space.type(list[0]), space.w_unicode)):
return list[0]
values_list = [None] * len(list)
values_list[0] = [u'\0']
for i in range(len(list)):
item = list[i]
if space.is_true(space.isinstance(item, space.w_unicode)):
pass
elif space.is_true(space.isinstance(item, space.w_str)):
item = space.call_function(space.w_unicode, item)
else:
w_msg = space.mod(space.wrap('sequence item %d: expected string or Unicode'),
space.wrap(i))
raise OperationError(space.w_TypeError, w_msg)
assert isinstance(item, W_UnicodeObject)
item = item._value
totlen += len(item)
values_list[i] = item
totlen += len(delim) * (len(values_list) - 1)
if len(values_list) == 1:
return W_UnicodeObject(values_list[0])
# Allocate result
result = [u'\0'] * totlen
first = values_list[0]
for i in range(len(first)):
result[i] = first[i]
offset = len(first)
for i in range(1, len(values_list)):
item = values_list[i]
# Add delimiter
for j in range(len(delim)):
result[offset + j] = delim[j]
offset += len(delim)
# Add item from values_list
for j in range(len(item)):
result[offset + j] = item[j]
offset += len(item)
return W_UnicodeObject(result)
def hash__Unicode(space, w_uni):
if w_uni.w_hash is None:
# hrmpf
chars = w_uni._value
if len(chars) == 0:
return space.wrap(0)
if space.config.objspace.std.withrope:
x = 0
for c in chars:
x = intmask((1000003 * x) + ord(c))
x <<= 1
x ^= len(chars)
x ^= ord(chars[0])
h = intmask(x)
else:
x = ord(chars[0]) << 7
for c in chars:
x = intmask((1000003 * x) ^ ord(c))
h = intmask(x ^ len(chars))
if h == -1:
h = -2
w_uni.w_hash = space.wrap(h)
return w_uni.w_hash
def len__Unicode(space, w_uni):
return space.wrap(len(w_uni._value))
def getitem__Unicode_ANY(space, w_uni, w_index):
ival = space.getindex_w(w_index, space.w_IndexError, "string index")
uni = w_uni._value
ulen = len(uni)
if ival < 0:
ival += ulen
if ival < 0 or ival >= ulen:
exc = space.call_function(space.w_IndexError,
space.wrap("unicode index out of range"))
raise OperationError(space.w_IndexError, exc)
return W_UnicodeObject([uni[ival]])
def getitem__Unicode_Slice(space, w_uni, w_slice):
uni = w_uni._value
length = len(uni)
start, stop, step, sl = w_slice.indices4(space, length)
if sl == 0:
r = []
elif step == 1:
assert start >= 0 and stop >= 0
r = uni[start:stop]
else:
r = [uni[start + i*step] for i in range(sl)]
return W_UnicodeObject(r)
def mul__Unicode_ANY(space, w_uni, w_times):
try:
times = space.getindex_w(w_times, space.w_OverflowError)
except OperationError, e:
if e.match(space, space.w_TypeError):
raise FailedToImplement
raise
chars = w_uni._value
charlen = len(chars)
if times <= 0 or charlen == 0:
return W_UnicodeObject([])
if times == 1:
return space.call_function(space.w_unicode, w_uni)
if charlen == 1:
return W_UnicodeObject([w_uni._value[0]] * times)
try:
result_size = ovfcheck(charlen * times)
result = [u'\0'] * result_size
except (OverflowError, MemoryError):
raise OperationError(space.w_OverflowError, space.wrap('repeated string is too long'))
for i in range(times):
offset = i * charlen
for j in range(charlen):
result[offset + j] = chars[j]
return W_UnicodeObject(result)
def mul__ANY_Unicode(space, w_times, w_uni):
return mul__Unicode_ANY(space, w_uni, w_times)
def _isspace(uchar):
return unicodedb.isspace(ord(uchar))
def unicode_isspace__Unicode(space, w_unicode):
if len(w_unicode._value) == 0:
return space.w_False
for uchar in w_unicode._value:
if not unicodedb.isspace(ord(uchar)):
return space.w_False
return space.w_True
def unicode_isalpha__Unicode(space, w_unicode):
if len(w_unicode._value) == 0:
return space.w_False
for uchar in w_unicode._value:
if not unicodedb.isalpha(ord(uchar)):
return space.w_False
return space.w_True
def unicode_isalnum__Unicode(space, w_unicode):
if len(w_unicode._value) == 0:
return space.w_False
for uchar in w_unicode._value:
if not unicodedb.isalnum(ord(uchar)):
return space.w_False
return space.w_True
def unicode_isdecimal__Unicode(space, w_unicode):
if len(w_unicode._value) == 0:
return space.w_False
for uchar in w_unicode._value:
if not unicodedb.isdecimal(ord(uchar)):
return space.w_False
return space.w_True
def unicode_isdigit__Unicode(space, w_unicode):
if len(w_unicode._value) == 0:
return space.w_False
for uchar in w_unicode._value:
if not unicodedb.isdigit(ord(uchar)):
return space.w_False
return space.w_True
def unicode_isnumeric__Unicode(space, w_unicode):
if len(w_unicode._value) == 0:
return space.w_False
for uchar in w_unicode._value:
if not unicodedb.isnumeric(ord(uchar)):
return space.w_False
return space.w_True
def unicode_islower__Unicode(space, w_unicode):
cased = False
for uchar in w_unicode._value:
if (unicodedb.isupper(ord(uchar)) or
unicodedb.istitle(ord(uchar))):
return space.w_False
if not cased and unicodedb.islower(ord(uchar)):
cased = True
return space.newbool(cased)
def unicode_isupper__Unicode(space, w_unicode):
cased = False
for uchar in w_unicode._value:
if (unicodedb.islower(ord(uchar)) or
unicodedb.istitle(ord(uchar))):
return space.w_False
if not cased and unicodedb.isupper(ord(uchar)):
cased = True
return space.newbool(cased)
def unicode_istitle__Unicode(space, w_unicode):
cased = False
previous_is_cased = False
for uchar in w_unicode._value:
if (unicodedb.isupper(ord(uchar)) or
unicodedb.istitle(ord(uchar))):
if previous_is_cased:
return space.w_False
previous_is_cased = cased = True
elif unicodedb.islower(ord(uchar)):
if not previous_is_cased:
return space.w_False
previous_is_cased = cased = True
else:
previous_is_cased = False
return space.newbool(cased)
def _strip(space, w_self, w_chars, left, right):
"internal function called by str_xstrip methods"
u_self = w_self._value
u_chars = w_chars._value
lpos = 0
rpos = len(u_self)
if left:
while lpos < rpos and u_self[lpos] in u_chars:
lpos += 1
if right:
while rpos > lpos and u_self[rpos - 1] in u_chars:
rpos -= 1
result = [u'\0'] * (rpos - lpos)
for i in range(rpos - lpos):
result[i] = u_self[lpos + i]
return W_UnicodeObject(result)
def _strip_none(space, w_self, left, right):
"internal function called by str_xstrip methods"
u_self = w_self._value
lpos = 0
rpos = len(u_self)
if left:
while lpos < rpos and _isspace(u_self[lpos]):
lpos += 1
if right:
while rpos > lpos and _isspace(u_self[rpos - 1]):
rpos -= 1
result = [u'\0'] * (rpos - lpos)
for i in range(rpos - lpos):
result[i] = u_self[lpos + i]
return W_UnicodeObject(result)
def unicode_strip__Unicode_None(space, w_self, w_chars):
return _strip_none(space, w_self, 1, 1)
def unicode_strip__Unicode_Unicode(space, w_self, w_chars):
return _strip(space, w_self, w_chars, 1, 1)
def unicode_strip__Unicode_String(space, w_self, w_chars):
return space.call_method(w_self, 'strip',
space.call_function(space.w_unicode, w_chars))
unicode_strip__Unicode_Rope = unicode_strip__Unicode_String
def unicode_lstrip__Unicode_None(space, w_self, w_chars):
return _strip_none(space, w_self, 1, 0)
def unicode_lstrip__Unicode_Unicode(space, w_self, w_chars):
return _strip(space, w_self, w_chars, 1, 0)
def unicode_lstrip__Unicode_String(space, w_self, w_chars):
return space.call_method(w_self, 'lstrip',
space.call_function(space.w_unicode, w_chars))
unicode_lstrip__Unicode_Rope = unicode_lstrip__Unicode_String
def unicode_rstrip__Unicode_None(space, w_self, w_chars):
return _strip_none(space, w_self, 0, 1)
def unicode_rstrip__Unicode_Unicode(space, w_self, w_chars):
return _strip(space, w_self, w_chars, 0, 1)
def unicode_rstrip__Unicode_String(space, w_self, w_chars):
return space.call_method(w_self, 'rstrip',
space.call_function(space.w_unicode, w_chars))
unicode_rstrip__Unicode_Rope = unicode_rstrip__Unicode_String
def unicode_capitalize__Unicode(space, w_self):
input = w_self._value
if len(input) == 0:
return W_UnicodeObject([])
result = [u'\0'] * len(input)
result[0] = unichr(unicodedb.toupper(ord(input[0])))
for i in range(1, len(input)):
result[i] = unichr(unicodedb.tolower(ord(input[i])))
return W_UnicodeObject(result)
def unicode_title__Unicode(space, w_self):
input = w_self._value
if len(input) == 0:
return w_self
result = [u'\0'] * len(input)
previous_is_cased = 0
for i in range(len(input)):
unichar = ord(input[i])
if previous_is_cased:
result[i] = unichr(unicodedb.tolower(unichar))
else:
result[i] = unichr(unicodedb.totitle(unichar))
previous_is_cased = unicodedb.iscased(unichar)
return W_UnicodeObject(result)
def unicode_lower__Unicode(space, w_self):
input = w_self._value
result = [u'\0'] * len(input)
for i in range(len(input)):
result[i] = unichr(unicodedb.tolower(ord(input[i])))
return W_UnicodeObject(result)
def unicode_upper__Unicode(space, w_self):
input = w_self._value
result = [u'\0'] * len(input)
for i in range(len(input)):
result[i] = unichr(unicodedb.toupper(ord(input[i])))
return W_UnicodeObject(result)
def unicode_swapcase__Unicode(space, w_self):
input = w_self._value
result = [u'\0'] * len(input)
for i in range(len(input)):
unichar = ord(input[i])
if unicodedb.islower(unichar):
result[i] = unichr(unicodedb.toupper(unichar))
elif unicodedb.isupper(unichar):
result[i] = unichr(unicodedb.tolower(unichar))
else:
result[i] = input[i]
return W_UnicodeObject(result)
def _normalize_index(length, index):
if index < 0:
index += length
if index < 0:
index = 0
elif index > length:
index = length
return index
def unicode_endswith__Unicode_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
self = w_self._value
start = _normalize_index(len(self), space.int_w(w_start))
end = _normalize_index(len(self), space.int_w(w_end))
substr = w_substr._value
substr_len = len(substr)
if end - start < substr_len:
return space.w_False # substring is too long
start = end - substr_len
for i in range(substr_len):
if self[start + i] != substr[i]:
return space.w_False
return space.w_True
def unicode_startswith__Unicode_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
self = w_self._value
start = _normalize_index(len(self), space.int_w(w_start))
end = _normalize_index(len(self), space.int_w(w_end))
substr = w_substr._value
substr_len = len(substr)
if end - start < substr_len:
return space.w_False # substring is too long
for i in range(substr_len):
if self[start + i] != substr[i]:
return space.w_False
return space.w_True
def _to_unichar_w(space, w_char):
try:
w_unichar = unicodetype.unicode_from_object(space, w_char)
except OperationError, e:
if e.match(space, space.w_TypeError):
msg = 'The fill character cannot be converted to Unicode'
raise OperationError(space.w_TypeError, space.wrap(msg))
else:
raise
if space.int_w(space.len(w_unichar)) != 1:
raise OperationError(space.w_TypeError, space.wrap('The fill character must be exactly one character long'))
unichar = unichr(space.int_w(space.ord(w_unichar)))
return unichar
def unicode_center__Unicode_ANY_ANY(space, w_self, w_width, w_fillchar):
self = w_self._value
width = space.int_w(w_width)
fillchar = _to_unichar_w(space, w_fillchar)
padding = width - len(self)
if padding < 0:
return space.call_function(space.w_unicode, w_self)
leftpad = padding // 2 + (padding & width & 1)
result = [fillchar] * width
for i in range(len(self)):
result[leftpad + i] = self[i]
return W_UnicodeObject(result)
def unicode_ljust__Unicode_ANY_ANY(space, w_self, w_width, w_fillchar):
self = w_self._value
width = space.int_w(w_width)
fillchar = _to_unichar_w(space, w_fillchar)
padding = width - len(self)
if padding < 0:
return space.call_function(space.w_unicode, w_self)
result = [fillchar] * width
for i in range(len(self)):
result[i] = self[i]
return W_UnicodeObject(result)
def unicode_rjust__Unicode_ANY_ANY(space, w_self, w_width, w_fillchar):
self = w_self._value
width = space.int_w(w_width)
fillchar = _to_unichar_w(space, w_fillchar)
padding = width - len(self)
if padding < 0:
return space.call_function(space.w_unicode, w_self)
result = [fillchar] * width
for i in range(len(self)):
result[padding + i] = self[i]
return W_UnicodeObject(result)
def unicode_zfill__Unicode_ANY(space, w_self, w_width):
self = w_self._value
width = space.int_w(w_width)
if len(self) == 0:
return W_UnicodeObject([u'0'] * width)
padding = width - len(self)
if padding <= 0:
return space.call_function(space.w_unicode, w_self)
result = [u'0'] * width
for i in range(len(self)):
result[padding + i] = self[i]
# Move sign to first position
if self[0] in (u'+', u'-'):
result[0] = self[0]
result[padding] = u'0'
return W_UnicodeObject(result)
def unicode_splitlines__Unicode_ANY(space, w_self, w_keepends):
self = w_self._value
keepends = 0
if space.int_w(w_keepends):
keepends = 1
if len(self) == 0:
return space.newlist([])
start = 0
end = len(self)
pos = 0
lines = []
while pos < end:
if unicodedb.islinebreak(ord(self[pos])):
if (self[pos] == u'\r' and pos + 1 < end and
self[pos + 1] == u'\n'):
# Count CRLF as one linebreak
lines.append(W_UnicodeObject(self[start:pos + keepends * 2]))
pos += 1
else:
lines.append(W_UnicodeObject(self[start:pos + keepends]))
pos += 1
start = pos
else:
pos += 1
if not unicodedb.islinebreak(ord(self[end - 1])):
lines.append(W_UnicodeObject(self[start:]))
return space.newlist(lines)
def unicode_find__Unicode_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
self = w_self._value
start = _normalize_index(len(self), space.int_w(w_start))
end = _normalize_index(len(self), space.int_w(w_end))
substr = w_substr._value
return space.wrap(_find(self, substr, start, end))
def unicode_rfind__Unicode_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
self = w_self._value
start = _normalize_index(len(self), space.int_w(w_start))
end = _normalize_index(len(self), space.int_w(w_end))
substr = w_substr._value
return space.wrap(_rfind(self, substr, start, end))
def unicode_index__Unicode_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
self = w_self._value
start = _normalize_index(len(self), space.int_w(w_start))
end = _normalize_index(len(self), space.int_w(w_end))
substr = w_substr._value
index = _find(self, substr, start, end)
if index < 0:
raise OperationError(space.w_ValueError,
space.wrap('substring not found'))
return space.wrap(index)
def unicode_rindex__Unicode_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
self = w_self._value
start = _normalize_index(len(self), space.int_w(w_start))
end = _normalize_index(len(self), space.int_w(w_end))
substr = w_substr._value
index = _rfind(self, substr, start, end)
if index < 0:
raise OperationError(space.w_ValueError,
space.wrap('substring not found'))
return space.wrap(index)
def unicode_count__Unicode_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
self = w_self._value
start = _normalize_index(len(self), space.int_w(w_start))
end = _normalize_index(len(self), space.int_w(w_end))
substr = w_substr._value
count = 0
while start <= end:
index = _find(self, substr, start, end)
if index < 0:
break
start = index + 1
count += 1
return space.wrap(count)
def unicode_split__Unicode_None_ANY(space, w_self, w_none, w_maxsplit):
self = w_self._value
maxsplit = space.int_w(w_maxsplit)
parts = []
if len(self) == 0:
return space.newlist([])
start = 0
end = len(self)
inword = 0
while maxsplit != 0 and start < end:
index = start
for index in range(start, end):
if _isspace(self[index]):
break
else:
inword = 1
else:
break
if inword == 1:
parts.append(W_UnicodeObject(self[start:index]))
maxsplit -= 1
# Eat whitespace
for start in range(index + 1, end):
if not _isspace(self[start]):
break
else:
return space.newlist(parts)
parts.append(W_UnicodeObject(self[start:]))
return space.newlist(parts)
def unicode_split__Unicode_Unicode_ANY(space, w_self, w_delim, w_maxsplit):
self = w_self._value
delim = w_delim._value
maxsplit = space.int_w(w_maxsplit)
delim_len = len(delim)
if delim_len == 0:
raise OperationError(space.w_ValueError,
space.wrap('empty separator'))
parts = []
start = 0
end = len(self)
while maxsplit != 0:
index = _find(self, delim, start, end)
if index < 0:
break
parts.append(W_UnicodeObject(self[start:index]))
start = index + delim_len
maxsplit -= 1
parts.append(W_UnicodeObject(self[start:]))
return space.newlist(parts)
def unicode_rsplit__Unicode_None_ANY(space, w_self, w_none, w_maxsplit):
self = w_self._value
maxsplit = space.int_w(w_maxsplit)
parts = []
if len(self) == 0:
return space.newlist([])
start = 0
end = len(self)
inword = 0
while maxsplit != 0 and start < end:
index = end
for index in range(end-1, start-1, -1):
if _isspace(self[index]):
break
else:
inword = 1
else:
break
if inword == 1:
parts.append(W_UnicodeObject(self[index+1:end]))
maxsplit -= 1
# Eat whitespace
for end in range(index, start-1, -1):
if not _isspace(self[end-1]):
break
else:
return space.newlist(parts)
parts.append(W_UnicodeObject(self[:end]))
parts.reverse()
return space.newlist(parts)
def unicode_rsplit__Unicode_Unicode_ANY(space, w_self, w_delim, w_maxsplit):
self = w_self._value
delim = w_delim._value
maxsplit = space.int_w(w_maxsplit)
delim_len = len(delim)
if delim_len == 0:
raise OperationError(space.w_ValueError,
space.wrap('empty separator'))
parts = []
if len(self) == 0:
return space.newlist([])
start = 0
end = len(self)
while maxsplit != 0:
index = _rfind(self, delim, 0, end)
if index < 0:
break
parts.append(W_UnicodeObject(self[index+delim_len:end]))
end = index
maxsplit -= 1
parts.append(W_UnicodeObject(self[:end]))
parts.reverse()
return space.newlist(parts)
def _split(space, self, maxsplit):
if maxsplit == 0:
return [W_UnicodeObject(self)]
index = 0
end = len(self)
parts = [W_UnicodeObject([])]
maxsplit -= 1
while maxsplit != 0:
if index >= end:
break
parts.append(W_UnicodeObject([self[index]]))
index += 1
maxsplit -= 1
parts.append(W_UnicodeObject(self[index:]))
return parts
def unicode_replace__Unicode_Unicode_Unicode_ANY(space, w_self, w_old,
w_new, w_maxsplit):
if len(w_old._value):
w_parts = space.call_method(w_self, 'split', w_old, w_maxsplit)
else:
self = w_self._value
maxsplit = space.int_w(w_maxsplit)
w_parts = space.newlist(_split(space, self, maxsplit))
return space.call_method(w_new, 'join', w_parts)
app = gateway.applevel(r'''
import sys
def unicode_expandtabs__Unicode_ANY(self, tabsize):
parts = self.split(u'\t')
result = [ parts[0] ]
prevsize = 0
for ch in parts[0]:
prevsize += 1
if ch in (u"\n", u"\r"):
prevsize = 0
for i in range(1, len(parts)):
pad = tabsize - prevsize % tabsize
result.append(u' ' * pad)
nextpart = parts[i]
result.append(nextpart)
prevsize = 0
for ch in nextpart:
prevsize += 1
if ch in (u"\n", u"\r"):
prevsize = 0
return u''.join(result)
def unicode_translate__Unicode_ANY(self, table):
result = []
for unichar in self:
try:
newval = table[ord(unichar)]
except KeyError:
result.append(unichar)
else:
if newval is None:
continue
elif isinstance(newval, int):
if newval < 0 or newval > sys.maxunicode:
raise TypeError("character mapping must be in range(0x%x)"%(sys.maxunicode + 1,))
result.append(unichr(newval))
elif isinstance(newval, unicode):
result.append(newval)
else:
raise TypeError("character mapping must return integer, None or unicode")
return ''.join(result)
def unicode_encode__Unicode_ANY_ANY(unistr, encoding=None, errors=None):
import codecs, sys
if encoding is None:
encoding = sys.getdefaultencoding()
encoder = codecs.getencoder(encoding)
if errors is None:
retval, lenght = encoder(unistr)
else:
retval, length = encoder(unistr, errors)
if not isinstance(retval,str):
raise TypeError("encoder did not return a string object (type=%s)" %
type(retval).__name__)
return retval
# XXX: These should probably be written on interplevel
def unicode_partition__Unicode_Unicode(unistr, unisub):
pos = unistr.find(unisub)
if pos == -1:
return (unistr, u'', u'')
else:
return (unistr[:pos], unisub, unistr[pos+len(unisub):])
def unicode_rpartition__Unicode_Unicode(unistr, unisub):
pos = unistr.rfind(unisub)
if pos == -1:
return (u'', u'', unistr)
else:
return (unistr[:pos], unisub, unistr[pos+len(unisub):])
def unicode_startswith__Unicode_Tuple_ANY_ANY(unistr, prefixes, start, end):
for prefix in prefixes:
if unistr.startswith(prefix):
return True
return False
def unicode_endswith__Unicode_Tuple_ANY_ANY(unistr, suffixes, start, end):
for suffix in suffixes:
if unistr.endswith(suffix):
return True
return False
''')
unicode_expandtabs__Unicode_ANY = app.interphook('unicode_expandtabs__Unicode_ANY')
unicode_translate__Unicode_ANY = app.interphook('unicode_translate__Unicode_ANY')
unicode_encode__Unicode_ANY_ANY = app.interphook('unicode_encode__Unicode_ANY_ANY')
unicode_partition__Unicode_Unicode = app.interphook('unicode_partition__Unicode_Unicode')
unicode_rpartition__Unicode_Unicode = app.interphook('unicode_rpartition__Unicode_Unicode')
unicode_startswith__Unicode_Tuple_ANY_ANY = app.interphook('unicode_startswith__Unicode_Tuple_ANY_ANY')
unicode_endswith__Unicode_Tuple_ANY_ANY = app.interphook('unicode_endswith__Unicode_Tuple_ANY_ANY')
# Move this into the _codecs module as 'unicodeescape_string (Remember to cater for quotes)'
def repr__Unicode(space, w_unicode):
hexdigits = "0123456789abcdef"
chars = w_unicode._value
size = len(chars)
singlequote = doublequote = False
for c in chars:
if c == u'\'':
singlequote = True
elif c == u'"':
doublequote = True
if singlequote and not doublequote:
quote = '"'
else:
quote = '\''
result = ['\0'] * (2 + size*6 + 1)
result[0] = 'u'
result[1] = quote
i = 2
j = 0
while j<len(chars):
ch = chars[j]
## if ch == u"'":
## quote ='''"'''
## result[1] = quote
## result[i] = '\''
## #result[i + 1] = "'"
## i += 1
## continue
code = ord(ch)
if code >= 0x10000:
# Resize if needed
if i + 12 > len(result):
result.extend(['\0'] * 100)
result[i] = '\\'
result[i + 1] = "U"
result[i + 2] = hexdigits[(code >> 28) & 0xf]
result[i + 3] = hexdigits[(code >> 24) & 0xf]
result[i + 4] = hexdigits[(code >> 20) & 0xf]
result[i + 5] = hexdigits[(code >> 16) & 0xf]
result[i + 6] = hexdigits[(code >> 12) & 0xf]
result[i + 7] = hexdigits[(code >> 8) & 0xf]
result[i + 8] = hexdigits[(code >> 4) & 0xf]
result[i + 9] = hexdigits[(code >> 0) & 0xf]
i += 10
j += 1
continue
if code >= 0xD800 and code < 0xDC00:
if j < size - 1:
ch2 = chars[j+1]
code2 = ord(ch2)
if code2 >= 0xDC00 and code2 <= 0xDFFF:
code = (((code & 0x03FF) << 10) | (code2 & 0x03FF)) + 0x00010000
if i + 12 > len(result):
result.extend(['\0'] * 100)
result[i] = '\\'
result[i + 1] = "U"
result[i + 2] = hexdigits[(code >> 28) & 0xf]
result[i + 3] = hexdigits[(code >> 24) & 0xf]
result[i + 4] = hexdigits[(code >> 20) & 0xf]
result[i + 5] = hexdigits[(code >> 16) & 0xf]
result[i + 6] = hexdigits[(code >> 12) & 0xf]
result[i + 7] = hexdigits[(code >> 8) & 0xf]
result[i + 8] = hexdigits[(code >> 4) & 0xf]
result[i + 9] = hexdigits[(code >> 0) & 0xf]
i += 10
j += 2
continue
if code >= 0x100:
result[i] = '\\'
result[i + 1] = "u"
result[i + 2] = hexdigits[(code >> 12) & 0xf]
result[i + 3] = hexdigits[(code >> 8) & 0xf]
result[i + 4] = hexdigits[(code >> 4) & 0xf]
result[i + 5] = hexdigits[(code >> 0) & 0xf]
i += 6
j += 1
continue
if code == ord('\\') or code == ord(quote):
result[i] = '\\'
result[i + 1] = chr(code)
i += 2
j += 1
continue
if code == ord('\t'):
result[i] = '\\'
result[i + 1] = "t"
i += 2
j += 1
continue
if code == ord('\r'):
result[i] = '\\'
result[i + 1] = "r"
i += 2
j += 1
continue
if code == ord('\n'):
result[i] = '\\'
result[i + 1] = "n"
i += 2
j += 1
continue
if code < ord(' ') or code >= 0x7f:
result[i] = '\\'
result[i + 1] = "x"
result[i + 2] = hexdigits[(code >> 4) & 0xf]
result[i + 3] = hexdigits[(code >> 0) & 0xf]
i += 4
j += 1
continue
result[i] = chr(code)
i += 1
j += 1
result[i] = quote
i += 1
return space.wrap(''.join(result[:i]))
#repr__Unicode = app.interphook('repr__Unicode') # uncomment when repr code is moved to _codecs
def mod__Unicode_ANY(space, w_format, w_values):
return mod_format(space, w_format, w_values, do_unicode=True)
import unicodetype
register_all(vars(), unicodetype)
# str.strip(unicode) needs to convert self to unicode and call unicode.strip
# we use the following magic to register strip_string_unicode as a String multimethod.
class str_methods:
import stringtype
W_UnicodeObject = W_UnicodeObject
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.ropeobject import W_RopeObject
def str_strip__String_Unicode(space, w_self, w_chars):
return space.call_method(space.call_function(space.w_unicode, w_self),
'strip', w_chars)
str_strip__Rope_Unicode = str_strip__String_Unicode
def str_lstrip__String_Unicode(space, w_self, w_chars):
return space.call_method(space.call_function(space.w_unicode, w_self),
'lstrip', w_chars)
str_lstrip__Rope_Unicode = str_lstrip__String_Unicode
def str_rstrip__String_Unicode(space, w_self, w_chars):
return space.call_method(space.call_function(space.w_unicode, w_self),
'rstrip', w_chars)
str_rstrip__Rope_Unicode = str_rstrip__String_Unicode
def str_count__String_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
return space.call_method(space.call_function(space.w_unicode, w_self),
'count', w_substr, w_start, w_end)
str_count__Rope_Unicode_ANY_ANY = str_count__String_Unicode_ANY_ANY
def str_find__String_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
return space.call_method(space.call_function(space.w_unicode, w_self),
'find', w_substr, w_start, w_end)
str_find__Rope_Unicode_ANY_ANY = str_find__String_Unicode_ANY_ANY
def str_rfind__String_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
return space.call_method(space.call_function(space.w_unicode, w_self),
'rfind', w_substr, w_start, w_end)
str_rfind__Rope_Unicode_ANY_ANY = str_rfind__String_Unicode_ANY_ANY
def str_index__String_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
return space.call_method(space.call_function(space.w_unicode, w_self),
'index', w_substr, w_start, w_end)
str_index__Rope_Unicode_ANY_ANY = str_index__String_Unicode_ANY_ANY
def str_rindex__String_Unicode_ANY_ANY(space, w_self, w_substr, w_start, w_end):
return space.call_method(space.call_function(space.w_unicode, w_self),
'rindex', w_substr, w_start, w_end)
str_rindex__Rope_Unicode_ANY_ANY = str_rindex__String_Unicode_ANY_ANY
def str_replace__String_Unicode_Unicode_ANY(space, w_self, w_old, w_new, w_maxsplit):
return space.call_method(space.call_function(space.w_unicode, w_self),
'replace', w_old, w_new, w_maxsplit)
str_replace__Rope_Unicode_Unicode_ANY = str_replace__String_Unicode_Unicode_ANY
def str_split__String_Unicode_ANY(space, w_self, w_delim, w_maxsplit):
return space.call_method(space.call_function(space.w_unicode, w_self),
'split', w_delim, w_maxsplit)
str_split__Rope_Unicode_ANY = str_split__String_Unicode_ANY
def str_rsplit__String_Unicode_ANY(space, w_self, w_delim, w_maxsplit):
return space.call_method(space.call_function(space.w_unicode, w_self),
'rsplit', w_delim, w_maxsplit)
str_rsplit__Rope_Unicode_ANY = str_rsplit__String_Unicode_ANY
register_all(vars(), stringtype)
| Python |
from pypy.objspace.std.stdtypedef import *
# ____________________________________________________________
def descr_seqiter__reduce__(w_self, space):
"""
XXX to do: remove this __reduce__ method and do
a registration with copy_reg, instead.
"""
from pypy.objspace.std.iterobject import W_SeqIterObject
assert isinstance(w_self, W_SeqIterObject)
from pypy.interpreter.mixedmodule import MixedModule
w_mod = space.getbuiltinmodule('_pickle_support')
mod = space.interp_w(MixedModule, w_mod)
new_inst = mod.get('seqiter_new')
tup = [w_self.w_seq, space.wrap(w_self.index)]
return space.newtuple([new_inst, space.newtuple(tup)])
# ____________________________________________________________
def descr_reverseseqiter__reduce__(w_self, space):
"""
XXX to do: remove this __reduce__ method and do
a registration with copy_reg, instead.
"""
from pypy.objspace.std.iterobject import W_ReverseSeqIterObject
assert isinstance(w_self, W_ReverseSeqIterObject)
from pypy.interpreter.mixedmodule import MixedModule
w_mod = space.getbuiltinmodule('_pickle_support')
mod = space.interp_w(MixedModule, w_mod)
new_inst = mod.get('reverseseqiter_new')
tup = [w_self.w_seq, space.wrap(w_self.index)]
return space.newtuple([new_inst, space.newtuple(tup)])
# ____________________________________________________________
iter_typedef = StdTypeDef("sequenceiterator",
__doc__ = '''iter(collection) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.''',
__reduce__ = gateway.interp2app(descr_seqiter__reduce__,
unwrap_spec=[gateway.W_Root, gateway.ObjSpace]),
)
reverse_iter_typedef = StdTypeDef("reversesequenceiterator",
__reduce__ = gateway.interp2app(descr_reverseseqiter__reduce__,
unwrap_spec=[gateway.W_Root, gateway.ObjSpace]),
)
| Python |
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.objspace.std.longobject import W_LongObject
from pypy.rlib.rarithmetic import ovfcheck_float_to_int, intmask, isinf
from pypy.rlib.rarithmetic import formatd
import math
from pypy.objspace.std.intobject import W_IntObject
class W_FloatObject(W_Object):
"""This is a reimplementation of the CPython "PyFloatObject"
it is assumed that the constructor takes a real Python float as
an argument"""
from pypy.objspace.std.floattype import float_typedef as typedef
def __init__(w_self, floatval):
w_self.floatval = floatval
def unwrap(w_self, space):
return w_self.floatval
def __repr__(self):
return "<W_FloatObject(%f)>" % self.floatval
registerimplementation(W_FloatObject)
# bool-to-float delegation
def delegate_Bool2Float(space, w_bool):
return W_FloatObject(float(w_bool.boolval))
# int-to-float delegation
def delegate_Int2Float(space, w_intobj):
return W_FloatObject(float(w_intobj.intval))
# long-to-float delegation
def delegate_Long2Float(space, w_longobj):
try:
return W_FloatObject(w_longobj.tofloat())
except OverflowError:
raise OperationError(space.w_OverflowError,
space.wrap("long int too large to convert to float"))
# float__Float is supposed to do nothing, unless it has
# a derived float object, where it should return
# an exact one.
def float__Float(space, w_float1):
if space.is_w(space.type(w_float1), space.w_float):
return w_float1
a = w_float1.floatval
return W_FloatObject(a)
def int__Float(space, w_value):
try:
value = ovfcheck_float_to_int(w_value.floatval)
except OverflowError:
return space.long(w_value)
else:
return space.newint(value)
def long__Float(space, w_floatobj):
try:
return W_LongObject.fromfloat(w_floatobj.floatval)
except OverflowError:
raise OperationError(space.w_OverflowError,
space.wrap("cannot convert float infinity to long"))
def float_w__Float(space, w_float):
return w_float.floatval
def should_not_look_like_an_int(s):
for c in s:
if c in '.eE':
break
else:
s += '.0'
return s
def repr__Float(space, w_float):
x = w_float.floatval
s = formatd("%.17g", x)
return space.wrap(should_not_look_like_an_int(s))
def str__Float(space, w_float):
x = w_float.floatval
s = formatd("%.12g", x)
return space.wrap(should_not_look_like_an_int(s))
def lt__Float_Float(space, w_float1, w_float2):
i = w_float1.floatval
j = w_float2.floatval
return space.newbool( i < j )
def le__Float_Float(space, w_float1, w_float2):
i = w_float1.floatval
j = w_float2.floatval
return space.newbool( i <= j )
def eq__Float_Float(space, w_float1, w_float2):
i = w_float1.floatval
j = w_float2.floatval
return space.newbool( i == j )
def ne__Float_Float(space, w_float1, w_float2):
i = w_float1.floatval
j = w_float2.floatval
return space.newbool( i != j )
def gt__Float_Float(space, w_float1, w_float2):
i = w_float1.floatval
j = w_float2.floatval
return space.newbool( i > j )
def ge__Float_Float(space, w_float1, w_float2):
i = w_float1.floatval
j = w_float2.floatval
return space.newbool( i >= j )
# for overflowing comparisons between longs and floats
# XXX we might have to worry (later) about eq__Float_Int, for the case
# where int->float conversion may lose precision :-(
def eq__Float_Long(space, w_float1, w_long2):
# XXX naive implementation
x = w_float1.floatval
if isinf(x) or math.floor(x) != x:
return space.w_False
try:
w_long1 = W_LongObject.fromfloat(x)
except OverflowError:
return space.w_False
return space.eq(w_long1, w_long2)
def eq__Long_Float(space, w_long1, w_float2):
return eq__Float_Long(space, w_float2, w_long1)
def ne__Float_Long(space, w_float1, w_long2):
return space.not_(eq__Float_Long(space, w_float1, w_long2))
def ne__Long_Float(space, w_long1, w_float2):
return space.not_(eq__Float_Long(space, w_float2, w_long1))
def lt__Float_Long(space, w_float1, w_long2):
# XXX naive implementation
x = w_float1.floatval
if isinf(x):
return space.newbool(x < 0.0)
x_floor = math.floor(x)
try:
w_long1 = W_LongObject.fromfloat(x_floor)
except OverflowError:
return space.newbool(x < 0.0)
return space.lt(w_long1, w_long2)
def lt__Long_Float(space, w_long1, w_float2):
return space.not_(le__Float_Long(space, w_float2, w_long1))
def le__Float_Long(space, w_float1, w_long2):
# XXX it's naive anyway
if space.is_true(space.lt(w_float1, w_long2)):
return space.w_True
else:
return space.eq(w_float1, w_long2)
def le__Long_Float(space, w_long1, w_float2):
return space.not_(lt__Float_Long(space, w_float2, w_long1))
def gt__Float_Long(space, w_float1, w_long2):
return space.not_(le__Float_Long(space, w_float1, w_long2))
def gt__Long_Float(space, w_long1, w_float2):
return lt__Float_Long(space, w_float2, w_long1)
def ge__Float_Long(space, w_float1, w_long2):
return space.not_(lt__Float_Long(space, w_float1, w_long2))
def ge__Long_Float(space, w_long1, w_float2):
return le__Float_Long(space, w_float2, w_long1)
def hash__Float(space, w_value):
return space.wrap(_hash_float(space, w_value.floatval))
def _hash_float(space, v):
from pypy.objspace.std.longobject import hash__Long
# This is designed so that Python numbers of different types
# that compare equal hash to the same value; otherwise comparisons
# of mapping keys will turn out weird.
fractpart, intpart = math.modf(v)
if fractpart == 0.0:
# This must return the same hash as an equal int or long.
try:
x = ovfcheck_float_to_int(intpart)
# Fits in a C long == a Python int, so is its own hash.
return x
except OverflowError:
# Convert to long and use its hash.
try:
w_lval = W_LongObject.fromfloat(v)
except OverflowError:
# can't convert to long int -- arbitrary
if v < 0:
return -271828
else:
return 314159
return space.int_w(hash__Long(space, w_lval))
# The fractional part is non-zero, so we don't have to worry about
# making this match the hash of some other type.
# Use frexp to get at the bits in the double.
# Since the VAX D double format has 56 mantissa bits, which is the
# most of any double format in use, each of these parts may have as
# many as (but no more than) 56 significant bits.
# So, assuming sizeof(long) >= 4, each part can be broken into two
# longs; frexp and multiplication are used to do that.
# Also, since the Cray double format has 15 exponent bits, which is
# the most of any double format in use, shifting the exponent field
# left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
v, expo = math.frexp(v)
v *= 2147483648.0 # 2**31
hipart = int(v) # take the top 32 bits
v = (v - hipart) * 2147483648.0 # get the next 32 bits
x = intmask(hipart + int(v) + (expo << 15))
return x
# coerce
def coerce__Float_Float(space, w_float1, w_float2):
return space.newtuple([w_float1, w_float2])
def add__Float_Float(space, w_float1, w_float2):
x = w_float1.floatval
y = w_float2.floatval
try:
z = x + y
except FloatingPointError:
raise FailedToImplement(space.w_FloatingPointError, space.wrap("float addition"))
return W_FloatObject(z)
def sub__Float_Float(space, w_float1, w_float2):
x = w_float1.floatval
y = w_float2.floatval
try:
z = x - y
except FloatingPointError:
raise FailedToImplement(space.w_FloatingPointError, space.wrap("float substraction"))
return W_FloatObject(z)
def mul__Float_Float(space, w_float1, w_float2):
x = w_float1.floatval
y = w_float2.floatval
try:
z = x * y
except FloatingPointError:
raise FailedToImplement(space.w_FloatingPointError, space.wrap("float multiplication"))
return W_FloatObject(z)
def div__Float_Float(space, w_float1, w_float2):
x = w_float1.floatval
y = w_float2.floatval
if y == 0.0:
raise FailedToImplement(space.w_ZeroDivisionError, space.wrap("float division"))
try:
z = x / y
except FloatingPointError:
raise FailedToImplement(space.w_FloatingPointError, space.wrap("float division"))
# no overflow
return W_FloatObject(z)
truediv__Float_Float = div__Float_Float
def floordiv__Float_Float(space, w_float1, w_float2):
w_div, w_mod = _divmod_w(space, w_float1, w_float2)
return w_div
def mod__Float_Float(space, w_float1, w_float2):
x = w_float1.floatval
y = w_float2.floatval
if y == 0.0:
raise FailedToImplement(space.w_ZeroDivisionError, space.wrap("float modulo"))
try:
mod = math.fmod(x, y)
if (mod and ((y < 0.0) != (mod < 0.0))):
mod += y
except FloatingPointError:
raise FailedToImplement(space.w_FloatingPointError, space.wrap("float division"))
return W_FloatObject(mod)
def _divmod_w(space, w_float1, w_float2):
x = w_float1.floatval
y = w_float2.floatval
if y == 0.0:
raise FailedToImplement(space.w_ZeroDivisionError, space.wrap("float modulo"))
try:
mod = math.fmod(x, y)
# fmod is typically exact, so vx-mod is *mathematically* an
# exact multiple of wx. But this is fp arithmetic, and fp
# vx - mod is an approximation; the result is that div may
# not be an exact integral value after the division, although
# it will always be very close to one.
div = (x - mod) / y
if (mod):
# ensure the remainder has the same sign as the denominator
if ((y < 0.0) != (mod < 0.0)):
mod += y
div -= 1.0
else:
# the remainder is zero, and in the presence of signed zeroes
# fmod returns different results across platforms; ensure
# it has the same sign as the denominator; we'd like to do
# "mod = wx * 0.0", but that may get optimized away
mod *= mod # hide "mod = +0" from optimizer
if y < 0.0:
mod = -mod
# snap quotient to nearest integral value
if div:
floordiv = math.floor(div)
if (div - floordiv > 0.5):
floordiv += 1.0
else:
# div is zero - get the same sign as the true quotient
div *= div # hide "div = +0" from optimizers
floordiv = div * x / y # zero w/ sign of vx/wx
except FloatingPointError:
raise FailedToImplement(space.w_FloatingPointError, space.wrap("float division"))
return [W_FloatObject(floordiv), W_FloatObject(mod)]
def divmod__Float_Float(space, w_float1, w_float2):
return space.newtuple(_divmod_w(space, w_float1, w_float2))
def pow__Float_Float_ANY(space, w_float1, w_float2, thirdArg):
# XXX it makes sense to do more here than in the backend
# about sorting out errors!
if not space.is_w(thirdArg, space.w_None):
raise FailedToImplement(space.w_TypeError, space.wrap(
"pow() 3rd argument not allowed unless all arguments are integers"))
x = w_float1.floatval
y = w_float2.floatval
z = 1.0
if y == 0.0:
z = 1.0
elif x == 0.0:
if y < 0.0:
raise FailedToImplement(space.w_ZeroDivisionError,
space.wrap("0.0 cannot be raised to a negative power"))
z = 0.0
else:
if x < 0.0:
if math.floor(y) != y:
raise FailedToImplement(space.w_ValueError,
space.wrap("negative number "
"cannot be raised to a fractional power"))
if x == -1.0:
# xxx what if y is infinity or a NaN
if math.floor(y * 0.5) * 2.0 == y:
return space.wrap(1.0)
else:
return space.wrap( -1.0)
# else:
try:
z = math.pow(x,y)
except OverflowError:
raise FailedToImplement(space.w_OverflowError, space.wrap("float power"))
except ValueError:
raise FailedToImplement(space.w_ValueError, space.wrap("float power")) # xxx
return W_FloatObject(z)
def neg__Float(space, w_float1):
return W_FloatObject(-w_float1.floatval)
def pos__Float(space, w_float):
return float__Float(space, w_float)
def abs__Float(space, w_float):
return W_FloatObject(abs(w_float.floatval))
def nonzero__Float(space, w_float):
return space.newbool(w_float.floatval != 0.0)
def getnewargs__Float(space, w_float):
return space.newtuple([W_FloatObject(w_float.floatval)])
register_all(vars())
# pow delegation for negative 2nd arg
def pow_neg__Long_Long_None(space, w_int1, w_int2, thirdarg):
w_float1 = delegate_Long2Float(space, w_int1)
w_float2 = delegate_Long2Float(space, w_int2)
return pow__Float_Float_ANY(space, w_float1, w_float2, thirdarg)
StdObjSpace.MM.pow.register(pow_neg__Long_Long_None, W_LongObject, W_LongObject, W_NoneObject, order=1)
def pow_neg__Int_Int_None(space, w_int1, w_int2, thirdarg):
w_float1 = delegate_Int2Float(space, w_int1)
w_float2 = delegate_Int2Float(space, w_int2)
return pow__Float_Float_ANY(space, w_float1, w_float2, thirdarg)
StdObjSpace.MM.pow.register(pow_neg__Int_Int_None, W_IntObject, W_IntObject, W_NoneObject, order=2)
| Python |
""" Some transparent helpers, put here because
of cyclic imports
"""
from pypy.objspace.std.model import W_ANY, W_Object
from pypy.interpreter import baseobjspace
from pypy.interpreter.argument import Arguments
from pypy.tool.sourcetools import func_with_new_name
def create_mm_names(classname, mm, is_local):
s = ""
if is_local:
s += "list_"
s += mm.name + "__"
s += "_".join([classname] + ["ANY"] * (mm.arity - 1))
#if '__' + mm.name + '__' in mm.specialnames:
# return s, '__' + mm.name + '__'
if mm.specialnames:
return s, mm.specialnames[0]
return s, mm.name
def install_general_args_trampoline(type_, mm, is_local, op_name):
def function(space, w_transparent_list, __args__):
args = __args__.prepend(space.wrap(op_name))
return space.call_args(w_transparent_list.w_controller, args)
function = func_with_new_name(function, mm.name)
mm.register(function, type_)
def install_w_args_trampoline(type_, mm, is_local, op_name):
def function(space, w_transparent_list, *args_w):
args = Arguments(space, [space.wrap(op_name)] + list(args_w[:-1]), w_stararg=args_w[-1])
return space.call_args(w_transparent_list.w_controller, args)
function = func_with_new_name(function, mm.name)
mm.register(function, type_, *([W_ANY] * (mm.arity - 1)))
def install_mm_trampoline(type_, mm, is_local):
classname = type_.__name__[2:]
mm_name, op_name = create_mm_names(classname, mm, is_local)
if ['__args__'] == mm.argnames_after:
return install_general_args_trampoline(type_, mm, is_local, op_name)
if ['w_args'] == mm.argnames_after:
return install_w_args_trampoline(type_, mm, is_local, op_name)
assert not mm.argnames_after
# we search here for special-cased stuff
def function(space, w_transparent_list, *args_w):
return space.call_function(w_transparent_list.w_controller, space.wrap\
(op_name), *args_w)
function = func_with_new_name(function, mm_name)
mm.register(function, type_, *([W_ANY] * (mm.arity - 1)))
def is_special_doublearg(mm, type_):
""" We specialcase when we've got two argument method for which
there exist reverse operation
"""
if mm.arity != 2:
return False
if len(mm.specialnames) != 2:
return False
# search over the signatures
for signature in mm.signatures():
if signature == (type_.original, type_.original):
return True
return False
def install_mm_special(type_, mm, is_local):
classname = type_.__name__[2:]
#mm_name, op_name = create_mm_names(classname, mm, is_local)
def function(space, w_any, w_transparent_list):
retval = space.call_function(w_transparent_list.w_controller, space.wrap(mm.specialnames[1]),
w_any)
return retval
function = func_with_new_name(function, mm.specialnames[0])
mm.register(function, type_.typedef.any, type_)
def register_type(type_):
from pypy.objspace.std.stdtypedef import multimethods_defined_on
for mm, is_local in multimethods_defined_on(type_.original):
if not mm.name.startswith('__'):
install_mm_trampoline(type_, mm, is_local)
if is_special_doublearg(mm, type_):
install_mm_special(type_, mm, is_local)
| Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.listtype import get_list_index
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std.tupleobject import W_TupleObject
from pypy.objspace.std import slicetype
from pypy.interpreter import gateway, baseobjspace
from pypy.rlib.listsort import TimSort
class W_ListObject(W_Object):
from pypy.objspace.std.listtype import list_typedef as typedef
def __init__(w_self, wrappeditems):
w_self.wrappeditems = wrappeditems
def __repr__(w_self):
""" representation for debugging purposes """
return "%s(%s)" % (w_self.__class__.__name__, w_self.wrappeditems)
def unwrap(w_list, space):
items = [space.unwrap(w_item) for w_item in w_list.wrappeditems]# XXX generic mixed types unwrap
return list(items)
registerimplementation(W_ListObject)
EMPTY_LIST = W_ListObject([])
def init__List(space, w_list, __args__):
w_iterable, = __args__.parse('list',
(['sequence'], None, None), # signature
[EMPTY_LIST]) # default argument
if w_iterable is EMPTY_LIST:
w_list.wrappeditems = []
else:
w_list.wrappeditems = space.unpackiterable(w_iterable)
def len__List(space, w_list):
result = len(w_list.wrappeditems)
return wrapint(space, result)
def getitem__List_ANY(space, w_list, w_index):
try:
return w_list.wrappeditems[get_list_index(space, w_index)]
except IndexError:
raise OperationError(space.w_IndexError,
space.wrap("list index out of range"))
def getitem__List_Slice(space, w_list, w_slice):
# XXX consider to extend rlist's functionality?
length = len(w_list.wrappeditems)
start, stop, step, slicelength = w_slice.indices4(space, length)
assert slicelength >= 0
if step == 1 and 0 <= start <= stop:
return W_ListObject(w_list.wrappeditems[start:stop])
w_res = W_ListObject([None] * slicelength)
items_w = w_list.wrappeditems
subitems_w = w_res.wrappeditems
for i in range(slicelength):
subitems_w[i] = items_w[start]
start += step
return w_res
def contains__List_ANY(space, w_list, w_obj):
# needs to be safe against eq_w() mutating the w_list behind our back
i = 0
items_w = w_list.wrappeditems
while i < len(items_w): # intentionally always calling len!
if space.eq_w(items_w[i], w_obj):
return space.w_True
i += 1
return space.w_False
def iter__List(space, w_list):
from pypy.objspace.std import iterobject
return iterobject.W_SeqIterObject(w_list)
def add__List_List(space, w_list1, w_list2):
return W_ListObject(w_list1.wrappeditems + w_list2.wrappeditems)
def inplace_add__List_ANY(space, w_list1, w_iterable2):
list_extend__List_ANY(space, w_list1, w_iterable2)
return w_list1
def inplace_add__List_List(space, w_list1, w_list2):
list_extend__List_List(space, w_list1, w_list2)
return w_list1
def mul_list_times(space, w_list, w_times):
try:
times = space.getindex_w(w_times, space.w_OverflowError)
except OperationError, e:
if e.match(space, space.w_TypeError):
raise FailedToImplement
raise
return W_ListObject(w_list.wrappeditems * times)
def mul__List_ANY(space, w_list, w_times):
return mul_list_times(space, w_list, w_times)
def mul__ANY_List(space, w_times, w_list):
return mul_list_times(space, w_list, w_times)
def inplace_mul__List_ANY(space, w_list, w_times):
try:
times = space.getindex_w(w_times, space.w_OverflowError)
except OperationError, e:
if e.match(space, space.w_TypeError):
raise FailedToImplement
raise
w_list.wrappeditems *= times
return w_list
def eq__List_List(space, w_list1, w_list2):
# needs to be safe against eq_w() mutating the w_lists behind our back
items1_w = w_list1.wrappeditems
items2_w = w_list2.wrappeditems
return equal_wrappeditems(space, items1_w, items2_w)
def equal_wrappeditems(space, items1_w, items2_w):
if len(items1_w) != len(items2_w):
return space.w_False
i = 0
while i < len(items1_w) and i < len(items2_w):
if not space.eq_w(items1_w[i], items2_w[i]):
return space.w_False
i += 1
return space.w_True
def _min(a, b):
if a < b:
return a
return b
def lessthan_unwrappeditems(space, items1_w, items2_w):
# needs to be safe against eq_w() mutating the w_lists behind our back
# Search for the first index where items are different
i = 0
while i < len(items1_w) and i < len(items2_w):
w_item1 = items1_w[i]
w_item2 = items2_w[i]
if not space.eq_w(w_item1, w_item2):
return space.lt(w_item1, w_item2)
i += 1
# No more items to compare -- compare sizes
return space.newbool(len(items1_w) < len(items2_w))
def greaterthan_unwrappeditems(space, items1_w, items2_w):
# needs to be safe against eq_w() mutating the w_lists behind our back
# Search for the first index where items are different
i = 0
while i < len(items1_w) and i < len(items2_w):
w_item1 = items1_w[i]
w_item2 = items2_w[i]
if not space.eq_w(w_item1, w_item2):
return space.gt(w_item1, w_item2)
i += 1
# No more items to compare -- compare sizes
return space.newbool(len(items1_w) > len(items2_w))
def lt__List_List(space, w_list1, w_list2):
return lessthan_unwrappeditems(space, w_list1.wrappeditems,
w_list2.wrappeditems)
def gt__List_List(space, w_list1, w_list2):
return greaterthan_unwrappeditems(space, w_list1.wrappeditems,
w_list2.wrappeditems)
def delitem__List_ANY(space, w_list, w_idx):
idx = get_list_index(space, w_idx)
try:
del w_list.wrappeditems[idx]
except IndexError:
raise OperationError(space.w_IndexError,
space.wrap("list deletion index out of range"))
return space.w_None
def delitem__List_Slice(space, w_list, w_slice):
start, stop, step, slicelength = w_slice.indices4(space,
len(w_list.wrappeditems))
if slicelength==0:
return
if step < 0:
start = start + step * (slicelength-1)
step = -step
# stop is invalid
if step == 1:
_del_slice(w_list, start, start+slicelength)
else:
items = w_list.wrappeditems
n = len(items)
recycle = [None] * slicelength
i = start
# keep a reference to the objects to be removed,
# preventing side effects during destruction
recycle[0] = items[i]
for discard in range(1, slicelength):
j = i+1
i += step
while j < i:
items[j-discard] = items[j]
j += 1
recycle[discard] = items[i]
j = i+1
while j < n:
items[j-slicelength] = items[j]
j += 1
start = n - slicelength
assert start >= 0 # annotator hint
# XXX allow negative indices in rlist
del items[start:]
# now we can destruct recycle safely, regardless of
# side-effects to the list
del recycle[:]
return space.w_None
def setitem__List_ANY_ANY(space, w_list, w_index, w_any):
idx = get_list_index(space, w_index)
try:
w_list.wrappeditems[idx] = w_any
except IndexError:
raise OperationError(space.w_IndexError,
space.wrap("list index out of range"))
return space.w_None
def setitem__List_Slice_List(space, w_list, w_slice, w_list2):
l = w_list2.wrappeditems
return _setitem_slice_helper(space, w_list, w_slice, l, len(l))
def setitem__List_Slice_Tuple(space, w_list, w_slice, w_tuple):
t = w_tuple.wrappeditems
return _setitem_slice_helper(space, w_list, w_slice, t, len(t))
def setitem__List_Slice_ANY(space, w_list, w_slice, w_iterable):
l = space.unpackiterable(w_iterable)
return _setitem_slice_helper(space, w_list, w_slice, l, len(l))
def _setitem_slice_helper(space, w_list, w_slice, sequence2, len2):
oldsize = len(w_list.wrappeditems)
start, stop, step, slicelength = w_slice.indices4(space, oldsize)
assert slicelength >= 0
items = w_list.wrappeditems
if step == 1: # Support list resizing for non-extended slices
delta = len2 - slicelength
if delta >= 0:
newsize = oldsize + delta
# XXX support this in rlist!
items += [None] * delta
lim = start+len2
i = newsize - 1
while i >= lim:
items[i] = items[i-delta]
i -= 1
else:
# shrinking requires the careful memory management of _del_slice()
_del_slice(w_list, start, start-delta)
elif len2 != slicelength: # No resize for extended slices
raise OperationError(space.w_ValueError, space.wrap("attempt to "
"assign sequence of size %d to extended slice of size %d" %
(len2,slicelength)))
if sequence2 is items:
if step > 0:
# Always copy starting from the right to avoid
# having to make a shallow copy in the case where
# the source and destination lists are the same list.
i = len2 - 1
start += i*step
while i >= 0:
items[start] = sequence2[i]
start -= step
i -= 1
return space.w_None
else:
# Make a shallow copy to more easily handle the reversal case
sequence2 = list(sequence2)
for i in range(len2):
items[start] = sequence2[i]
start += step
return space.w_None
app = gateway.applevel("""
def listrepr(currently_in_repr, l):
'The app-level part of repr().'
list_id = id(l)
if list_id in currently_in_repr:
return '[...]'
currently_in_repr[list_id] = 1
try:
return "[" + ", ".join([repr(x) for x in l]) + ']'
finally:
try:
del currently_in_repr[list_id]
except:
pass
""", filename=__file__)
listrepr = app.interphook("listrepr")
def repr__List(space, w_list):
if len(w_list.wrappeditems) == 0:
return space.wrap('[]')
w_currently_in_repr = space.getexecutioncontext()._py_repr
return listrepr(space, w_currently_in_repr, w_list)
def list_insert__List_ANY_ANY(space, w_list, w_where, w_any):
where = space.int_w(w_where)
length = len(w_list.wrappeditems)
if where < 0:
where += length
if where < 0:
where = 0
elif where > length:
where = length
w_list.wrappeditems.insert(where, w_any)
return space.w_None
def list_append__List_ANY(space, w_list, w_any):
w_list.wrappeditems.append(w_any)
return space.w_None
def list_extend__List_List(space, w_list, w_other):
w_list.wrappeditems += w_other.wrappeditems
return space.w_None
def list_extend__List_ANY(space, w_list, w_any):
w_list.wrappeditems += space.unpackiterable(w_any)
return space.w_None
def _del_slice(w_list, ilow, ihigh):
""" similar to the deletion part of list_ass_slice in CPython """
items = w_list.wrappeditems
n = len(items)
if ilow < 0:
ilow = 0
elif ilow > n:
ilow = n
if ihigh < ilow:
ihigh = ilow
elif ihigh > n:
ihigh = n
# keep a reference to the objects to be removed,
# preventing side effects during destruction
recycle = items[ilow:ihigh]
del items[ilow:ihigh]
# now we can destruct recycle safely, regardless of
# side-effects to the list
del recycle[:]
# note that the default value will come back wrapped!!!
def list_pop__List_ANY(space, w_list, w_idx=-1):
items = w_list.wrappeditems
if len(items)== 0:
raise OperationError(space.w_IndexError,
space.wrap("pop from empty list"))
idx = space.int_w(w_idx)
try:
return items.pop(idx)
except IndexError:
raise OperationError(space.w_IndexError,
space.wrap("pop index out of range"))
def list_remove__List_ANY(space, w_list, w_any):
# needs to be safe against eq_w() mutating the w_list behind our back
items = w_list.wrappeditems
i = 0
while i < len(items):
if space.eq_w(items[i], w_any):
if i < len(items): # if this is wrong the list was changed
del items[i]
return space.w_None
i += 1
raise OperationError(space.w_ValueError,
space.wrap("list.remove(x): x not in list"))
def list_index__List_ANY_ANY_ANY(space, w_list, w_any, w_start, w_stop):
# needs to be safe against eq_w() mutating the w_list behind our back
items = w_list.wrappeditems
size = len(items)
i = slicetype.adapt_bound(space, size, w_start)
stop = slicetype.adapt_bound(space, size, w_stop)
while i < stop and i < len(items):
if space.eq_w(items[i], w_any):
return space.wrap(i)
i += 1
raise OperationError(space.w_ValueError,
space.wrap("list.index(x): x not in list"))
def list_count__List_ANY(space, w_list, w_any):
# needs to be safe against eq_w() mutating the w_list behind our back
count = 0
i = 0
items = w_list.wrappeditems
while i < len(items):
if space.eq_w(items[i], w_any):
count += 1
i += 1
return space.wrap(count)
def list_reverse__List(space, w_list):
w_list.wrappeditems.reverse()
return space.w_None
# ____________________________________________________________
# Sorting
# Reverse a slice of a list in place, from lo up to (exclusive) hi.
# (used in sort)
class KeyContainer(baseobjspace.W_Root):
def __init__(self, w_key, w_item):
self.w_key = w_key
self.w_item = w_item
# NOTE: all the subclasses of TimSort should inherit from a common subclass,
# so make sure that only SimpleSort inherits directly from TimSort.
# This is necessary to hide the parent method TimSort.lt() from the
# annotator.
class SimpleSort(TimSort):
def lt(self, a, b):
space = self.space
return space.is_true(space.lt(a, b))
class CustomCompareSort(SimpleSort):
def lt(self, a, b):
space = self.space
w_cmp = self.w_cmp
w_result = space.call_function(w_cmp, a, b)
try:
result = space.int_w(w_result)
except OperationError, e:
if e.match(space, space.w_TypeError):
raise OperationError(space.w_TypeError,
space.wrap("comparison function must return int"))
raise
return result < 0
class CustomKeySort(SimpleSort):
def lt(self, a, b):
assert isinstance(a, KeyContainer)
assert isinstance(b, KeyContainer)
space = self.space
return space.is_true(space.lt(a.w_key, b.w_key))
class CustomKeyCompareSort(CustomCompareSort):
def lt(self, a, b):
assert isinstance(a, KeyContainer)
assert isinstance(b, KeyContainer)
return CustomCompareSort.lt(self, a.w_key, b.w_key)
def list_sort__List_ANY_ANY_ANY(space, w_list, w_cmp, w_keyfunc, w_reverse):
has_cmp = not space.is_w(w_cmp, space.w_None)
has_key = not space.is_w(w_keyfunc, space.w_None)
has_reverse = space.is_true(w_reverse)
# create and setup a TimSort instance
if has_cmp:
if has_key:
sorterclass = CustomKeyCompareSort
else:
sorterclass = CustomCompareSort
else:
if has_key:
sorterclass = CustomKeySort
else:
sorterclass = SimpleSort
items = w_list.wrappeditems
sorter = sorterclass(items, len(items))
sorter.space = space
sorter.w_cmp = w_cmp
try:
# The list is temporarily made empty, so that mutations performed
# by comparison functions can't affect the slice of memory we're
# sorting (allowing mutations during sorting is an IndexError or
# core-dump factory, since wrappeditems may change).
w_list.wrappeditems = []
# wrap each item in a KeyContainer if needed
if has_key:
for i in range(sorter.listlength):
w_item = sorter.list[i]
w_key = space.call_function(w_keyfunc, w_item)
sorter.list[i] = KeyContainer(w_key, w_item)
# Reverse sort stability achieved by initially reversing the list,
# applying a stable forward sort, then reversing the final result.
if has_reverse:
sorter.list.reverse()
# perform the sort
sorter.sort()
# reverse again
if has_reverse:
sorter.list.reverse()
finally:
# unwrap each item if needed
if has_key:
for i in range(sorter.listlength):
w_obj = sorter.list[i]
if isinstance(w_obj, KeyContainer):
sorter.list[i] = w_obj.w_item
# check if the user mucked with the list during the sort
mucked = len(w_list.wrappeditems) > 0
# put the items back into the list
w_list.wrappeditems = sorter.list
if mucked:
raise OperationError(space.w_ValueError,
space.wrap("list modified during sort"))
return space.w_None
from pypy.objspace.std import listtype
register_all(vars(), listtype)
| Python |
from pypy.objspace.std.dictmultiobject import DictImplementation
from pypy.objspace.std.dictmultiobject import IteratorImplementation
class BucketNode:
def __init__(self, hash, w_key, w_value, next):
self.hash = hash
self.w_key = w_key
self.w_value = w_value
self.next = next
DISTRIBUTE = 9
class BucketDictImplementation(DictImplementation):
def __init__(self, space):
self.space = space
self.len = 0
self.table = [None] * 4
def __repr__(self):
bs = []
for node in self.table:
count = 0
while node is not None:
count += 1
node = node.next
bs.append(str(count))
return "%s<%s>" % (self.__class__.__name__, ', '.join(bs))
def get(self, w_key):
space = self.space
hash = space.hash_w(w_key)
index = (hash * DISTRIBUTE) & (len(self.table) - 1)
node = self.table[index]
while node is not None:
if node.hash == hash and space.eq_w(w_key, node.w_key):
return node.w_value
node = node.next
return None
def setitem(self, w_key, w_value):
space = self.space
hash = space.hash_w(w_key)
index = (hash * DISTRIBUTE) & (len(self.table) - 1)
node = head = self.table[index]
while node is not None:
if node.hash == hash and space.eq_w(w_key, node.w_key):
node.w_value = w_value
return self
node = node.next
self.table[index] = BucketNode(hash, w_key, w_value, head)
self.len += 1
if self.len > len(self.table):
self._resize()
return self
def setitem_str(self, w_key, w_value, shadows_type=True):
return self.setitem(w_key, w_value)
def delitem(self, w_key):
space = self.space
hash = space.hash_w(w_key)
index = (hash * DISTRIBUTE) & (len(self.table) - 1)
node = self.table[index]
prev = None
while node is not None:
if node.hash == hash and space.eq_w(w_key, node.w_key):
self.len -= 1
if self.len == 0:
return self.space.emptydictimpl
if prev is None:
self.table[index] = node.next
else:
prev.next = node.next
if self.len < len(self.table) // 2:
self._resize()
return self
prev = node
node = node.next
raise KeyError
def length(self):
return self.len
def _resize(self):
newsize = 4
while newsize < self.len:
newsize *= 2
newtable = [None] * newsize
for node in self.table:
while node is not None:
newindex = (node.hash * DISTRIBUTE) & (newsize - 1)
next = node.next
node.next = newtable[newindex]
newtable[newindex] = node
node = next
self.table = newtable
def iteritems(self):
return BucketDictItemIteratorImplementation(self.space, self)
def iterkeys(self):
return BucketDictKeyIteratorImplementation(self.space, self)
def itervalues(self):
return BucketDictValueIteratorImplementation(self.space, self)
def keys(self):
result_w = []
for node in self.table:
while node is not None:
result_w.append(node.w_key)
node = node.next
return result_w
def values(self):
result_w = []
for node in self.table:
while node is not None:
result_w.append(node.w_value)
node = node.next
return result_w
def items(self):
space = self.space
result_w = []
for node in self.table:
while node is not None:
w_item = space.newtuple([node.w_key, node.w_value])
result_w.append(w_item)
node = node.next
return result_w
class BucketDictIteratorImplementation(IteratorImplementation):
def __init__(self, space, dictimplementation):
IteratorImplementation.__init__(self, space, dictimplementation)
self.index = 0
self.node = None
def next_entry(self):
node = self.node
while node is None:
table = self.dictimplementation.table
if self.index >= len(table):
return None
node = table[self.index]
self.index += 1
self.node = node.next
return self.get_result(node)
class BucketDictKeyIteratorImplementation(BucketDictIteratorImplementation):
def get_result(self, node):
return node.w_key
class BucketDictValueIteratorImplementation(BucketDictIteratorImplementation):
def get_result(self, node):
return node.w_value
class BucketDictItemIteratorImplementation(BucketDictIteratorImplementation):
def get_result(self, node):
return self.space.newtuple([node.w_key, node.w_value])
| Python |
from __future__ import generators
from pypy.interpreter import gateway
from pypy.interpreter.error import OperationError
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.register_all import register_all
from sys import maxint
list_append = SMM('append', 2,
doc='L.append(object) -- append object to end')
list_insert = SMM('insert', 3,
doc='L.insert(index, object) -- insert object before index')
list_extend = SMM('extend', 2,
doc='L.extend(iterable) -- extend list by appending'
' elements from the iterable')
list_pop = SMM('pop', 2, defaults=(-1,),
doc='L.pop([index]) -> item -- remove and return item at'
' index (default last)')
list_remove = SMM('remove', 2,
doc='L.remove(value) -- remove first occurrence of value')
list_index = SMM('index', 4, defaults=(0,maxint),
doc='L.index(value, [start, [stop]]) -> integer -- return'
' first index of value')
list_count = SMM('count', 2,
doc='L.count(value) -> integer -- return number of'
' occurrences of value')
list_reverse = SMM('reverse',1,
doc='L.reverse() -- reverse *IN PLACE*')
list_sort = SMM('sort', 4, defaults=(None, None, False), argnames=['cmp', 'key', 'reverse'],
doc='L.sort(cmp=None, key=None, reverse=False) -- stable'
' sort *IN PLACE*;\ncmp(x, y) -> -1, 0, 1')
list_reversed = SMM('__reversed__', 1,
doc='L.__reversed__() -- return a reverse iterator over'
' the list')
def list_reversed__ANY(space, w_list):
from pypy.objspace.std.iterobject import W_ReverseSeqIterObject
return W_ReverseSeqIterObject(space, w_list, -1)
register_all(vars(), globals())
# ____________________________________________________________
def descr__new__(space, w_listtype, __args__):
if space.config.objspace.std.withmultilist:
from pypy.objspace.std.listmultiobject import W_ListMultiObject
w_obj = space.allocate_instance(W_ListMultiObject, w_listtype)
W_ListMultiObject.__init__(w_obj, space)
else:
from pypy.objspace.std.listobject import W_ListObject
w_obj = space.allocate_instance(W_ListObject, w_listtype)
W_ListObject.__init__(w_obj, [])
return w_obj
# ____________________________________________________________
list_typedef = StdTypeDef("list",
__doc__ = '''list() -> new list
list(sequence) -> new list initialized from sequence's items''',
__new__ = newmethod(descr__new__, unwrap_spec=[gateway.ObjSpace,
gateway.W_Root,
gateway.Arguments]),
__hash__ = no_hash_descr,
)
list_typedef.registermethods(globals())
# ____________________________________________________________
def get_list_index(space, w_index):
return space.getindex_w(w_index, space.w_IndexError, "list index")
| Python |
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.inttype import int_typedef
# XXX should forbit subclassing of 'bool'
def descr__new__(space, w_booltype, w_obj=None):
space.w_bool.check_user_subclass(w_booltype)
if space.is_true(w_obj):
return space.w_True
else:
return space.w_False
# ____________________________________________________________
bool_typedef = StdTypeDef("bool", int_typedef,
__doc__ = '''bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.''',
__new__ = newmethod(descr__new__),
)
bool_typedef.acceptable_as_base_class = False
| Python |
# implementation of marshalling by multimethods
"""
The idea is to have an effective but flexible
way to implement marshalling for the native types.
The marshal_w operation is called with an object,
a callback and a state variable.
"""
from pypy.interpreter.error import OperationError
from pypy.objspace.std.register_all import register_all
from pypy.rlib.rarithmetic import LONG_BIT
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.floatobject import repr__Float as repr_float
from pypy.objspace.std.longobject import SHIFT as long_bits
from pypy.objspace.std.objspace import StdObjSpace
from pypy.interpreter.special import Ellipsis
from pypy.interpreter.pycode import PyCode
from pypy.interpreter import gateway
from pypy.objspace.std.boolobject import W_BoolObject
from pypy.objspace.std.complexobject import W_ComplexObject
from pypy.objspace.std.intobject import W_IntObject
from pypy.objspace.std.floatobject import W_FloatObject
from pypy.objspace.std.tupleobject import W_TupleObject
from pypy.objspace.std.listobject import W_ListObject
from pypy.objspace.std.dictobject import W_DictObject
from pypy.objspace.std.dictmultiobject import W_DictMultiObject
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.ropeobject import W_RopeObject
from pypy.objspace.std.typeobject import W_TypeObject
from pypy.objspace.std.longobject import W_LongObject
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.objspace.std.unicodeobject import W_UnicodeObject
import longobject, dictobject
from pypy.module.marshal.interp_marshal import register
TYPE_NULL = '0'
TYPE_NONE = 'N'
TYPE_FALSE = 'F'
TYPE_TRUE = 'T'
TYPE_STOPITER = 'S'
TYPE_ELLIPSIS = '.'
TYPE_INT = 'i'
TYPE_INT64 = 'I'
TYPE_FLOAT = 'f'
TYPE_BINARY_FLOAT = 'g'
TYPE_COMPLEX = 'x'
TYPE_BINARY_COMPLEX = 'y'
TYPE_LONG = 'l'
TYPE_STRING = 's'
TYPE_INTERNED = 't'
TYPE_STRINGREF = 'R'
TYPE_TUPLE = '('
TYPE_LIST = '['
TYPE_DICT = '{'
TYPE_CODE = 'c'
TYPE_UNICODE = 'u'
TYPE_UNKNOWN = '?'
TYPE_SET = '<'
TYPE_FROZENSET = '>'
"""
simple approach:
a call to marshal_w has the following semantics:
marshal_w receives a marshaller object which contains
state and several methods.
atomic types including typecode:
atom(tc) puts single typecode
atom_int(tc, int) puts code and int
atom_int64(tc, int64) puts code and int64
atom_str(tc, str) puts code, len and string
atom_strlist(tc, strlist) puts code, len and list of strings
building blocks for compound types:
start(typecode) sets the type character
put(s) puts a string with fixed length
put_short(int) puts a short integer
put_int(int) puts an integer
put_pascal(s) puts a short string
put_w_obj(w_obj) puts a wrapped object
put_list_w(list_w, lng) puts a list of lng wrapped objects
"""
handled_by_any = []
def raise_exception(space, msg):
raise OperationError(space.w_ValueError, space.wrap(msg))
def marshal_w__None(space, w_none, m):
m.atom(TYPE_NONE)
def unmarshal_None(space, u, tc):
return space.w_None
register(TYPE_NONE, unmarshal_None)
def marshal_w__Bool(space, w_bool, m):
if w_bool.boolval:
m.atom(TYPE_TRUE)
else:
m.atom(TYPE_FALSE)
def unmarshal_Bool(space, u, tc):
if tc == TYPE_TRUE:
return space.w_True
else:
return space.w_False
register(TYPE_TRUE + TYPE_FALSE, unmarshal_Bool)
def marshal_w__Type(space, w_type, m):
if not space.is_w(w_type, space.w_StopIteration):
raise_exception(space, "unmarshallable object")
m.atom(TYPE_STOPITER)
def unmarshal_Type(space, u, tc):
return space.w_StopIteration
register(TYPE_STOPITER, unmarshal_Type)
# not directly supported:
def marshal_w_Ellipsis(space, w_ellipsis, m):
m.atom(TYPE_ELLIPSIS)
StdObjSpace.MM.marshal_w.register(marshal_w_Ellipsis, Ellipsis)
def unmarshal_Ellipsis(space, u, tc):
return space.w_Ellipsis
register(TYPE_ELLIPSIS, unmarshal_Ellipsis)
def marshal_w__Int(space, w_int, m):
if LONG_BIT == 32:
m.atom_int(TYPE_INT, w_int.intval)
else:
y = w_int.intval >> 31
if y and y != -1:
m.atom_int64(TYPE_INT64, w_int.intval)
else:
m.atom_int(TYPE_INT, w_int.intval)
def unmarshal_Int(space, u, tc):
return wrapint(space, u.get_int())
register(TYPE_INT, unmarshal_Int)
def unmarshal_Int64(space, u, tc):
if LONG_BIT >= 64:
lo = u.get_int() & (2**32-1)
hi = u.get_int()
return wrapint(space, (hi << 32) | lo)
else:
# fall back to a long
# XXX at some point, we need to extend longobject
# by _PyLong_FromByteArray and _PyLong_AsByteArray.
# I will do that when implementing cPickle.
# for now, this rare case is solved the simple way.
lshift = longobject.lshift__Long_Long
longor = longobject.or__Long_Long
lo1 = space.newlong(u.get_short() & 0xffff)
lo2 = space.newlong(u.get_short() & 0xffff)
res = space.newlong(u.get_int())
nbits = space.newlong(16)
res = lshift(space, res, nbits)
res = longor(space, res, lo2)
res = lshift(space, res, nbits)
res = longor(space, res, lo1)
return res
register(TYPE_INT64, unmarshal_Int64)
# support for marshal version 2:
# we call back into the struct module.
# XXX struct should become interp-level.
# XXX we also should have an rtyper operation
# that allows to typecast between double and char{8}
app = gateway.applevel(r'''
def float_to_str(fl):
import struct
return struct.pack('<d', fl)
def str_to_float(s):
import struct
return struct.unpack('<d', s)[0]
''')
float_to_str = app.interphook('float_to_str')
str_to_float = app.interphook('str_to_float')
def marshal_w__Float(space, w_float, m):
if m.version > 1:
m.start(TYPE_BINARY_FLOAT)
m.put(space.str_w(float_to_str(space, w_float)))
else:
m.start(TYPE_FLOAT)
m.put_pascal(space.str_w(repr_float(space, w_float)))
def unmarshal_Float(space, u, tc):
if tc == TYPE_BINARY_FLOAT:
w_ret = str_to_float(space, space.wrap(u.get(8)))
return W_FloatObject(space.float_w(w_ret))
else:
return space.call_function(space.builtin.get('float'),
space.wrap(u.get_pascal()))
register(TYPE_FLOAT + TYPE_BINARY_FLOAT, unmarshal_Float)
def marshal_w__Complex(space, w_complex, m):
# XXX a bit too wrap-happy
w_real = space.wrap(w_complex.realval)
w_imag = space.wrap(w_complex.imagval)
if m.version > 1:
m.start(TYPE_BINARY_COMPLEX)
m.put(space.str_w(float_to_str(space, w_real)))
m.put(space.str_w(float_to_str(space, w_imag)))
else:
m.start(TYPE_COMPLEX)
m.put_pascal(space.str_w(repr_float(space, w_real)))
m.put_pascal(space.str_w(repr_float(space, w_imag)))
def unmarshal_Complex(space, u, tc):
if tc == TYPE_BINARY_COMPLEX:
w_real = str_to_float(space, space.wrap(u.get(8)))
w_imag = str_to_float(space, space.wrap(u.get(8)))
else:
w_real = space.call_function(space.builtin.get('float'),
space.wrap(u.get_pascal()))
w_imag = space.call_function(space.builtin.get('float'),
space.wrap(u.get_pascal()))
w_t = space.builtin.get('complex')
return space.call_function(w_t, w_real, w_imag)
register(TYPE_COMPLEX + TYPE_BINARY_COMPLEX, unmarshal_Complex)
def marshal_w__Long(space, w_long, m):
assert long_bits == 15, """if long_bits is not 15,
we need to write much more general code for marshal
that breaks things into pieces, or invent a new
typecode and have our own magic number for pickling"""
m.start(TYPE_LONG)
# XXX access internals
lng = len(w_long.num.digits)
if w_long.num.sign < 0:
m.put_int(-lng)
else:
m.put_int(lng)
for digit in w_long.num.digits:
m.put_short(digit)
def unmarshal_Long(space, u, tc):
from pypy.rlib import rbigint
lng = u.get_int()
if lng < 0:
sign = -1
lng = -lng
elif lng > 0:
sign = 1
else:
sign = 0
digits = [0] * lng
i = 0
while i < lng:
digit = u.get_short()
if digit < 0:
raise_exception(space, 'bad marshal data')
digits[i] = digit
i += 1
# XXX poking at internals
w_long = W_LongObject(rbigint.rbigint(digits, sign))
w_long.num._normalize()
return w_long
register(TYPE_LONG, unmarshal_Long)
# XXX currently, intern() is at applevel,
# and there is no interface to get at the
# internal table.
# Move intern to interplevel and add a flag
# to strings.
def PySTRING_CHECK_INTERNED(w_str):
return False
def marshal_w__String(space, w_str, m):
# using the fastest possible access method here
# that does not touch the internal representation,
# which might change (array of bytes?)
s = w_str.unwrap(space)
if m.version >= 1 and PySTRING_CHECK_INTERNED(w_str):
# we use a native rtyper stringdict for speed
idx = m.stringtable.get(s, -1)
if idx >= 0:
m.atom_int(TYPE_STRINGREF, idx)
else:
idx = len(m.stringtable)
m.stringtable[s] = idx
m.atom_str(TYPE_INTERNED, s)
else:
m.atom_str(TYPE_STRING, s)
marshal_w__Rope = marshal_w__String
def unmarshal_String(space, u, tc):
return space.wrap(u.get_str())
register(TYPE_STRING, unmarshal_String)
def unmarshal_interned(space, u, tc):
w_ret = space.wrap(u.get_str())
u.stringtable_w.append(w_ret)
w_intern = space.builtin.get('intern')
space.call_function(w_intern, w_ret)
return w_ret
register(TYPE_INTERNED, unmarshal_interned)
def unmarshal_stringref(space, u, tc):
idx = u.get_int()
try:
return u.stringtable_w[idx]
except IndexError:
raise_exception(space, 'bad marshal data')
register(TYPE_STRINGREF, unmarshal_stringref)
def marshal_w__Tuple(space, w_tuple, m):
m.start(TYPE_TUPLE)
items = w_tuple.wrappeditems
m.put_list_w(items, len(items))
def unmarshal_Tuple(space, u, tc):
items_w = u.get_list_w()
return space.newtuple(items_w)
register(TYPE_TUPLE, unmarshal_Tuple)
def marshal_w__List(space, w_list, m):
m.start(TYPE_LIST)
items = w_list.wrappeditems
m.put_list_w(items, len(items))
def unmarshal_List(space, u, tc):
items_w = u.get_list_w()
return space.newlist(items_w)
def finish_List(space, items_w, typecode):
return space.newlist(items_w)
register(TYPE_LIST, unmarshal_List)
def marshal_w__Dict(space, w_dict, m):
m.start(TYPE_DICT)
for w_key, w_value in w_dict.content.iteritems():
m.put_w_obj(w_key)
m.put_w_obj(w_value)
m.atom(TYPE_NULL)
def marshal_w__DictMulti(space, w_dict, m):
m.start(TYPE_DICT)
for w_tuple in w_dict.implementation.items():
w_key, w_value = space.unpacktuple(w_tuple, 2)
m.put_w_obj(w_key)
m.put_w_obj(w_value)
m.atom(TYPE_NULL)
def unmarshal_Dict(space, u, tc):
# since primitive lists are not optimized and we don't know
# the dict size in advance, use the dict's setitem instead
# of building a list of tuples.
w_dic = space.newdict()
while 1:
w_key = u.get_w_obj(True)
if w_key is None:
break
w_value = u.get_w_obj(False)
space.setitem(w_dic, w_key, w_value)
return w_dic
register(TYPE_DICT, unmarshal_Dict)
def unmarshal_NULL(self, u, tc):
return None
register(TYPE_NULL, unmarshal_NULL)
# this one is registered by hand:
def marshal_w_pycode(space, w_pycode, m):
m.start(TYPE_CODE)
# see pypy.interpreter.pycode for the layout
x = space.interp_w(PyCode, w_pycode)
m.put_int(x.co_argcount)
m.put_int(x.co_nlocals)
m.put_int(x.co_stacksize)
m.put_int(x.co_flags)
m.atom_str(TYPE_STRING, x.co_code)
m.start(TYPE_TUPLE)
m.put_list_w(x.co_consts_w, len(x.co_consts_w))
m.atom_strlist(TYPE_TUPLE, TYPE_INTERNED, [space.str_w(w_name) for w_name in x.co_names_w])
m.atom_strlist(TYPE_TUPLE, TYPE_INTERNED, x.co_varnames)
m.atom_strlist(TYPE_TUPLE, TYPE_INTERNED, x.co_freevars)
m.atom_strlist(TYPE_TUPLE, TYPE_INTERNED, x.co_cellvars)
m.atom_str(TYPE_INTERNED, x.co_filename)
m.atom_str(TYPE_INTERNED, x.co_name)
m.put_int(x.co_firstlineno)
m.atom_str(TYPE_STRING, x.co_lnotab)
StdObjSpace.MM.marshal_w.register(marshal_w_pycode, PyCode)
# helper for unmarshalling string lists of code objects.
# unfortunately they now can be interned or referenced,
# so we no longer can handle it in interp_marshal.atom_strlist
def unmarshal_str(u):
w_obj = u.get_w_obj(False)
try:
return u.space.str_w(w_obj)
except OperationError, e:
if e.match(u.space, u.space.w_TypeError):
u.raise_exc('invalid marshal data for code object')
else:
raise
def unmarshal_strlist(u, tc):
lng = u.atom_lng(tc)
res = [None] * lng
idx = 0
space = u.space
while idx < lng:
res[idx] = unmarshal_str(u)
idx += 1
return res
def unmarshal_pycode(space, u, tc):
argcount = u.get_int()
nlocals = u.get_int()
stacksize = u.get_int()
flags = u.get_int()
code = unmarshal_str(u)
u.start(TYPE_TUPLE)
consts_w = u.get_list_w()
names = unmarshal_strlist(u, TYPE_TUPLE)
varnames = unmarshal_strlist(u, TYPE_TUPLE)
freevars = unmarshal_strlist(u, TYPE_TUPLE)
cellvars = unmarshal_strlist(u, TYPE_TUPLE)
filename = unmarshal_str(u)
name = unmarshal_str(u)
firstlineno = u.get_int()
lnotab = unmarshal_str(u)
code = PyCode._code_new_w(space, argcount, nlocals, stacksize, flags,
code, consts_w, names, varnames, filename,
name, firstlineno, lnotab, freevars, cellvars)
return space.wrap(code)
register(TYPE_CODE, unmarshal_pycode)
app = gateway.applevel(r'''
def PyUnicode_EncodeUTF8(data):
import _codecs
return _codecs.utf_8_encode(data)[0]
def PyUnicode_DecodeUTF8(data):
import _codecs
return _codecs.utf_8_decode(data)[0]
''')
PyUnicode_EncodeUTF8 = app.interphook('PyUnicode_EncodeUTF8')
PyUnicode_DecodeUTF8 = app.interphook('PyUnicode_DecodeUTF8')
def marshal_w__Unicode(space, w_unicode, m):
s = space.str_w(PyUnicode_EncodeUTF8(space, w_unicode))
m.atom_str(TYPE_UNICODE, s)
def unmarshal_Unicode(space, u, tc):
return PyUnicode_DecodeUTF8(space, space.wrap(u.get_str()))
register(TYPE_UNICODE, unmarshal_Unicode)
# not directly supported:
def marshal_w_buffer(space, w_buffer, m):
s = space.str_w(space.str(w_buffer))
m.atom_str(TYPE_UNKNOWN, s)
handled_by_any.append( ('buffer', marshal_w_buffer) )
app = gateway.applevel(r'''
def string_to_buffer(s):
return buffer(s)
''')
string_to_buffer = app.interphook('string_to_buffer')
def unmarshal_buffer(space, u, tc):
w_s = space.wrap(u.get_str())
return string_to_buffer(space, w_s)
register(TYPE_UNKNOWN, unmarshal_buffer)
app = gateway.applevel(r'''
def set_to_list(theset):
return [item for item in theset]
def list_to_set(datalist, frozen=False):
if frozen:
return frozenset(datalist)
return set(datalist)
''')
set_to_list = app.interphook('set_to_list')
list_to_set = app.interphook('list_to_set')
# not directly supported:
def marshal_w_set(space, w_set, m):
w_lis = set_to_list(space, w_set)
# cannot access this list directly, because it's
# type is not exactly known through applevel.
lis_w = space.unpackiterable(w_lis)
m.start(TYPE_SET)
m.put_list_w(lis_w, len(lis_w))
handled_by_any.append( ('set', marshal_w_set) )
# not directly supported:
def marshal_w_frozenset(space, w_frozenset, m):
w_lis = set_to_list(space, w_frozenset)
lis_w = space.unpackiterable(w_lis)
m.start(TYPE_FROZENSET)
m.put_list_w(lis_w, len(lis_w))
handled_by_any.append( ('frozenset', marshal_w_frozenset) )
def unmarshal_set_frozenset(space, u, tc):
items_w = u.get_list_w()
if tc == TYPE_SET:
w_frozen = space.w_False
else:
w_frozen = space.w_True
w_lis = space.newlist(items_w)
return list_to_set(space, w_lis, w_frozen)
register(TYPE_SET + TYPE_FROZENSET, unmarshal_set_frozenset)
# dispatching for all not directly dispatched types
def marshal_w__ANY(space, w_obj, m):
w_type = space.type(w_obj)
for name, func in handled_by_any:
w_t = space.builtin.get(name)
if space.is_true(space.issubtype(w_type, w_t)):
func(space, w_obj, m)
break
else:
raise_exception(space, "unmarshallable object")
register_all(vars())
| Python |
from pypy.interpreter import gateway
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.register_all import register_all
from pypy.interpreter.error import OperationError
dict_copy = SMM('copy', 1,
doc='D.copy() -> a shallow copy of D')
dict_items = SMM('items', 1,
doc="D.items() -> list of D's (key, value) pairs, as"
' 2-tuples')
dict_keys = SMM('keys', 1,
doc="D.keys() -> list of D's keys")
dict_values = SMM('values', 1,
doc="D.values() -> list of D's values")
dict_has_key = SMM('has_key', 2,
doc='D.has_key(k) -> True if D has a key k, else False')
dict_clear = SMM('clear', 1,
doc='D.clear() -> None. Remove all items from D.')
dict_get = SMM('get', 3, defaults=(None,),
doc='D.get(k[,d]) -> D[k] if k in D, else d. d defaults'
' to None.')
dict_pop = SMM('pop', 2, w_varargs=True,
doc='D.pop(k[,d]) -> v, remove specified key and return'
' the corresponding value\nIf key is not found, d is'
' returned if given, otherwise KeyError is raised')
dict_popitem = SMM('popitem', 1,
doc='D.popitem() -> (k, v), remove and return some (key,'
' value) pair as a\n2-tuple; but raise KeyError if D'
' is empty')
dict_setdefault = SMM('setdefault', 3, defaults=(None,),
doc='D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d'
' if k not in D')
dict_update = SMM('update', 1, general__args__=True,
doc='D.update(E, **F) -> None. Update D from E and F:'
' for k in E: D[k] = E[k]\n(if E has keys else: for'
' (k, v) in E: D[k] = v) then: for k in F: D[k] ='
' F[k]')
dict_iteritems = SMM('iteritems', 1,
doc='D.iteritems() -> an iterator over the (key, value)'
' items of D')
dict_iterkeys = SMM('iterkeys', 1,
doc='D.iterkeys() -> an iterator over the keys of D')
dict_itervalues = SMM('itervalues', 1,
doc='D.itervalues() -> an iterator over the values of D')
dict_reversed = SMM('__reversed__', 1)
def dict_reversed__ANY(space, w_dict):
raise OperationError(space.w_TypeError, space.wrap('argument to reversed() must be a sequence'))
#dict_fromkeys = MultiMethod('fromkeys', 2, varargs=True)
# This can return when multimethods have been fixed
#dict_str = StdObjSpace.str
# default application-level implementations for some operations
# gateway is imported in the stdtypedef module
app = gateway.applevel('''
def update1(d, o):
if hasattr(o, 'keys'):
for k in o.keys():
d[k] = o[k]
else:
for k,v in o:
d[k] = v
def update(d, *args, **kwargs):
if len(args) == 1:
update1(d, args[0])
elif len(args) > 1:
raise TypeError("update takes at most 1 (non-keyword) argument")
if kwargs:
update1(d, kwargs)
def popitem(d):
k = d.keys()
if not k:
raise KeyError("popitem(): dictionary is empty")
k = k[0]
v = d[k]
del d[k]
return k, v
def get(d, k, v=None):
if k in d:
return d[k]
else:
return v
def setdefault(d, k, v=None):
if k in d:
return d[k]
else:
d[k] = v
return v
def pop(d, k, defaults): # XXX defaults is actually *defaults
if len(defaults) > 1:
raise TypeError, "pop expected at most 2 arguments, got %d" % (
1 + len(defaults))
try:
v = d[k]
del d[k]
except KeyError, e:
if defaults:
return defaults[0]
else:
raise e
return v
def iteritems(d):
return iter(d.items())
def iterkeys(d):
return iter(d.keys())
def itervalues(d):
return iter(d.values())
''', filename=__file__)
#XXX what about dict.fromkeys()?
dict_update__ANY = app.interphook("update")
dict_popitem__ANY = app.interphook("popitem")
dict_get__ANY_ANY_ANY = app.interphook("get")
dict_setdefault__ANY_ANY_ANY = app.interphook("setdefault")
dict_pop__ANY_ANY = app.interphook("pop")
dict_iteritems__ANY = app.interphook("iteritems")
dict_iterkeys__ANY = app.interphook("iterkeys")
dict_itervalues__ANY = app.interphook("itervalues")
update1 = app.interphook("update1")
register_all(vars(), globals())
# ____________________________________________________________
def descr__new__(space, w_dicttype, __args__):
w_obj = space.allocate_instance(space.DictObjectCls, w_dicttype)
space.DictObjectCls.__init__(w_obj, space)
return w_obj
# ____________________________________________________________
dict_typedef = StdTypeDef("dict",
__doc__ = '''dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object\'s
(key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)''',
__new__ = newmethod(descr__new__,
unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]),
__hash__ = no_hash_descr,
)
dict_typedef.registermethods(globals())
# ____________________________________________________________
def descr_dictiter__reduce__(w_self, space):
"""
This is a slightly special case of pickling.
Since iteration over a dict is a bit hairy,
we do the following:
- create a clone of the dict iterator
- run it to the original position
- collect all remaining elements into a list
At unpickling time, we just use that list
and create an iterator on it.
This is of course not the standard way.
XXX to do: remove this __reduce__ method and do
a registration with copy_reg, instead.
"""
from pypy.interpreter.mixedmodule import MixedModule
w_mod = space.getbuiltinmodule('_pickle_support')
mod = space.interp_w(MixedModule, w_mod)
new_inst = mod.get('dictiter_surrogate_new')
w_typeobj = space.gettypeobject(dictiter_typedef)
from pypy.interpreter.mixedmodule import MixedModule
if space.config.objspace.std.withmultidict:
raise OperationError(
space.w_RuntimeError,
space.wrap("cannot pickle dictiters with multidicts"))
else:
from pypy.objspace.std.dictobject import \
W_DictIter_Keys, W_DictIter_Values, W_DictIter_Items
# we cannot call __init__ since we don't have the original dict
if isinstance(w_self, W_DictIter_Keys):
w_clone = space.allocate_instance(W_DictIter_Keys, w_typeobj)
elif isinstance(w_self, W_DictIter_Values):
w_clone = space.allocate_instance(W_DictIter_Values, w_typeobj)
elif isinstance(w_self, W_DictIter_Items):
w_clone = space.allocate_instance(W_DictIter_Items, w_typeobj)
else:
msg = "unsupported dictiter type '%s' during pickling" % (w_self, )
raise OperationError(space.w_TypeError, space.wrap(msg))
w_clone.space = space
w_clone.content = w_self.content
w_clone.len = w_self.len
w_clone.pos = 0
w_clone.setup_iterator()
# spool until we have the same pos
while w_clone.pos < w_self.pos:
w_obj = w_clone.next_entry()
w_clone.pos += 1
stuff = [w_clone.next_entry() for i in range(w_clone.pos, w_clone.len)]
w_res = space.newlist(stuff)
tup = [
w_res
]
w_ret = space.newtuple([new_inst, space.newtuple(tup)])
return w_ret
# ____________________________________________________________
dictiter_typedef = StdTypeDef("dictionaryiterator",
__reduce__ = gateway.interp2app(descr_dictiter__reduce__,
unwrap_spec=[gateway.W_Root, gateway.ObjSpace]),
)
#note: registering in dictobject.py
### fragment for frame object left here
#w(10),
#w(self.co_argcount),
#w(self.co_nlocals),
#w(self.co_stacksize),
#w(self.co_flags),
#w(self.co_code),
#space.newtuple(self.co_consts_w),
#space.newtuple(self.co_names_w),
#space.newtuple([w(v) for v in self.co_varnames]),
#w(self.co_filename),
#w(self.co_name),
#w(self.co_firstlineno),
#w(self.co_lnotab),
#space.newtuple([w(v) for v in self.co_freevars]),
#space.newtuple([w(v) for v in self.co_cellvars]),
#hidden_applevel=False, magic = 62061 | 0x0a0d0000
| Python |
import sys
from pypy.interpreter import baseobjspace
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.register_all import register_all
from pypy.interpreter.error import OperationError
# indices multimehtod
slice_indices = SMM('indices', 2,
doc='S.indices(len) -> (start, stop, stride)\n\nAssuming a'
' sequence of length len, calculate the start and'
' stop\nindices, and the stride length of the extended'
' slice described by\nS. Out of bounds indices are'
' clipped in a manner consistent with the\nhandling of'
' normal slices.')
# utility functions
def _Eval_SliceIndex(space, w_int):
try:
return space.getindex_w(w_int, None) # clamp if long integer too large
except OperationError, err:
if not err.match(space, space.w_TypeError):
raise
raise OperationError(space.w_TypeError,
space.wrap("slice indices must be integers or "
"None or have an __index__ method"))
def adapt_bound(space, size, w_index):
index = _Eval_SliceIndex(space, w_index)
if index < 0:
index = index + size
if index < 0:
index = 0
if index > size:
index = size
return index
register_all(vars(), globals())
# ____________________________________________________________
def descr__new__(space, w_slicetype, args_w):
from pypy.objspace.std.sliceobject import W_SliceObject
w_start = space.w_None
w_stop = space.w_None
w_step = space.w_None
if len(args_w) == 1:
w_stop, = args_w
elif len(args_w) == 2:
w_start, w_stop = args_w
elif len(args_w) == 3:
w_start, w_stop, w_step = args_w
elif len(args_w) > 3:
raise OperationError(space.w_TypeError,
space.wrap("slice() takes at most 3 arguments"))
else:
raise OperationError(space.w_TypeError,
space.wrap("slice() takes at least 1 argument"))
w_obj = space.allocate_instance(W_SliceObject, w_slicetype)
W_SliceObject.__init__(w_obj, w_start, w_stop, w_step)
return w_obj
#
descr__new__.unwrap_spec = [baseobjspace.ObjSpace, baseobjspace.W_Root,
'args_w']
# ____________________________________________________________
def slicewprop(name):
def fget(space, w_obj):
from pypy.objspace.std.sliceobject import W_SliceObject
if not isinstance(w_obj, W_SliceObject):
raise OperationError(space.w_TypeError,
space.wrap("descriptor is for 'slice'"))
return getattr(w_obj, name)
return GetSetProperty(fget)
slice_typedef = StdTypeDef("slice",
__doc__ = '''slice([start,] stop[, step])
Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).''',
__new__ = newmethod(descr__new__),
__hash__ = no_hash_descr,
start = slicewprop('w_start'),
stop = slicewprop('w_stop'),
step = slicewprop('w_step'),
)
slice_typedef.registermethods(globals())
| Python |
_name_mappings = {
'and': 'and_',
'or': 'or_',
}
def register_all(module_dict, *alt_ns):
"""register implementations for multimethods.
By default a (name, object) pair of the given module dictionary
is registered on the multimethod 'name' of StdObjSpace.
If the name doesn't exist then the alternative namespace is tried
for registration.
"""
from pypy.objspace.std.objspace import StdObjSpace
from pypy.objspace.std.model import W_ANY, W_Object
namespaces = list(alt_ns) + [StdObjSpace.MM, StdObjSpace]
for name, obj in module_dict.items():
if name.startswith('app_'):
print "%s: direct app definitions deprecated" % name
if name.find('__')<1 or name.startswith('app_'):
continue
funcname, sig = name.split('__')
l=[]
for i in sig.split('_'):
if i == 'ANY': # just in case W_ANY is not in module_dict
icls = W_ANY
elif i == 'Object': # just in case W_Object is not in module_dict
icls = W_Object
else:
icls = (module_dict.get('W_%s' % i) or
module_dict.get('W_%sObject' % i))
if icls is None:
raise ValueError, \
"no W_%s or W_%sObject for the definition of %s" % (
i, i, name)
l.append(icls)
#XXX trying to be too clever at the moment for userobject.SpecialMethod
#if len(l) != obj.func_code.co_argcount-1:
# raise ValueError, \
# "function name %s doesn't specify exactly %d arguments" % (
# repr(name), obj.func_code.co_argcount-1)
funcname = _name_mappings.get(funcname, funcname)
func = hack_func_by_name(funcname, namespaces)
func.register(obj, *l)
add_extra_comparisons()
def hack_func_by_name(funcname, namespaces):
for ns in namespaces:
if isinstance(ns, dict):
if funcname in ns:
return ns[funcname]
else:
if hasattr(ns, funcname):
return getattr(ns, funcname)
#import typetype
#try:
# return getattr(typetype.W_TypeType, funcname)
#except AttributeError:
# pass # catches not only the getattr() but the typetype.W_TypeType
# # in case it is not fully imported yet :-((((
from pypy.objspace.std import objecttype
try:
return getattr(objecttype, funcname)
except AttributeError:
pass
raise NameError, ("trying hard but not finding a multimethod named %s" %
funcname)
def op_negated(function):
def op(space, w_1, w_2):
return space.not_(function(space, w_1, w_2))
return op
def op_swapped(function):
def op(space, w_1, w_2):
return function(space, w_2, w_1)
return op
def op_swapped_negated(function):
def op(space, w_1, w_2):
return space.not_(function(space, w_2, w_1))
return op
OPERATORS = ['lt', 'le', 'eq', 'ne', 'gt', 'ge']
OP_CORRESPONDANCES = [
('eq', 'ne', op_negated),
('lt', 'gt', op_swapped),
('le', 'ge', op_swapped),
('lt', 'ge', op_negated),
('le', 'gt', op_negated),
('lt', 'le', op_swapped_negated),
('gt', 'ge', op_swapped_negated),
]
for op1, op2, value in OP_CORRESPONDANCES[:]:
i = OP_CORRESPONDANCES.index((op1, op2, value))
OP_CORRESPONDANCES.insert(i+1, (op2, op1, value))
def add_extra_comparisons():
"""
Add the missing comparison operators if they were not explicitly
defined: eq <-> ne and lt <-> le <-> gt <-> ge.
We try to add them in the order defined by the OP_CORRESPONDANCES
table, thus favouring swapping the arguments over negating the result.
"""
from pypy.objspace.std.objspace import StdObjSpace
originalentries = {}
for op in OPERATORS:
originalentries[op] = getattr(StdObjSpace.MM, op).signatures()
for op1, op2, correspondance in OP_CORRESPONDANCES:
mirrorfunc = getattr(StdObjSpace.MM, op2)
for types in originalentries[op1]:
t1, t2 = types
if t1 is t2:
if not mirrorfunc.has_signature(types):
functions = getattr(StdObjSpace.MM, op1).getfunctions(types)
assert len(functions) == 1, ('Automatic'
' registration of comparison functions'
' only work when there is a single method for'
' the operation.')
#print 'adding %s <<<%s>>> %s as %s(%s)' % (
# t1, op2, t2,
# correspondance.func_name, functions[0].func_name)
mirrorfunc.register(
correspondance(functions[0]),
*types)
| Python |
# implement resizable arrays
# see "Resizable Arrays in Optimal time and Space"
# Brodnik, Carlsson, Demaine, Munro, Sedgewick, 1999
from pypy.objspace.std.listmultiobject import ListImplementation
import sys
import math
LOG2 = math.log(2)
NBITS = int(math.log(sys.maxint) / LOG2) + 2
LSBSTEPS = int(math.log(NBITS) / LOG2) + 1
def leftmost_set_bit(i):
# return int(math.log(i) / LOG2)
# do something fancy?
assert i > 0
shift = NBITS // 2
result = 0
for x in range(LSBSTEPS):
newi = i >> shift
if newi:
result += shift
i = newi
shift //= 2
return result
def decompose(i, k):
halfk_lower = k // 2
halfk_upper = halfk_lower + (k & 1)
mask1 = ((1 << halfk_lower) - 1) << halfk_upper
mask2 = ((1 << halfk_upper) - 1)
assert mask1 + mask2 == ((1 << k) - 1)
return ((i & mask1) >> halfk_upper), i & mask2
def find_block_index(i):
if i == 0:
return (0, 0)
k = leftmost_set_bit(i + 1)
b, e = decompose(i + 1, k)
x = k
m = (1 << (x // 2 + 1)) - 2 + (x & 1) * (1 << (x // 2))
return m + b, e
class FreeList(object):
def __init__(self):
self.freelist = {}
def alloc(self, size):
l = self.freelist.get(size, None)
if l is not None and l:
return l.pop()
return [None] * size
def dealloc(self, l):
size = len(l)
if size >= 2 ** 20:
return
if size in self.freelist:
self.freelist[size].append(l)
else:
self.freelist[size] = [l]
freelist = FreeList()
class SmartResizableListImplementation(ListImplementation):
def __init__(self, space):
self._length = 0
self.size_superblock = 1
self.size_datablock = 1
self.num_superblocks = 1 # "s" in the paper
self.num_datablocks = 1 # "d" in the paper
self.last_superblock_filled = 1
self.index_last = 0 # number of elements occupying last data block
self.data_blocks = [[None] * 1]
self.space = space
def length(self):
return self._length
def grow(self, items=1):
data_blocks = self.data_blocks
self._length += items
idx = self.num_datablocks - 1
assert idx >= 0
free_in_last_datablock = len(data_blocks[idx]) - self.index_last
while items > free_in_last_datablock:
items -= free_in_last_datablock
free_in_last_datablock = self.grow_block()
self.index_last += items
return (self.num_datablocks - 1, self.index_last - 1)
def grow_block(self):
data_blocks = self.data_blocks
if self.last_superblock_filled == self.size_superblock:
self.num_superblocks += 1
if self.num_superblocks % 2 == 1:
self.size_superblock *= 2
else:
self.size_datablock *= 2
self.last_superblock_filled = 0
if len(data_blocks) == self.num_datablocks:
data_blocks.append(freelist.alloc(self.size_datablock))
self.last_superblock_filled += 1
self.num_datablocks += 1
self.index_last = 0
return self.size_datablock
def shrink(self, items=1):
if items > self._length:
raise ValueError("cannot shrink by more items than the list has")
self._length -= items
data_blocks = self.data_blocks
while items > self.index_last:
items -= self.index_last
self.shrink_block()
self.index_last -= items
idx = self.num_datablocks - 1
assert idx >= 0
data_block = data_blocks[idx]
while items:
idx = self.index_last - 1 + items
assert idx >= 0
data_block[idx] = None
items -= 1
def shrink_block(self):
data_blocks = self.data_blocks
if len(data_blocks) > self.num_datablocks:
assert len(data_blocks) - self.num_datablocks == 1
freelist.dealloc(data_blocks.pop())
for i in range(self.index_last): #XXX consider when not to do this
idx = self.num_datablocks - 1
assert idx >= 0
data_blocks[idx][i] = None
self.num_datablocks -= 1
self.last_superblock_filled -= 1
if self.last_superblock_filled == 0:
self.num_superblocks -= 1
if self.num_superblocks % 2 == 0:
self.size_superblock //= 2
else:
self.size_datablock //= 2
self.last_superblock_filled = self.size_superblock
self.index_last = len(data_blocks[-2])
def getitem(self, i):
a, b = find_block_index(i)
return self.getitem_raw(a, b)
def getitem_raw(self, a, b):
assert a >= 0
assert b >= 0
return self.data_blocks[a][b]
def setitem(self, i, value):
a, b = find_block_index(i)
return self.setitem_raw(a, b, value)
def setitem_raw(self, a, b, value):
assert a >= 0
assert b >= 0
self.data_blocks[a][b] = value
def getitem_slice(self, start, stop):
l = stop - start
result = SmartResizableListImplementation(self.space)
result.grow(l)
for i in range(l):
result.setitem(i, self.getitem(i + start))
return result
def insert(self, i, w_item):
self.grow()
for x in range(self._length - 2, i - 1, -1):
self.setitem(x + 1, self.getitem(x))
self.setitem(i, w_item)
return self
def delitem(self, index):
for x in range(index + 1, self._length):
self.setitem(x - 1, self.getitem(x))
self.shrink()
return self
def delitem_slice(self, start, stop):
slicelength = stop - start
for x in range(stop, self._length):
self.setitem(x - slicelength, self.getitem(x))
self.shrink(slicelength)
return self
def append(self, w_item):
a, b = self.grow()
self.setitem_raw(a, b, w_item)
return self
def extend(self, other):
selflength = self._length
length = other.length()
self.grow(length)
for i in range(length):
self.setitem(selflength + i, other.getitem(i))
return self
# special cases:
def add(self, other):
result = self.copy()
result.extend(other)
return result
def get_list_w(self):
l = self._length
result = [None] * l
for i in range(l):
result[i] = self.getitem(i)
return result
# default implementations, can (but don't have to be) overridden:
def copy(self):
from pypy.rlib.objectmodel import instantiate
result = instantiate(SmartResizableListImplementation)
result._length = self._length
result.size_superblock = self.size_superblock
result.size_datablock = self.size_datablock
result.num_superblocks = self.num_superblocks
result.num_datablocks = self.num_datablocks
result.last_superblock_filled = self.last_superblock_filled
result.index_last = self.index_last
result.data_blocks = [l[:] for l in self.data_blocks]
result.space = self.space
return result
| Python |
"""
The full list of which Python types and which implementation we want
to provide in this version of PyPy, along with conversion rules.
"""
from pypy.objspace.std.multimethod import MultiMethodTable, FailedToImplement
from pypy.interpreter.baseobjspace import W_Root, ObjSpace
import pypy.interpreter.pycode
import pypy.interpreter.special
option_to_typename = {
"withsmallint" : ["smallintobject.W_SmallIntObject"],
"withstrslice" : ["strsliceobject.W_StringSliceObject"],
"withstrjoin" : ["strjoinobject.W_StringJoinObject"],
"withmultidict" : ["dictmultiobject.W_DictMultiObject",
"dictmultiobject.W_DictMultiIterObject"],
"withmultilist" : ["listmultiobject.W_ListMultiObject"],
"withrope" : ["ropeobject.W_RopeObject",
"ropeobject.W_RopeIterObject"],
"withrangelist" : ["rangeobject.W_RangeListObject",
"rangeobject.W_RangeIterObject"],
"withtproxy" : ["proxyobject.W_TransparentList",
"proxyobject.W_TransparentDict"],
}
class StdTypeModel:
def __init__(self, config):
"""NOT_RPYTHON: inititialization only"""
# All the Python types that we want to provide in this StdObjSpace
class result:
from pypy.objspace.std.objecttype import object_typedef
from pypy.objspace.std.booltype import bool_typedef
from pypy.objspace.std.inttype import int_typedef
from pypy.objspace.std.floattype import float_typedef
from pypy.objspace.std.complextype import complex_typedef
from pypy.objspace.std.settype import set_typedef
from pypy.objspace.std.frozensettype import frozenset_typedef
from pypy.objspace.std.tupletype import tuple_typedef
from pypy.objspace.std.listtype import list_typedef
from pypy.objspace.std.dicttype import dict_typedef
from pypy.objspace.std.basestringtype import basestring_typedef
from pypy.objspace.std.stringtype import str_typedef
from pypy.objspace.std.typetype import type_typedef
from pypy.objspace.std.slicetype import slice_typedef
from pypy.objspace.std.longtype import long_typedef
from pypy.objspace.std.unicodetype import unicode_typedef
from pypy.objspace.std.dictproxytype import dictproxy_typedef
from pypy.objspace.std.nonetype import none_typedef
from pypy.objspace.std.itertype import iter_typedef
self.pythontypes = [value for key, value in result.__dict__.items()
if not key.startswith('_')] # don't look
# The object implementations that we want to 'link' into PyPy must be
# imported here. This registers them into the multimethod tables,
# *before* the type objects are built from these multimethod tables.
from pypy.objspace.std import objectobject
from pypy.objspace.std import boolobject
from pypy.objspace.std import intobject
from pypy.objspace.std import floatobject
from pypy.objspace.std import complexobject
from pypy.objspace.std import setobject
from pypy.objspace.std import smallintobject
from pypy.objspace.std import tupleobject
from pypy.objspace.std import listobject
from pypy.objspace.std import dictobject
from pypy.objspace.std import dictmultiobject
from pypy.objspace.std import listmultiobject
from pypy.objspace.std import stringobject
from pypy.objspace.std import ropeobject
from pypy.objspace.std import strsliceobject
from pypy.objspace.std import strjoinobject
from pypy.objspace.std import typeobject
from pypy.objspace.std import sliceobject
from pypy.objspace.std import longobject
from pypy.objspace.std import noneobject
from pypy.objspace.std import iterobject
from pypy.objspace.std import unicodeobject
from pypy.objspace.std import dictproxyobject
from pypy.objspace.std import rangeobject
from pypy.objspace.std import proxyobject
from pypy.objspace.std import fake
import pypy.objspace.std.default # register a few catch-all multimethods
import pypy.objspace.std.marshal_impl # install marshal multimethods
# the set of implementation types
self.typeorder = {
objectobject.W_ObjectObject: [],
boolobject.W_BoolObject: [],
intobject.W_IntObject: [],
floatobject.W_FloatObject: [],
tupleobject.W_TupleObject: [],
listobject.W_ListObject: [],
dictobject.W_DictObject: [],
dictobject.W_DictIterObject: [],
stringobject.W_StringObject: [],
typeobject.W_TypeObject: [],
sliceobject.W_SliceObject: [],
longobject.W_LongObject: [],
noneobject.W_NoneObject: [],
iterobject.W_SeqIterObject: [],
iterobject.W_ReverseSeqIterObject: [],
unicodeobject.W_UnicodeObject: [],
dictproxyobject.W_DictProxyObject: [],
pypy.interpreter.pycode.PyCode: [],
pypy.interpreter.special.Ellipsis: [],
}
self.typeorder[complexobject.W_ComplexObject] = []
self.typeorder[setobject.W_SetObject] = []
self.typeorder[setobject.W_FrozensetObject] = []
self.typeorder[setobject.W_SetIterObject] = []
self.imported_but_not_registered = {
dictobject.W_DictObject: True,
dictobject.W_DictIterObject: True,
listobject.W_ListObject: True,
stringobject.W_StringObject: True,
}
for option, value in config.objspace.std:
if option.startswith("with") and option in option_to_typename:
for classname in option_to_typename[option]:
implcls = eval(classname)
if value:
self.typeorder[implcls] = []
else:
self.imported_but_not_registered[implcls] = True
if config.objspace.std.withmultidict:
del self.typeorder[dictobject.W_DictObject]
del self.typeorder[dictobject.W_DictIterObject]
if config.objspace.std.withmultilist:
del self.typeorder[listobject.W_ListObject]
if config.objspace.std.withrope:
del self.typeorder[stringobject.W_StringObject]
#check if we missed implementations
from pypy.objspace.std.objspace import _registered_implementations
for implcls in _registered_implementations:
assert (implcls in self.typeorder or
implcls in self.imported_but_not_registered), (
"please add %r in StdTypeModel.typeorder" % (implcls,))
for type in self.typeorder:
self.typeorder[type].append((type, None))
# register the order in which types are converted into each others
# when trying to dispatch multimethods.
# XXX build these lists a bit more automatically later
if config.objspace.std.withsmallint:
self.typeorder[boolobject.W_BoolObject] += [
(smallintobject.W_SmallIntObject, boolobject.delegate_Bool2SmallInt),
]
self.typeorder[smallintobject.W_SmallIntObject] += [
(intobject.W_IntObject, smallintobject.delegate_SmallInt2Int),
(longobject.W_LongObject, smallintobject.delegate_SmallInt2Long),
(floatobject.W_FloatObject, smallintobject.delegate_SmallInt2Float),
(complexobject.W_ComplexObject, smallintobject.delegate_SmallInt2Complex),
]
self.typeorder[boolobject.W_BoolObject] += [
(intobject.W_IntObject, boolobject.delegate_Bool2IntObject),
(longobject.W_LongObject, longobject.delegate_Bool2Long),
(floatobject.W_FloatObject, floatobject.delegate_Bool2Float),
(complexobject.W_ComplexObject, complexobject.delegate_Bool2Complex),
]
self.typeorder[intobject.W_IntObject] += [
(longobject.W_LongObject, longobject.delegate_Int2Long),
(floatobject.W_FloatObject, floatobject.delegate_Int2Float),
(complexobject.W_ComplexObject, complexobject.delegate_Int2Complex),
]
self.typeorder[longobject.W_LongObject] += [
(floatobject.W_FloatObject, floatobject.delegate_Long2Float),
(complexobject.W_ComplexObject,
complexobject.delegate_Long2Complex),
]
self.typeorder[floatobject.W_FloatObject] += [
(complexobject.W_ComplexObject,
complexobject.delegate_Float2Complex),
]
if not config.objspace.std.withrope:
self.typeorder[stringobject.W_StringObject] += [
(unicodeobject.W_UnicodeObject, unicodeobject.delegate_String2Unicode),
]
else:
self.typeorder[ropeobject.W_RopeObject] += [
(unicodeobject.W_UnicodeObject, unicodeobject.delegate_String2Unicode),
]
if config.objspace.std.withstrslice:
self.typeorder[strsliceobject.W_StringSliceObject] += [
(stringobject.W_StringObject,
strsliceobject.delegate_slice2str),
(unicodeobject.W_UnicodeObject,
strsliceobject.delegate_slice2unicode),
]
if config.objspace.std.withstrjoin:
self.typeorder[strjoinobject.W_StringJoinObject] += [
(stringobject.W_StringObject,
strjoinobject.delegate_join2str),
(unicodeobject.W_UnicodeObject,
strjoinobject.delegate_join2unicode)
]
if config.objspace.std.withrangelist:
self.typeorder[rangeobject.W_RangeListObject] += [
(listobject.W_ListObject,
rangeobject.delegate_range2list),
]
# put W_Root everywhere
self.typeorder[W_Root] = []
for type in self.typeorder:
from pypy.objspace.std import stdtypedef
if type is not W_Root and isinstance(type.typedef, stdtypedef.StdTypeDef):
self.typeorder[type].append((type.typedef.any, None))
self.typeorder[type].append((W_Root, None))
# ____________________________________________________________
# Prebuilt common integer values
if config.objspace.std.withprebuiltint:
intobject.W_IntObject.PREBUILT = []
for i in range(config.objspace.std.prebuiltintfrom,
config.objspace.std.prebuiltintto):
intobject.W_IntObject.PREBUILT.append(intobject.W_IntObject(i))
del i
else:
intobject.W_IntObject.PREBUILT = None
# ____________________________________________________________
# ____________________________________________________________
W_ANY = W_Root
class W_Object(W_Root):
"Parent base class for wrapped objects provided by the StdObjSpace."
# Note that not all wrapped objects in the interpreter inherit from
# W_Object. (They inherit from W_Root.)
__slots__ = ()
def __repr__(self):
s = '%s(%s)' % (
self.__class__.__name__,
#', '.join(['%s=%r' % keyvalue for keyvalue in self.__dict__.items()])
getattr(self, 'name', '')
)
w_cls = getattr(self, 'w__class__', None)
if w_cls is not None and w_cls is not self:
s += ' instance of %s' % self.w__class__
return '<%s>' % s
def unwrap(w_self, space):
raise UnwrapError, 'cannot unwrap %r' % (w_self,)
class UnwrapError(Exception):
pass
class StdObjSpaceMultiMethod(MultiMethodTable):
def __init__(self, operatorsymbol, arity, specialnames=None, **extras):
"""NOT_RPYTHON: cannot create new multimethods dynamically.
"""
MultiMethodTable.__init__(self, arity, W_ANY,
argnames_before = ['space'])
self.operatorsymbol = operatorsymbol
if specialnames is None:
specialnames = [operatorsymbol]
self.specialnames = specialnames # e.g. ['__xxx__', '__rxxx__']
self.extras = extras
# transform '+' => 'add' etc.
for line in ObjSpace.MethodTable:
realname, symbolname = line[:2]
if symbolname == operatorsymbol:
self.name = realname
break
else:
self.name = operatorsymbol
if extras.get('general__args__', False):
self.argnames_after = ['__args__']
if extras.get('w_varargs', False):
self.argnames_after = ['w_args']
if extras.get('varargs_w', False):
self.argnames_after = ['args_w']
self.argnames_after += extras.get('extra_args', [])
def install_not_sliced(self, typeorder, baked_perform_call=True):
return self.install(prefix = '__mm_' + self.name,
list_of_typeorders = [typeorder]*self.arity,
baked_perform_call=baked_perform_call)
| Python |
from pypy.objspace.std.objspace import *
class W_ObjectObject(W_Object):
"""Instances of this class are what the user can directly see with an
'object()' call."""
from pypy.objspace.std.objecttype import object_typedef as typedef
# ____________________________________________________________
register_all(vars())
| Python |
"""
Reviewed 03-06-22
All common dictionary methods are correctly implemented,
tested, and complete. The only missing feature is support
for order comparisons.
"""
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
from pypy.rlib.objectmodel import r_dict
class W_DictObject(W_Object):
from pypy.objspace.std.dicttype import dict_typedef as typedef
def __init__(w_self, space, w_otherdict=None):
if w_otherdict is None:
w_self.content = r_dict(space.eq_w, space.hash_w)
else:
w_self.content = w_otherdict.content.copy()
def initialize_content(w_self, list_pairs_w):
for w_k, w_v in list_pairs_w:
w_self.content[w_k] = w_v
def __repr__(w_self):
""" representation for debugging purposes """
return "%s(%s)" % (w_self.__class__.__name__, w_self.content)
def unwrap(w_dict, space):
result = {}
for w_key, w_value in w_dict.content.items():
# generic mixed types unwrap
result[space.unwrap(w_key)] = space.unwrap(w_value)
return result
def len(w_self):
return len(w_self.content)
def get(w_dict, w_lookup, w_default):
return w_dict.content.get(w_lookup, w_default)
def missing_method(w_dict, space, w_key):
if not space.is_w(space.type(w_dict), space.w_dict):
w_missing = space.lookup(w_dict, "__missing__")
if w_missing is None:
return None
return space.call_function(w_missing, w_dict, w_key)
else:
return None
def set_str_keyed_item(w_dict, w_key, w_value, shadows_type=True):
w_dict.content[w_key] = w_value
registerimplementation(W_DictObject)
def init__Dict(space, w_dict, __args__):
w_src, w_kwds = __args__.parse('dict',
(['seq_or_map'], None, 'kwargs'), # signature
[W_DictObject(space)]) # default argument
# w_dict.content.clear() - disabled only for CPython compatibility
if space.findattr(w_src, space.wrap("keys")) is None:
list_of_w_pairs = space.unpackiterable(w_src)
for w_pair in list_of_w_pairs:
pair = space.unpackiterable(w_pair)
if len(pair)!=2:
raise OperationError(space.w_ValueError,
space.wrap("dict() takes a sequence of pairs"))
w_k, w_v = pair
w_dict.content[w_k] = w_v
else:
if space.is_true(w_src):
from pypy.objspace.std.dicttype import update1
update1(space, w_dict, w_src)
if space.is_true(w_kwds):
from pypy.objspace.std.dicttype import update1
update1(space, w_dict, w_kwds)
def getitem__Dict_ANY(space, w_dict, w_lookup):
try:
return w_dict.content[w_lookup]
except KeyError:
w_missing_item = w_dict.missing_method(space, w_lookup)
if w_missing_item is None:
raise OperationError(space.w_KeyError, w_lookup)
else:
return w_missing_item
def setitem__Dict_ANY_ANY(space, w_dict, w_newkey, w_newvalue):
w_dict.content[w_newkey] = w_newvalue
def delitem__Dict_ANY(space, w_dict, w_lookup):
try:
del w_dict.content[w_lookup]
except KeyError:
raise OperationError(space.w_KeyError, w_lookup)
def len__Dict(space, w_dict):
return space.wrap(len(w_dict.content))
def contains__Dict_ANY(space, w_dict, w_lookup):
return space.newbool(w_lookup in w_dict.content)
dict_has_key__Dict_ANY = contains__Dict_ANY
def iter__Dict(space, w_dict):
return W_DictIter_Keys(space, w_dict)
def eq__Dict_Dict(space, w_left, w_right):
if space.is_w(w_left, w_right):
return space.w_True
if len(w_left.content) != len(w_right.content):
return space.w_False
for w_key, w_val in w_left.content.iteritems():
try:
w_rightval = w_right.content[w_key]
except KeyError:
return space.w_False
if not space.eq_w(w_val, w_rightval):
return space.w_False
return space.w_True
def characterize(space, acontent, bcontent):
""" (similar to CPython)
returns the smallest key in acontent for which b's value is different or absent and this value """
w_smallest_diff_a_key = None
w_its_value = None
for w_key, w_val in acontent.iteritems():
if w_smallest_diff_a_key is None or space.is_true(space.lt(w_key, w_smallest_diff_a_key)):
try:
w_bvalue = bcontent[w_key]
except KeyError:
w_its_value = w_val
w_smallest_diff_a_key = w_key
else:
if not space.eq_w(w_val, w_bvalue):
w_its_value = w_val
w_smallest_diff_a_key = w_key
return w_smallest_diff_a_key, w_its_value
def lt__Dict_Dict(space, w_left, w_right):
# Different sizes, no problem
leftcontent = w_left.content
rightcontent = w_right.content
if len(leftcontent) < len(rightcontent):
return space.w_True
if len(leftcontent) > len(rightcontent):
return space.w_False
# Same size
w_leftdiff, w_leftval = characterize(space, leftcontent, rightcontent)
if w_leftdiff is None:
return space.w_False
w_rightdiff, w_rightval = characterize(space, rightcontent, leftcontent)
if w_rightdiff is None:
# w_leftdiff is not None, w_rightdiff is None
return space.w_True
w_res = space.lt(w_leftdiff, w_rightdiff)
if (not space.is_true(w_res) and
space.eq_w(w_leftdiff, w_rightdiff) and
w_rightval is not None):
w_res = space.lt(w_leftval, w_rightval)
return w_res
def dict_copy__Dict(space, w_self):
return W_DictObject(space, w_self)
def dict_items__Dict(space, w_self):
return space.newlist([ space.newtuple([w_key, w_value])
for w_key, w_value in w_self.content.iteritems() ])
def dict_keys__Dict(space, w_self):
return space.newlist(w_self.content.keys())
def dict_values__Dict(space, w_self):
return space.newlist(w_self.content.values())
def dict_iteritems__Dict(space, w_self):
return W_DictIter_Items(space, w_self)
def dict_iterkeys__Dict(space, w_self):
return W_DictIter_Keys(space, w_self)
def dict_itervalues__Dict(space, w_self):
return W_DictIter_Values(space, w_self)
def dict_clear__Dict(space, w_self):
w_self.content.clear()
def dict_get__Dict_ANY_ANY(space, w_dict, w_lookup, w_default):
return w_dict.content.get(w_lookup, w_default)
app = gateway.applevel('''
def dictrepr(currently_in_repr, d):
# Now we only handle one implementation of dicts, this one.
# The fix is to move this to dicttype.py, and do a
# multimethod lookup mapping str to StdObjSpace.str
# This cannot happen until multimethods are fixed. See dicttype.py
dict_id = id(d)
if dict_id in currently_in_repr:
return '{...}'
currently_in_repr[dict_id] = 1
try:
items = []
# XXX for now, we cannot use iteritems() at app-level because
# we want a reasonable result instead of a RuntimeError
# even if the dict is mutated by the repr() in the loop.
for k, v in d.items():
items.append(repr(k) + ": " + repr(v))
return "{" + ', '.join(items) + "}"
finally:
try:
del currently_in_repr[dict_id]
except:
pass
''', filename=__file__)
dictrepr = app.interphook("dictrepr")
def repr__Dict(space, w_dict):
if len(w_dict.content) == 0:
return space.wrap('{}')
w_currently_in_repr = space.getexecutioncontext()._py_repr
return dictrepr(space, w_currently_in_repr, w_dict)
# ____________________________________________________________
# Iteration
class W_DictIterObject(W_Object):
from pypy.objspace.std.dicttype import dictiter_typedef as typedef
def __init__(w_self, space, w_dictobject):
w_self.space = space
w_self.content = content = w_dictobject.content
w_self.len = len(content)
w_self.pos = 0
w_self.setup_iterator()
def setup_iterator(w_self):
raise NotImplementedError("abstract base class")
def next_entry(w_self):
raise NotImplementedError("abstract base class")
registerimplementation(W_DictIterObject)
class W_DictIter_Keys(W_DictIterObject):
def setup_iterator(w_self):
w_self.iterator = w_self.content.iterkeys()
def next_entry(w_self):
# note that this 'for' loop only runs once, at most
for w_key in w_self.iterator:
return w_key
else:
return None
class W_DictIter_Values(W_DictIterObject):
def setup_iterator(w_self):
w_self.iterator = w_self.content.itervalues()
def next_entry(w_self):
# note that this 'for' loop only runs once, at most
for w_value in w_self.iterator:
return w_value
else:
return None
class W_DictIter_Items(W_DictIterObject):
def setup_iterator(w_self):
w_self.iterator = w_self.content.iteritems()
def next_entry(w_self):
# note that this 'for' loop only runs once, at most
for w_key, w_value in w_self.iterator:
return w_self.space.newtuple([w_key, w_value])
else:
return None
def iter__DictIterObject(space, w_dictiter):
return w_dictiter
def next__DictIterObject(space, w_dictiter):
content = w_dictiter.content
if content is not None:
if w_dictiter.len != len(content):
w_dictiter.len = -1 # Make this error state sticky
raise OperationError(space.w_RuntimeError,
space.wrap("dictionary changed size during iteration"))
# look for the next entry
try:
w_result = w_dictiter.next_entry()
except RuntimeError:
# it's very likely the underlying dict changed during iteration
raise OperationError(space.w_RuntimeError,
space.wrap("dictionary changed during iteration"))
if w_result is not None:
w_dictiter.pos += 1
return w_result
# no more entries
w_dictiter.content = None
raise OperationError(space.w_StopIteration, space.w_None)
def len__DictIterObject(space, w_dictiter):
content = w_dictiter.content
if content is None or w_dictiter.len == -1:
return space.wrap(0)
return space.wrap(w_dictiter.len - w_dictiter.pos)
# ____________________________________________________________
from pypy.objspace.std import dicttype
register_all(vars(), dicttype)
| Python |
""" transparent.py - Several transparent proxy helpers
"""
from pypy.interpreter import gateway
from pypy.interpreter.function import Function
from pypy.interpreter.error import OperationError
from pypy.objspace.std.proxyobject import *
from pypy.objspace.std.typeobject import W_TypeObject
def proxy(space, w_type, w_controller):
"""tproxy(typ, controller) -> obj
Return something that looks like it is of type typ. Its behaviour is
completely controlled by the controller."""
from pypy.interpreter.typedef import Function, PyTraceback, PyFrame, \
PyCode, GeneratorIterator
if not space.is_true(space.callable(w_controller)):
raise OperationError(space.w_TypeError, space.wrap("controller should be function"))
if isinstance(w_type, W_TypeObject):
if space.is_true(space.issubtype(w_type, space.w_list)):
return W_TransparentList(space, w_type, w_controller)
if space.is_true(space.issubtype(w_type, space.w_dict)):
return W_TransparentDict(space, w_type, w_controller)
if space.is_true(space.issubtype(w_type, space.gettypeobject(Function.typedef))):
return W_TransparentFunction(space, w_type, w_controller)
if space.is_true(space.issubtype(w_type, space.gettypeobject(PyTraceback.typedef))):
return W_TransparentTraceback(space, w_type, w_controller)
if space.is_true(space.issubtype(w_type, space.gettypeobject(PyFrame.typedef))):
return W_TransparentFrame(space, w_type, w_controller)
if space.is_true(space.issubtype(w_type, space.gettypeobject(GeneratorIterator.typedef))):
return W_TransparentGenerator(space, w_type, w_controller)
if space.is_true(space.issubtype(w_type, space.gettypeobject(PyCode.typedef))):
return W_TransparentCode(space, w_type, w_controller)
if w_type.instancetypedef is space.w_object.instancetypedef:
return W_Transparent(space, w_type, w_controller)
else:
raise OperationError(space.w_TypeError, space.wrap("type expected as first argument"))
#return type_cache[w_type or w_type.w_bestbase]
raise OperationError(space.w_TypeError, space.wrap("Object type %s could not "\
"be wrapped (YET)" % w_type.getname(space, "?")))
def proxy_controller(space, w_object):
"""get_tproxy_controller(obj) -> controller
If obj is really a transparent proxy, return its controller. Otherwise return
None."""
if isinstance(w_object, W_Transparent):
return w_object.w_controller
if isinstance(w_object, W_TransparentObject):
return w_object.w_controller
return None
app_proxy = gateway.interp2app(proxy, unwrap_spec=[gateway.ObjSpace, gateway.W_Root, \
gateway.W_Root])
app_proxy_controller = gateway.interp2app(proxy_controller, unwrap_spec=[gateway.ObjSpace, gateway.W_Root])
| Python |
from pypy.objspace.std.stdtypedef import *
# ____________________________________________________________
none_typedef = StdTypeDef("NoneType",
)
| Python |
"""
Pure Python implementation of string utilities.
"""
from pypy.rlib.rarithmetic import ovfcheck, break_up_float, parts_to_float
from pypy.interpreter.error import OperationError
import math
# XXX factor more functions out of stringobject.py.
# This module is independent from PyPy.
def strip_spaces(s):
# XXX this is not locale-dependent
p = 0
q = len(s)
while p < q and s[p] in ' \f\n\r\t\v':
p += 1
while p < q and s[q-1] in ' \f\n\r\t\v':
q -= 1
assert q >= p # annotator hint, don't remove
return s[p:q]
class ParseStringError(Exception):
def __init__(self, msg):
self.msg = msg
class ParseStringOverflowError(Exception):
def __init__(self, parser):
self.parser = parser
# iterator-like class
class NumberStringParser:
def error(self):
if self.literal:
raise ParseStringError, 'invalid literal for %s(): %s' % (self.fname, self.literal)
else:
raise ParseStringError, 'empty string for %s()' % (self.fname,)
def __init__(self, s, literal, base, fname):
self.literal = literal
self.fname = fname
sign = 1
if s.startswith('-'):
sign = -1
s = strip_spaces(s[1:])
elif s.startswith('+'):
s = strip_spaces(s[1:])
self.sign = sign
if base == 0:
if s.startswith('0x') or s.startswith('0X'):
base = 16
elif s.startswith('0'):
base = 8
else:
base = 10
elif base < 2 or base > 36:
raise ParseStringError, "%s() base must be >= 2 and <= 36" % (fname,)
self.base = base
if not s:
self.error()
if base == 16 and (s.startswith('0x') or s.startswith('0X')):
s = s[2:]
self.s = s
self.n = len(s)
self.i = 0
def rewind(self):
self.i = 0
def next_digit(self): # -1 => exhausted
if self.i < self.n:
c = self.s[self.i]
digit = ord(c)
if '0' <= c <= '9':
digit -= ord('0')
elif 'A' <= c <= 'Z':
digit = (digit - ord('A')) + 10
elif 'a' <= c <= 'z':
digit = (digit - ord('a')) + 10
else:
self.error()
if digit >= self.base:
self.error()
self.i += 1
return digit
else:
return -1
def string_to_int(s, base=10):
"""Utility to converts a string to an integer (or possibly a long).
If base is 0, the proper base is guessed based on the leading
characters of 's'. Raises ParseStringError in case of error.
"""
s = literal = strip_spaces(s)
p = NumberStringParser(s, literal, base, 'int')
base = p.base
result = 0
while True:
digit = p.next_digit()
if digit == -1:
try:
result = ovfcheck(p.sign * result)
except OverflowError:
raise ParseStringOverflowError(p)
else:
return result
try:
result = ovfcheck(result * base)
result = ovfcheck(result + digit)
except OverflowError:
raise ParseStringOverflowError(p)
def string_to_long(space, s, base=10, parser=None):
return string_to_w_long(space, s, base, parser).longval()
def string_to_w_long(space, s, base=10, parser=None):
"""As string_to_int(), but ignores an optional 'l' or 'L' suffix."""
if parser is None:
s = literal = strip_spaces(s)
if (s.endswith('l') or s.endswith('L')) and base < 22:
# in base 22 and above, 'L' is a valid digit! try: long('L',22)
s = s[:-1]
p = NumberStringParser(s, literal, base, 'long')
else:
p = parser
w_base = space.newlong(p.base)
w_result = space.newlong(0)
while True:
digit = p.next_digit()
if digit == -1:
if p.sign == -1:
w_result = space.neg(w_result)
# XXX grumble
from pypy.objspace.std.longobject import W_LongObject
assert isinstance(w_result, W_LongObject)
return w_result
w_result = space.add(space.mul(w_result,w_base), space.newlong(digit))
def string_to_float(s):
"""
Conversion of string to float.
This version tries to only raise on invalid literals.
Overflows should be converted to infinity whenever possible.
"""
s = strip_spaces(s)
if not s:
raise ParseStringError("empty string for float()")
# 1) parse the string into pieces.
try:
sign, before_point, after_point, exponent = break_up_float(s)
except ValueError:
raise ParseStringError("invalid literal for float()")
if not before_point and not after_point:
raise ParseStringError("invalid literal for float()")
try:
return parts_to_float(sign, before_point, after_point, exponent)
except ValueError:
raise ParseStringError("invalid literal for float()")
# Tim's comment:
# 57 bits are more than needed in any case.
# to allow for some rounding, we take one
# digit more.
# In the PyPy case, we can compute everything at compile time:
# XXX move this stuff to some central place, it is now also
# in _float_formatting.
def calc_mantissa_bits():
bits = 1 # I know it is almost always 53, but let it compute...
while 1:
pattern = (1L << bits) - 1
comp = long(float(pattern))
if comp != pattern:
return bits - 1
bits += 1
MANTISSA_BITS = calc_mantissa_bits()
del calc_mantissa_bits
MANTISSA_DIGITS = len(str( (1L << MANTISSA_BITS)-1 )) + 1
# we keep this version for reference.
def applevel_string_to_float(s):
"""
Conversion of string to float.
This version tries to only raise on invalid literals.
Overflows should be converted to infinity whenever possible.
"""
# this version was triggered by Python 2.4 which adds
# a test that breaks on overflow.
# XXX The test still breaks for a different reason:
# float must implement rich comparisons, where comparison
# between infinity and a too large long does not overflow!
# The problem:
# there can be extreme notations of floats which are not
# infinity.
# For instance, this works in CPython:
# float('1' + '0'*1000 + 'e-1000')
# should evaluate to 1.0.
# note: float('1' + '0'*10000 + 'e-10000')
# does not work in CPython, but PyPy can do it, now.
# The idea:
# in order to compensate between very long digit strings
# and extreme exponent numbers, we try to avoid overflows
# by adjusting the exponent by the number of mantissa
# digits. For simplicity, all computations are done in
# long math.
# The plan:
# 1) parse the string into pieces.
# 2) pre-calculate digit exponent dexp.
# 3) truncate and adjust dexp.
# 4) compute the exponent and truncate to +-400.
# 5) compute the value using long math and proper rounding.
# Positive results:
# The algorithm appears appears to produce correct round-trip
# values for the perfect input of _float_formatting.
# Note:
# XXX: the builtin rounding of long->float does not work, correctly.
# Ask Tim Peters for the reasons why no correct rounding is done.
# XXX: limitations:
# - It is possibly not too efficient.
# - Really optimum results need a more sophisticated algorithm
# like Bellerophon from William D. Clinger, cf.
# http://citeseer.csail.mit.edu/clinger90how.html
s = strip_spaces(s)
if not s:
raise ParseStringError("empty string for float()")
# 1) parse the string into pieces.
try:
sign, before_point, after_point, exponent = break_up_float(s)
except ValueError:
raise ParseStringError("invalid literal for float()")
digits = before_point + after_point
if digits:
raise ParseStringError("invalid literal for float()")
# 2) pre-calculate digit exponent dexp.
dexp = len(before_point)
# 3) truncate and adjust dexp.
p = 0
plim = dexp + len(after_point)
while p < plim and digits[p] == '0':
p += 1
dexp -= 1
digits = digits[p : p + MANTISSA_DIGITS]
p = len(digits) - 1
while p >= 0 and digits[p] == '0':
p -= 1
dexp -= p + 1
digits = digits[:p+1]
if len(digits) == 0:
digits = '0'
# 4) compute the exponent and truncate to +-400
if not exponent:
exponent = '0'
e = long(exponent) + dexp
if e >= 400:
e = 400
elif e <= -400:
e = -400
# 5) compute the value using long math and proper rounding.
lr = long(digits)
if e >= 0:
bits = 0
m = lr * 10L ** e
else:
# compute a sufficiently large scale
prec = MANTISSA_DIGITS * 2 + 22 # 128, maybe
bits = - (int(math.ceil(-e / math.log10(2.0) - 1e-10)) + prec)
scale = 2L ** -bits
pten = 10L ** -e
m = (lr * scale) // pten
# we now have a fairly large mantissa.
# Shift it and round the last bit.
# first estimate the bits and do a big shift
if m:
mbits = int(math.ceil(math.log(m, 2) - 1e-10))
needed = MANTISSA_BITS
if mbits > needed:
if mbits > needed+1:
shifted = mbits - (needed+1)
m >>= shifted
bits += shifted
# do the rounding
bits += 1
m = (m >> 1) + (m & 1)
try:
r = math.ldexp(m, bits)
except OverflowError:
r = 1e200 * 1e200 # produce inf, hopefully
if sign == '-':
r = -r
return r
# the "real" implementation.
# for comments, see above.
# XXX probably this very specific thing should go into longobject?
def interp_string_to_float(space, s):
"""
Conversion of string to float.
This version tries to only raise on invalid literals.
Overflows should be converted to infinity whenever possible.
Expects an unwrapped string and return an unwrapped float.
"""
s = strip_spaces(s)
if not s:
raise OperationError(space.w_ValueError, space.wrap(
"empty string for float()"))
# 1) parse the string into pieces.
try:
sign, before_point, after_point, exponent = break_up_float(s)
except ValueError:
raise ParseStringError("invalid literal for float()")
digits = before_point + after_point
if not digits:
raise ParseStringError("invalid literal for float()")
# 2) pre-calculate digit exponent dexp.
dexp = len(before_point)
# 3) truncate and adjust dexp.
p = 0
plim = dexp + len(after_point)
while p < plim and digits[p] == '0':
p += 1
dexp -= 1
digits = digits[p : p + MANTISSA_DIGITS]
p = len(digits) - 1
while p >= 0 and digits[p] == '0':
p -= 1
dexp -= p + 1
p += 1
assert p >= 0
digits = digits[:p]
if len(digits) == 0:
digits = '0'
# a few abbreviations
from pypy.objspace.std import longobject
mklong = longobject.W_LongObject.fromint
d2long = longobject.W_LongObject.fromdecimalstr
adlong = longobject.add__Long_Long
longup = longobject.pow__Long_Long_None
multip = longobject.mul__Long_Long
divide = longobject.div__Long_Long
lshift = longobject.lshift__Long_Long
rshift = longobject.rshift__Long_Long
# 4) compute the exponent and truncate to +-400
if not exponent:
exponent = '0'
w_le = d2long(exponent)
w_le = adlong(space, w_le, mklong(space, dexp))
try:
e = w_le.toint()
except OverflowError:
# XXX poking at internals
e = w_le.num.sign * 400
if e >= 400:
e = 400
elif e <= -400:
e = -400
# 5) compute the value using long math and proper rounding.
w_lr = d2long(digits)
w_10 = mklong(space, 10)
w_1 = mklong(space, 1)
if e >= 0:
bits = 0
w_pten = longup(space, w_10, mklong(space, e), space.w_None)
w_m = multip(space, w_lr, w_pten)
else:
# compute a sufficiently large scale
prec = MANTISSA_DIGITS * 2 + 22 # 128, maybe
bits = - (int(math.ceil(-e / math.log10(2.0) - 1e-10)) + prec)
w_scale = lshift(space, w_1, mklong(space, -bits))
w_pten = longup(space, w_10, mklong(space, -e), None)
w_tmp = multip(space, w_lr, w_scale)
w_m = divide(space, w_tmp, w_pten)
# we now have a fairly large mantissa.
# Shift it and round the last bit.
# first estimate the bits and do a big shift
mbits = w_m._count_bits()
needed = MANTISSA_BITS
if mbits > needed:
if mbits > needed+1:
shifted = mbits - (needed+1)
w_m = rshift(space, w_m, mklong(space, shifted))
bits += shifted
# do the rounding
bits += 1
round = w_m.is_odd()
w_m = rshift(space, w_m, w_1)
w_m = adlong(space, w_m, mklong(space, round))
try:
r = math.ldexp(w_m.tofloat(), bits)
# XXX I guess we do not check for overflow in ldexp as we agreed to!
if r == 2*r and r != 0.0:
raise OverflowError
except OverflowError:
r = 1e200 * 1e200 # produce inf, hopefully
if sign == '-':
r = -r
return r
| Python |
from pypy.objspace.std.objspace import *
from pypy.objspace.std.inttype import wrapint
from pypy.objspace.std.listtype import get_list_index
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std import slicetype
from pypy.interpreter import gateway, baseobjspace
from pypy.rlib.listsort import TimSort
# ListImplementations
# An empty list always is an EmptyListImplementation.
#
# RDictImplementation -- standard implementation
# StrListImplementation -- lists consisting only of strings
# ChunkedListImplementation -- when having set the withchunklist option
# SmartResizableListImplementation -- when having set the
# withsmartresizablelist option
# RangeImplementation -- constructed by range()
# SliceTrackingListImplementation -- when having set the withfastslice option
# SliceListImplementation -- slices of a SliceTrackingListImplementation
class ListImplementation(object):
def __init__(self, space):
self.space = space
# A list implementation must implement the following methods:
## def length(self):
## pass
## def getitem(self, i):
## pass
## def getitem_slice(self, start, stop):
## pass
## def get_list_w(self):
## => returns an RPython list of all wrapped items
# The following operations return the list implementation that should
# be used after the call.
# If it turns out that the list implementation cannot really perform
# the operation it can return None for the following ones:
def setitem(self, i, w_item):
return None
def insert(self, i, w_item):
return None
def delitem(self, index):
return None
def delitem_slice(self, start, stop):
return None
def append(self, w_item):
return None
def extend(self, other):
return None
# special case
def add(self, other):
return None
# Default implementations, can (but don't have to be) overridden:
def reverse(self):
l = self.length()
for i in range(l // 2):
x = self.getitem(i)
y = self.getitem(l - i - 1)
self = self.i_setitem(i, y)
self = self.i_setitem(l - i - 1, x)
return self
def getitem_slice_step(self, start, stop, step, slicelength):
res_w = [None] * slicelength
for i in range(slicelength):
res_w[i] = self.getitem(start)
start += step
return RListImplementation(self.space, res_w)
def delitem_slice_step(self, start, stop, step, slicelength):
n = self.length()
recycle = [None] * slicelength
i = start
# keep a reference to the objects to be removed,
# preventing side effects during destruction
recycle[0] = self.getitem(i)
for discard in range(1, slicelength):
j = i+1
i += step
while j < i:
self = self.i_setitem(j - discard, self.getitem(j))
j += 1
recycle[discard] = self.getitem(i)
j = i+1
while j < n:
self = self.i_setitem(j-slicelength, self.getitem(j))
j += 1
start = n - slicelength
assert start >= 0 # annotator hint
self = self.i_delitem_slice(start, n)
return self
def mul(self, times):
return make_implementation(self.space, self.get_list_w() * times)
def copy(self):
return self.getitem_slice(0, self.length())
def to_rlist(self):
list_w = self.get_list_w()
return RListImplementation(self.space, list_w)
# interface used by W_ListMultiObject:
def i_setitem(self, i, w_item):
impl = self.setitem(i, w_item)
if impl is None: # failed to implement
list_w = self.get_list_w()
assert i >= 0 and i < len(list_w)
list_w[i] = w_item
return make_implementation(self.space, list_w)
return impl
def i_insert(self, i, w_item):
impl = self.insert(i, w_item)
if impl is None: # failed to implement
list_w = self.get_list_w()
assert i >= 0 and i <= len(list_w)
list_w.insert(i, w_item)
return make_implementation(self.space, list_w)
return impl
def i_append(self, w_item):
impl = self.append(w_item)
if impl is None: # failed to implement
list_w = self.get_list_w()
list_w.append(w_item)
return make_implementation(self.space, list_w)
return impl
def i_add(self, other):
impl = self.add(other)
if impl is None:
list_w1 = self.get_list_w()
list_w2 = other.get_list_w()
return make_implementation(self.space, list_w1 + list_w2)
return impl
def i_extend(self, other):
impl = self.extend(other)
if impl is None:
list_w1 = self.get_list_w()
list_w2 = other.get_list_w()
return make_implementation(self.space, list_w1 + list_w2)
return impl
def i_delitem(self, i):
impl = self.delitem(i)
if impl is None:
list_w = self.get_list_w()
del list_w[i]
return make_implementation(self.space, list_w)
return impl
def i_delitem_slice(self, start, stop):
impl = self.delitem_slice(start, stop)
if impl is None:
list_w = self.get_list_w()
assert 0 <= start < len(list_w)
assert 0 <= stop <= len(list_w)
del list_w[start:stop]
return make_implementation(self.space, list_w)
return impl
class RListImplementation(ListImplementation):
def __init__(self, space, list_w):
ListImplementation.__init__(self, space)
self.list_w = list_w
def length(self):
return len(self.list_w)
def getitem(self, i):
return self.list_w[i]
def getitem_slice(self, start, stop):
assert start >= 0
assert stop >= 0 and stop <= len(self.list_w)
return RListImplementation(self.space, self.list_w[start:stop])
def delitem(self, i):
assert i >= 0 and i < len(self.list_w)
if len(self.list_w) == 1:
return self.space.fromcache(State).empty_impl
del self.list_w[i]
return self
def delitem_slice(self, start, stop):
assert start >= 0
assert stop >= 0 and stop <= len(self.list_w)
if len(self.list_w) == stop and start == 0:
return self.space.fromcache(State).empty_impl
del self.list_w[start:stop]
return self
def setitem(self, i, w_item):
assert i >= 0 and i < len(self.list_w)
self.list_w[i] = w_item
return self
def insert(self, i, w_item):
assert i >= 0 and i <= len(self.list_w)
self.list_w.insert(i, w_item)
return self
def add(self, other):
return RListImplementation(
self.space, self.list_w + other.get_list_w())
def append(self, w_item):
self.list_w.append(w_item)
return self
def extend(self, other):
self.list_w.extend(other.get_list_w())
return self
def reverse(self):
self.list_w.reverse()
return self
def get_list_w(self):
return self.list_w
def to_rlist(self):
return self
def __repr__(self):
return "RListImplementation(%s)" % (self.list_w, )
CHUNK_SIZE_BITS = 4
CHUNK_SIZE = 2**CHUNK_SIZE_BITS
class ChunkedListImplementation(ListImplementation):
""" A list of chunks that allow extend operations to be cheaper
because only a smaller list has to be resized.
Invariant: Every element of self.chunks is a list of wrapped objects.
Each of those lists has exactly CHUNK_SIZE elements.
"""
def __init__(self, space, list_w=None, chunks=None, length=-1):
ListImplementation.__init__(self, space)
if list_w is not None:
self.chunks = []
self._length = 0
self._grow(len(list_w))
i = 0
for w_elem in list_w:
self.setitem(i, w_elem)
i += 1
else:
self.chunks = chunks
self._length = length
def _grow(self, how_much=1):
free_slots = -self._length % CHUNK_SIZE
if free_slots < how_much:
to_allocate = how_much - free_slots
while to_allocate > 0:
self.chunks.append([None] * CHUNK_SIZE)
to_allocate -= CHUNK_SIZE
self._length += how_much
def length(self):
return self._length
def getitem(self, i):
assert i < self._length
return self.chunks[i >> CHUNK_SIZE_BITS][i & (CHUNK_SIZE - 1)]
def _get_chunks_slice(self, start, stop):
assert start >= 0 and stop >= 0
current_chunk = [None] * CHUNK_SIZE
chunks = [current_chunk]
element_index = 0
for i in range(start, stop):
if element_index == CHUNK_SIZE:
current_chunk = [None] * CHUNK_SIZE
chunks.append(current_chunk)
element_index = 0
current_chunk[element_index] = self.getitem(i)
element_index += 1
return chunks
def getitem_slice(self, start, stop):
assert start >= 0
assert stop >= 0
delta = stop - start
if start % CHUNK_SIZE == 0 and stop % CHUNK_SIZE == 0:
first_chunk = start >> CHUNK_SIZE_BITS
last_chunk = stop >> CHUNK_SIZE_BITS
chunks = [chunk[:] for chunk in self.chunks[first_chunk:last_chunk]]
return ChunkedListImplementation(self.space, chunks=chunks, length=delta)
return ChunkedListImplementation(self.space, chunks=self._get_chunks_slice(start, stop),
length=delta)
def delitem(self, i):
length = self._length
if length == 1:
return self.space.fromcache(State).empty_impl
assert i >= 0
for j in range(i + 1, length):
self.setitem(j - 1, self.getitem(j))
self._length -= 1
return self
def delitem_slice(self, start, stop):
length = self._length
if length == stop and start == 0:
return self.space.fromcache(State).empty_impl
assert start >= 0
assert stop >= 0
delta = stop - start
for j in range(start + delta, length):
self.setitem(j - delta, self.getitem(j))
first_unneeded_chunk = ((length - delta) >> CHUNK_SIZE_BITS) + 1
assert first_unneeded_chunk >= 0
del self.chunks[first_unneeded_chunk:]
self._length -= delta
return self
def setitem(self, i, w_item):
assert i >= 0
chunk = self.chunks[i >> CHUNK_SIZE_BITS]
chunk[i & (CHUNK_SIZE - 1)] = w_item
return self
def insert(self, i, w_item):
assert i >= 0
length = self._length
self._grow()
for j in range(length - 1, 0, -1):
self.setitem(j + 1, self.getitem(j))
self.setitem(i, w_item)
return self
def append(self, w_item):
self._grow()
self.setitem(self._length - 1, w_item)
return self
def extend(self, other):
other_length = other.length()
old_length = self._length
self._grow(other_length)
for idx in range(0, other_length):
self.setitem(old_length + idx, other.getitem(idx))
return self
def get_list_w(self):
return [self.getitem(idx) for idx in range(0, self._length)]
def __repr__(self):
return "ChunkedListImplementation(%s)" % (self.get_list_w(), )
class EmptyListImplementation(ListImplementation):
def make_list_with_one_item(self, w_item):
space = self.space
if space.config.objspace.std.withfastslice:
return SliceTrackingListImplementation(space, [w_item])
w_type = space.type(w_item)
if space.is_w(w_type, space.w_str):
strlist = [space.str_w(w_item)]
return StrListImplementation(space, strlist)
return RListImplementation(space, [w_item])
def length(self):
return 0
def getitem(self, i):
raise IndexError
def getitem_slice(self, start, stop):
if start == 0 and stop == 0:
return self
raise IndexError
def delitem(self, index):
raise IndexError
def delitem_slice(self, start, stop):
if start == 0 and stop == 0:
return self
raise IndexError
def setitem(self, i, w_item):
raise IndexError
def insert(self, i, w_item):
return self.make_list_with_one_item(w_item)
def add(self, other):
return other.copy()
def append(self, w_item):
return self.make_list_with_one_item(w_item)
def extend(self, other):
return other.copy()
def reverse(self):
return self
def get_list_w(self):
return []
def copy(self):
return self
def mul(self, times):
return self
def __repr__(self):
return "EmptyListImplementation()"
class StrListImplementation(ListImplementation):
def __init__(self, space, strlist):
self.strlist = strlist
ListImplementation.__init__(self, space)
def length(self):
return len(self.strlist)
def getitem(self, i):
assert 0 <= i < len(self.strlist)
return self.space.wrap(self.strlist[i])
def getitem_slice(self, start, stop):
assert 0 <= start < len(self.strlist)
assert 0 <= stop <= len(self.strlist)
return StrListImplementation(self.space, self.strlist[start:stop])
def getitem_slice_step(self, start, stop, step, slicelength):
assert 0 <= start < len(self.strlist)
# stop is -1 e.g. for [2::-1]
assert -1 <= stop <= len(self.strlist)
assert slicelength > 0
res = [""] * slicelength
for i in range(slicelength):
res[i] = self.strlist[start]
start += step
return StrListImplementation(self.space, res)
def delitem(self, i):
assert 0 <= i < len(self.strlist)
if len(self.strlist) == 1:
return self.space.fromcache(State).empty_impl
del self.strlist[i]
return self
def delitem_slice(self, start, stop):
assert 0 <= start < len(self.strlist)
assert 0 <= stop < len(self.strlist)
if len(self.strlist) == stop and start == 0:
return self.space.fromcache(State).empty_impl
del self.strlist[start:stop]
return self
def setitem(self, i, w_item):
assert 0 <= i < len(self.strlist)
if self.space.is_w(self.space.type(w_item), self.space.w_str):
self.strlist[i] = self.space.str_w(w_item)
return self
return None
def insert(self, i, w_item):
assert 0 <= i <= len(self.strlist)
if self.space.is_w(self.space.type(w_item), self.space.w_str):
self.strlist.insert(i, self.space.str_w(w_item))
return self
return None
def add(self, other):
if isinstance(other, StrListImplementation):
return StrListImplementation(
self.space, self.strlist + other.strlist)
def append(self, w_item):
if self.space.is_w(self.space.type(w_item), self.space.w_str):
self.strlist.append(self.space.str_w(w_item))
return self
return None
def extend(self, other):
if isinstance(other, StrListImplementation):
self.strlist.extend(other.strlist)
return self
def reverse(self):
self.strlist.reverse()
return self
def get_list_w(self):
return [self.space.wrap(i) for i in self.strlist]
def __repr__(self):
return "StrListImplementation(%s)" % (self.strlist, )
class RangeImplementation(ListImplementation):
def __init__(self, space, start, step, length):
ListImplementation.__init__(self, space)
self.start = start
self.step = step
self.len = length
def length(self):
return self.len
def getitem_w(self, i):
assert 0 <= i < self.len
return self.start + i * self.step
def getitem(self, i):
return wrapint(self.space, self.getitem_w(i))
def getitem_slice(self, start, stop):
rangestart = self.getitem_w(start)
return RangeImplementation(
self.space, rangestart, self.step, stop - start)
def getitem_slice_step(self, start, stop, step, slicelength):
rangestart = self.getitem_w(start)
rangestep = self.step * step
return RangeImplementation(
self.space, rangestart, rangestep, slicelength)
def delitem(self, index):
if index == 0:
self.start = self.getitem_w(1)
self.len -= 1
return self
if index == self.len - 1:
self.len -= 1
return self
return None
def delitem_slice(self, start, stop):
if start == 0:
if stop == self.len:
return self.space.fromcache(State).empty_impl
self.start = self.getitem_w(stop)
self.len -= stop
return self
if stop == self.len:
self.len = start
return self
return None
def reverse(self):
self.start = self.getitem_w(self.len - 1)
self.step = -self.step
return self
def get_list_w(self):
start = self.start
step = self.step
length = self.len
if not length:
return []
list_w = [None] * length
i = start
n = 0
while n < length:
list_w[n] = wrapint(self.space, i)
i += step
n += 1
return list_w
def __repr__(self):
return "RangeImplementation(%s, %s, %s)" % (
self.start, self.len, self.step)
class SliceTrackingListImplementation(RListImplementation):
def __init__(self, space, list_w):
RListImplementation.__init__(self, space, list_w)
self.slices = []
def getitem_slice(self, start, stop):
assert start >= 0
assert stop >= 0 and stop <= len(self.list_w)
# just do this for slices of a certain length
if stop - start > 5:
index = len(self.slices)
sliceimpl = SliceListImplementation(
self.space, self, index, start, stop)
self.slices.append(sliceimpl)
return sliceimpl
else:
return self.getitem_true_slice(start, stop)
def getitem_true_slice(self, start, stop):
assert start >= 0
assert stop >= 0 and stop <= len(self.list_w)
return SliceTrackingListImplementation(
self.space, self.list_w[start:stop])
def getitem_slice_step(self, start, stop, step, slicelength):
res_w = [None] * slicelength
for i in range(slicelength):
res_w[i] = self.getitem(start)
start += step
return SliceTrackingListImplementation(self.space, res_w)
def delitem(self, index):
assert 0 <= index < len(self.list_w)
if len(self.list_w) == 1:
return self.space.fromcache(State).empty_impl
self.changed()
del self.list_w[index]
return self
def delitem_slice(self, start, stop):
assert start >= 0
assert stop >= 0 and stop <= len(self.list_w)
if start == 0 and len(self.list_w) == stop:
return self.space.fromcache(State).empty_impl
self.changed()
del self.list_w[start:stop]
return self
def setitem(self, i, w_item):
self.changed()
assert 0 <= i < len(self.list_w)
self.list_w[i] = w_item
return self
def insert(self, i, w_item):
assert 0 <= i <= len(self.list_w)
if i == len(self.list_w):
return self.append(w_item)
self.changed()
self.list_w.insert(i, w_item)
return self
def add(self, other):
if isinstance(other, SliceTrackingListImplementation):
return SliceTrackingListImplementation(
self.space, self.list_w + other.list_w)
return SliceTrackingListImplementation(
self.space, self.list_w + other.get_list_w())
# append and extend need not be overridden from RListImplementation.__init__
# they change the list but cannot affect slices taken so far
def reverse(self):
# could be optimised: the slices grow steps and their
# step is reversed :-)
self.changed()
self.list_w.reverse()
return self
def to_rlist(self):
return RListImplementation(self.space, self.list_w)
def changed(self):
if not self.slices:
return
self.notify_slices()
def notify_slices(self):
for slice in self.slices:
if slice is not None:
slice.detach()
self.slices = []
def unregister_slice(self, index):
self.slices[index] = None
def __repr__(self):
return "SliceTrackingListImplementation(%s, <%s slice(s)>)" % (
self.list_w, len(self.slices))
class SliceListImplementation(ListImplementation):
def __init__(self, space, listimpl, index, start, stop):
assert 0 <= start < listimpl.length()
assert 0 <= stop <= listimpl.length()
ListImplementation.__init__(self, space)
self.listimpl = listimpl
self.index = index
self.start = start
self.stop = stop
self.len = stop - start
self.detached_impl = None
def detach(self):
if self.detached_impl is None:
self.detached_impl = self.listimpl.getitem_true_slice(
self.start, self.stop)
self.listimpl = None # lose the reference
def detach_and_unregister(self):
if self.detached_impl is None:
self.listimpl.unregister_slice(self.index)
self.detach()
def length(self):
if self.detached_impl is not None:
return self.detached_impl.length()
return self.len
def getitem(self, i):
if self.detached_impl is not None:
return self.detached_impl.getitem(i)
return self.listimpl.getitem(self.start + i)
def getitem_slice(self, start, stop):
assert start >= 0
assert stop >= 0
if self.detached_impl is not None:
return self.detached_impl.getitem_slice(start, stop)
return self.listimpl.getitem_slice(
self.start + start, self.start + stop)
def delitem(self, index):
self.detach_and_unregister()
return self.detached_impl.delitem(index)
def delitem_slice(self, start, stop):
self.detach_and_unregister()
if start == 0 and self.len == stop:
return self.space.fromcache(State).empty_impl
return self.detached_impl.delitem_slice(start, stop)
def setitem(self, i, w_item):
self.detach_and_unregister()
return self.detached_impl.setitem(i, w_item)
def insert(self, i, w_item):
self.detach_and_unregister()
return self.detached_impl.insert(i, w_item)
def add(self, other):
self.detach_and_unregister()
return self.detached_impl.add(other)
def append(self, w_item):
self.detach_and_unregister()
return self.detached_impl.append(w_item)
def extend(self, other):
self.detach_and_unregister()
return self.detached_impl.extend(other)
def reverse(self):
self.detach_and_unregister()
return self.detached_impl.reverse()
def get_list_w(self):
self.detach_and_unregister()
return self.detached_impl.get_list_w()
def __repr__(self):
if self.detached_impl is not None:
return "SliceListImplementation(%s)" % (self.detached_impl, )
return "SliceListImplementation(%s, %s, %s)" % (
self.listimpl, self.start, self.stop)
def is_homogeneous(space, list_w, w_type):
for i in range(len(list_w)):
if not space.is_w(w_type, space.type(list_w[i])):
return False
return True
def make_implementation(space, list_w):
if not list_w:
return space.fromcache(State).empty_impl
if space.config.objspace.std.withsmartresizablelist:
from pypy.objspace.std.smartresizablelist import \
SmartResizableListImplementation
impl = SmartResizableListImplementation(space)
impl.extend(RListImplementation(space, list_w))
return impl
if space.config.objspace.std.withchunklist:
return ChunkedListImplementation(space, list_w)
elif space.config.objspace.std.withfastslice:
return SliceTrackingListImplementation(space, list_w)
else:
# check if it's strings only
w_type = space.type(list_w[0])
if (space.is_w(w_type, space.w_str) and
is_homogeneous(space, list_w, w_type)):
strlist = [space.str_w(w_i) for w_i in list_w]
return StrListImplementation(space, strlist)
else:
return RListImplementation(space, list_w)
def convert_list_w(space, list_w):
if not list_w:
impl = space.fromcache(State).empty_impl
else:
impl = make_implementation(space, list_w)
return W_ListMultiObject(space, impl)
class W_ListMultiObject(W_Object):
from pypy.objspace.std.listtype import list_typedef as typedef
def __init__(w_self, space, implementation=None):
if implementation is None:
implementation = space.fromcache(State).empty_impl
w_self.implementation = implementation
def __repr__(w_self):
""" representation for debugging purposes """
return "%s(%s)" % (w_self.__class__.__name__, w_self.implementation)
def unwrap(w_list, space):
items = [space.unwrap(w_item)
for w_item in w_list.implementation.get_list_w()]
return items
registerimplementation(W_ListMultiObject)
class State(object):
def __init__(self, space):
self.empty_impl = EmptyListImplementation(space)
self.empty_list = W_ListMultiObject(space, self.empty_impl)
def _adjust_index(space, index, length, indexerrormsg):
if index < 0:
index += length
if index < 0 or index >= length:
raise OperationError(space.w_IndexError,
space.wrap(indexerrormsg))
return index
def init__ListMulti(space, w_list, __args__):
EMPTY_LIST = space.fromcache(State).empty_list
w_iterable, = __args__.parse('list',
(['sequence'], None, None), # signature
[EMPTY_LIST]) # default argument
if w_iterable is not EMPTY_LIST:
list_w = space.unpackiterable(w_iterable)
if list_w:
w_list.implementation = RListImplementation(space, list_w)
return
w_list.implementation = space.fromcache(State).empty_impl
def len__ListMulti(space, w_list):
result = w_list.implementation.length()
return wrapint(space, result)
def getitem__ListMulti_ANY(space, w_list, w_index):
idx = get_list_index(space, w_index)
idx = _adjust_index(space, idx, w_list.implementation.length(),
"list index out of range")
return w_list.implementation.getitem(idx)
def getitem__ListMulti_Slice(space, w_list, w_slice):
length = w_list.implementation.length()
start, stop, step, slicelength = w_slice.indices4(space, length)
assert slicelength >= 0
if slicelength == 0:
return W_ListMultiObject(space)
if step == 1 and 0 <= start <= stop:
return W_ListMultiObject(
space,
w_list.implementation.getitem_slice(start, stop))
return W_ListMultiObject(
space,
w_list.implementation.getitem_slice_step(
start, stop, step, slicelength))
def contains__ListMulti_ANY(space, w_list, w_obj):
# needs to be safe against eq_w() mutating the w_list behind our back
i = 0
impl = w_list.implementation
while i < impl.length(): # intentionally always calling len!
if space.eq_w(impl.getitem(i), w_obj):
return space.w_True
i += 1
return space.w_False
def iter__ListMulti(space, w_list):
from pypy.objspace.std import iterobject
return iterobject.W_SeqIterObject(w_list)
def add__ListMulti_ListMulti(space, w_list1, w_list2):
impl = w_list1.implementation.i_add(w_list2.implementation)
return W_ListMultiObject(space, impl)
def inplace_add__ListMulti_ANY(space, w_list1, w_iterable2):
list_extend__ListMulti_ANY(space, w_list1, w_iterable2)
return w_list1
def inplace_add__ListMulti_ListMulti(space, w_list1, w_list2):
list_extend__ListMulti_ListMulti(space, w_list1, w_list2)
return w_list1
def mul_list_times(space, w_list, w_times):
try:
times = space.getindex_w(w_times, space.w_OverflowError)
except OperationError, e:
if e.match(space, space.w_TypeError):
raise FailedToImplement
raise
if times <= 0:
return W_ListMultiObject(space)
return W_ListMultiObject(space, w_list.implementation.mul(times))
def mul__ListMulti_ANY(space, w_list, w_times):
return mul_list_times(space, w_list, w_times)
def mul__ANY_ListMulti(space, w_times, w_list):
return mul_list_times(space, w_list, w_times)
def inplace_mul__ListMulti_ANY(space, w_list, w_times):
try:
times = space.getindex_w(w_times, space.w_OverflowError)
except OperationError, e:
if e.match(space, space.w_TypeError):
raise FailedToImplement
raise
if times <= 0:
w_list.implementation = space.fromcache(State).empty_impl
else:
# XXX could be more efficient?
w_list.implementation = w_list.implementation.mul(times)
return w_list
def eq__ListMulti_ListMulti(space, w_list1, w_list2):
# needs to be safe against eq_w() mutating the w_lists behind our back
impl1 = w_list1.implementation
impl2 = w_list2.implementation
return equal_impls(space, impl1, impl2)
def equal_impls(space, impl1, impl2):
if impl1.length() != impl2.length():
return space.w_False
i = 0
while i < impl1.length() and i < impl2.length():
if not space.eq_w(impl1.getitem(i), impl2.getitem(i)):
return space.w_False
i += 1
return space.w_True
def _min(a, b):
if a < b:
return a
return b
def lessthan_impls(space, impl1, impl2):
# needs to be safe against eq_w() mutating the w_lists behind our back
# Search for the first index where items are different
i = 0
while i < impl1.length() and i < impl2.length():
w_item1 = impl1.getitem(i)
w_item2 = impl2.getitem(i)
if not space.eq_w(w_item1, w_item2):
return space.lt(w_item1, w_item2)
i += 1
# No more items to compare -- compare sizes
return space.newbool(impl1.length() < impl2.length())
def greaterthan_impls(space, impl1, impl2):
# needs to be safe against eq_w() mutating the w_lists behind our back
# Search for the first index where items are different
i = 0
while i < impl1.length() and i < impl2.length():
w_item1 = impl1.getitem(i)
w_item2 = impl2.getitem(i)
if not space.eq_w(w_item1, w_item2):
return space.gt(w_item1, w_item2)
i += 1
# No more items to compare -- compare sizes
return space.newbool(impl1.length() > impl2.length())
def lt__ListMulti_ListMulti(space, w_list1, w_list2):
return lessthan_impls(space, w_list1.implementation,
w_list2.implementation)
def gt__ListMulti_ListMulti(space, w_list1, w_list2):
return greaterthan_impls(space, w_list1.implementation,
w_list2.implementation)
def delitem__ListMulti_ANY(space, w_list, w_idx):
idx = get_list_index(space, w_idx)
length = w_list.implementation.length()
idx = _adjust_index(space, idx, length, "list deletion index out of range")
if length == 1:
w_list.implementation = space.fromcache(State).empty_impl
else:
w_list.implementation = w_list.implementation.i_delitem(idx)
return space.w_None
def delitem__ListMulti_Slice(space, w_list, w_slice):
length = w_list.implementation.length()
start, stop, step, slicelength = w_slice.indices4(space, length)
if slicelength == 0:
return
if slicelength == length:
w_list.implementation = space.fromcache(State).empty_impl
return space.w_None
if step < 0:
start = start + step * (slicelength-1)
step = -step
# stop is invalid
if step == 1:
_del_slice(w_list, start, start+slicelength)
else:
w_list.implementation = w_list.implementation.delitem_slice_step(
start, start + slicelength, step, slicelength)
return space.w_None
def setitem__ListMulti_ANY_ANY(space, w_list, w_index, w_any):
idx = get_list_index(space, w_index)
idx = _adjust_index(space, idx, w_list.implementation.length(),
"list index out of range")
w_list.implementation = w_list.implementation.i_setitem(idx, w_any)
return space.w_None
def setitem__ListMulti_Slice_ListMulti(space, w_list, w_slice, w_list2):
impl = w_list2.implementation
return _setitem_slice_helper(space, w_list, w_slice, impl)
def setitem__ListMulti_Slice_ANY(space, w_list, w_slice, w_iterable):
l = RListImplementation(space, space.unpackiterable(w_iterable))
return _setitem_slice_helper(space, w_list, w_slice, l)
def _setitem_slice_helper(space, w_list, w_slice, impl2):
impl = w_list.implementation
oldsize = impl.length()
len2 = impl2.length()
start, stop, step, slicelength = w_slice.indices4(space, oldsize)
assert slicelength >= 0
if step == 1: # Support list resizing for non-extended slices
delta = len2 - slicelength
if delta >= 0:
newsize = oldsize + delta
impl = impl.i_extend(
RListImplementation(space, [space.w_None] * delta))
lim = start + len2
i = newsize - 1
while i >= lim:
impl = impl.i_setitem(i, impl.getitem(i-delta))
i -= 1
else:
# shrinking requires the careful memory management of _del_slice()
impl = _del_slice(w_list, start, start-delta)
elif len2 != slicelength: # No resize for extended slices
raise OperationError(space.w_ValueError, space.wrap("attempt to "
"assign sequence of size %d to extended slice of size %d" %
(len2,slicelength)))
if impl2 is impl:
if step > 0:
# Always copy starting from the right to avoid
# having to make a shallow copy in the case where
# the source and destination lists are the same list.
i = len2 - 1
start += i*step
while i >= 0:
impl = impl.i_setitem(start, impl2.getitem(i))
start -= step
i -= 1
return space.w_None
else:
# Make a shallow copy to more easily handle the reversal case
impl2 = impl2.getitem_slice(0, impl2.length())
for i in range(len2):
impl = impl.i_setitem(start, impl2.getitem(i))
start += step
w_list.implementation = impl
return space.w_None
app = gateway.applevel("""
def listrepr(currently_in_repr, l):
'The app-level part of repr().'
list_id = id(l)
if list_id in currently_in_repr:
return '[...]'
currently_in_repr[list_id] = 1
try:
return "[" + ", ".join([repr(x) for x in l]) + ']'
finally:
try:
del currently_in_repr[list_id]
except:
pass
""", filename=__file__)
listrepr = app.interphook("listrepr")
def repr__ListMulti(space, w_list):
if w_list.implementation.length() == 0:
return space.wrap('[]')
w_currently_in_repr = space.getexecutioncontext()._py_repr
return listrepr(space, w_currently_in_repr, w_list)
def list_insert__ListMulti_ANY_ANY(space, w_list, w_where, w_any):
where = space.int_w(w_where)
length = w_list.implementation.length()
if where < 0:
where += length
if where < 0:
where = 0
elif where > length:
where = length
w_list.implementation = w_list.implementation.i_insert(where, w_any)
return space.w_None
def list_append__ListMulti_ANY(space, w_list, w_any):
w_list.implementation = w_list.implementation.i_append(w_any)
return space.w_None
def list_extend__ListMulti_ListMulti(space, w_list, w_list2):
impl2 = w_list2.implementation
w_list.implementation = w_list.implementation.i_extend(impl2)
return space.w_None
def list_extend__ListMulti_ANY(space, w_list, w_any):
list_w2 = space.unpackiterable(w_any)
impl2 = RListImplementation(space, list_w2)
w_list.implementation = w_list.implementation.i_extend(impl2)
return space.w_None
def _del_slice(w_list, ilow, ihigh):
""" similar to the deletion part of list_ass_slice in CPython """
impl = w_list.implementation
n = impl.length()
if ilow < 0:
ilow = 0
elif ilow > n:
ilow = n
if ihigh < ilow:
ihigh = ilow
elif ihigh > n:
ihigh = n
# keep a reference to the objects to be removed,
# preventing side effects during destruction
recycle = impl.getitem_slice(ilow, ihigh)
newimpl = w_list.implementation = impl.i_delitem_slice(ilow, ihigh)
return newimpl
def list_pop__ListMulti_ANY(space, w_list, w_idx=-1):
impl = w_list.implementation
length = impl.length()
if length == 0:
raise OperationError(space.w_IndexError,
space.wrap("pop from empty list"))
idx = space.int_w(w_idx)
idx = _adjust_index(space, idx, length, "pop index out of range")
w_result = impl.getitem(idx)
w_list.implementation = impl.i_delitem(idx)
return w_result
def list_remove__ListMulti_ANY(space, w_list, w_any):
# needs to be safe against eq_w() mutating the w_list behind our back
i = 0
while i < w_list.implementation.length():
if space.eq_w(w_list.implementation.getitem(i), w_any):
if i < w_list.implementation.length():
w_list.implementation = w_list.implementation.i_delitem(i)
return space.w_None
i += 1
raise OperationError(space.w_ValueError,
space.wrap("list.remove(x): x not in list"))
def list_index__ListMulti_ANY_ANY_ANY(space, w_list, w_any, w_start, w_stop):
# needs to be safe against eq_w() mutating the w_list behind our back
length = w_list.implementation.length()
i = slicetype.adapt_bound(space, length, w_start)
stop = slicetype.adapt_bound(space, length, w_stop)
while i < stop and i < w_list.implementation.length():
if space.eq_w(w_list.implementation.getitem(i), w_any):
return space.wrap(i)
i += 1
raise OperationError(space.w_ValueError,
space.wrap("list.index(x): x not in list"))
def list_count__ListMulti_ANY(space, w_list, w_any):
# needs to be safe against eq_w() mutating the w_list behind our back
count = 0
i = 0
while i < w_list.implementation.length():
if space.eq_w(w_list.implementation.getitem(i), w_any):
count += 1
i += 1
return space.wrap(count)
def list_reverse__ListMulti(space, w_list):
w_list.implementation = w_list.implementation.reverse()
return space.w_None
# ____________________________________________________________
# Sorting
# Reverse a slice of a list in place, from lo up to (exclusive) hi.
# (used in sort)
class KeyContainer(baseobjspace.W_Root):
def __init__(self, w_key, w_item):
self.w_key = w_key
self.w_item = w_item
# NOTE: all the subclasses of TimSort should inherit from a common subclass,
# so make sure that only SimpleSort inherits directly from TimSort.
# This is necessary to hide the parent method TimSort.lt() from the
# annotator.
class SimpleSort(TimSort):
def lt(self, a, b):
space = self.space
return space.is_true(space.lt(a, b))
class CustomCompareSort(SimpleSort):
def lt(self, a, b):
space = self.space
w_cmp = self.w_cmp
w_result = space.call_function(w_cmp, a, b)
try:
result = space.int_w(w_result)
except OperationError, e:
if e.match(space, space.w_TypeError):
raise OperationError(space.w_TypeError,
space.wrap("comparison function must return int"))
raise
return result < 0
class CustomKeySort(SimpleSort):
def lt(self, a, b):
assert isinstance(a, KeyContainer)
assert isinstance(b, KeyContainer)
space = self.space
return space.is_true(space.lt(a.w_key, b.w_key))
class CustomKeyCompareSort(CustomCompareSort):
def lt(self, a, b):
assert isinstance(a, KeyContainer)
assert isinstance(b, KeyContainer)
return CustomCompareSort.lt(self, a.w_key, b.w_key)
def list_sort__ListMulti_ANY_ANY_ANY(space, w_list, w_cmp, w_keyfunc, w_reverse):
has_cmp = not space.is_w(w_cmp, space.w_None)
has_key = not space.is_w(w_keyfunc, space.w_None)
has_reverse = space.is_true(w_reverse)
# create and setup a TimSort instance
if has_cmp:
if has_key:
sorterclass = CustomKeyCompareSort
else:
sorterclass = CustomCompareSort
else:
if has_key:
sorterclass = CustomKeySort
else:
sorterclass = SimpleSort
impl = w_list.implementation.to_rlist()
w_list.implementation = impl
items = impl.list_w
sorter = sorterclass(items, impl.length())
sorter.space = space
sorter.w_cmp = w_cmp
try:
# The list is temporarily made empty, so that mutations performed
# by comparison functions can't affect the slice of memory we're
# sorting (allowing mutations during sorting is an IndexError or
# core-dump factory).
w_list.implementation = EmptyListImplementation(space)
# wrap each item in a KeyContainer if needed
if has_key:
for i in range(sorter.listlength):
w_item = sorter.list[i]
w_key = space.call_function(w_keyfunc, w_item)
sorter.list[i] = KeyContainer(w_key, w_item)
# Reverse sort stability achieved by initially reversing the list,
# applying a stable forward sort, then reversing the final result.
if has_reverse:
sorter.list.reverse()
# perform the sort
sorter.sort()
# reverse again
if has_reverse:
sorter.list.reverse()
finally:
# unwrap each item if needed
if has_key:
for i in range(sorter.listlength):
w_obj = sorter.list[i]
if isinstance(w_obj, KeyContainer):
sorter.list[i] = w_obj.w_item
# check if the user mucked with the list during the sort
mucked = w_list.implementation.length() > 0
# put the items back into the list
impl.list_w = sorter.list
w_list.implementation = impl
if mucked:
raise OperationError(space.w_ValueError,
space.wrap("list modified during sort"))
return space.w_None
from pypy.objspace.std import listtype
register_all(vars(), listtype)
| Python |
"""
String formatting routines.
"""
from pypy.rlib.unroll import unrolling_iterable
from pypy.rlib.rarithmetic import ovfcheck, formatd_overflow
from pypy.interpreter.error import OperationError
class BaseStringFormatter(object):
def __init__(self, space, values_w, w_valuedict):
self.space = space
self.fmtpos = 0
self.values_w = values_w
self.values_pos = 0
self.w_valuedict = w_valuedict
def forward(self):
# move current position forward
self.fmtpos += 1
def nextinputvalue(self):
# return the next value in the tuple of input arguments
try:
w_result = self.values_w[self.values_pos]
except IndexError:
space = self.space
raise OperationError(space.w_TypeError, space.wrap(
'not enough arguments for format string'))
else:
self.values_pos += 1
return w_result
def checkconsumed(self):
if self.values_pos < len(self.values_w) and self.w_valuedict is None:
space = self.space
raise OperationError(space.w_TypeError,
space.wrap('not all arguments converted '
'during string formatting'))
def std_wp_int(self, r, prefix=''):
# use self.prec to add some '0' on the left of the number
if self.prec >= 0:
sign = r[0] == '-'
padding = self.prec - (len(r)-int(sign))
if padding > 0:
if sign:
r = '-' + '0'*padding + r[1:]
else:
r = '0'*padding + r
elif self.prec == 0 and r == '0':
r = ''
self.std_wp_number(r, prefix)
def fmt_d(self, w_value):
"int formatting"
r = int_num_helper(self.space, w_value)
self.std_wp_int(r)
def fmt_x(self, w_value):
"hex formatting"
r = hex_num_helper(self.space, w_value)
if self.f_alt:
prefix = '0x'
else:
prefix = ''
self.std_wp_int(r, prefix)
def fmt_X(self, w_value):
"HEX formatting"
r = hex_num_helper(self.space, w_value)
if self.f_alt:
prefix = '0X'
else:
prefix = ''
self.std_wp_int(r.upper(), prefix)
def fmt_o(self, w_value):
"oct formatting"
r = oct_num_helper(self.space, w_value)
if self.f_alt and (r != '0' or self.prec == 0):
prefix = '0'
else:
prefix = ''
self.std_wp_int(r, prefix)
fmt_i = fmt_d
fmt_u = fmt_d
def fmt_e(self, w_value):
self.format_float(w_value, 'e')
def fmt_f(self, w_value):
self.format_float(w_value, 'f')
def fmt_g(self, w_value):
self.format_float(w_value, 'g')
def fmt_E(self, w_value):
self.format_float(w_value, 'E')
def fmt_F(self, w_value):
self.format_float(w_value, 'F')
def fmt_G(self, w_value):
self.format_float(w_value, 'G')
def format_float(self, w_value, char):
space = self.space
x = space.float_w(maybe_float(space, w_value))
if isnan(x):
r = 'nan'
elif isinf(x):
r = 'inf'
else:
prec = self.prec
if prec < 0:
prec = 6
if char in 'fF' and x/1e25 > 1e25:
char = chr(ord(char) + 1) # 'f' => 'g'
try:
r = formatd_overflow(self.f_alt, prec, char, x)
except OverflowError:
raise OperationError(space.w_OverflowError, space.wrap(
"formatted float is too long (precision too large?)"))
self.std_wp_number(r)
def make_formatter_subclass(do_unicode):
# to build two subclasses of the BaseStringFormatter class,
# each one getting its own subtle differences and RPython types.
class StringFormatter(BaseStringFormatter):
def __init__(self, space, fmt, values_w, w_valuedict):
BaseStringFormatter.__init__(self, space, values_w, w_valuedict)
self.fmt = fmt # either a string or a list of unichars
def peekchr(self):
# return the 'current' character
try:
return self.fmt[self.fmtpos]
except IndexError:
space = self.space
raise OperationError(space.w_ValueError,
space.wrap("incomplete format"))
def getmappingkey(self):
# return the mapping key in a '%(key)s' specifier
fmt = self.fmt
i = self.fmtpos + 1 # first character after '('
i0 = i
pcount = 1
while 1:
try:
c = fmt[i]
except IndexError:
space = self.space
raise OperationError(space.w_ValueError,
space.wrap("incomplete format key"))
if c == ')':
pcount -= 1
if pcount == 0:
break
elif c == '(':
pcount += 1
i += 1
self.fmtpos = i + 1 # first character after ')'
return fmt[i0:i]
def getmappingvalue(self, key):
# return the value corresponding to a key in the input dict
space = self.space
if self.w_valuedict is None:
raise OperationError(space.w_TypeError,
space.wrap("format requires a mapping"))
if do_unicode:
w_key = space.newunicode(key)
else:
w_key = space.wrap(key)
return space.getitem(self.w_valuedict, w_key)
def parse_fmt(self):
if self.peekchr() == '(':
w_value = self.getmappingvalue(self.getmappingkey())
else:
w_value = None
self.peel_flags()
self.width = self.peel_num()
if self.width < 0:
# this can happen: '%*s' % (-5, "hi")
self.f_ljust = True
self.width = -self.width
if self.peekchr() == '.':
self.forward()
self.prec = self.peel_num()
if self.prec < 0:
self.prec = 0 # this can happen: '%.*f' % (-5, 3)
else:
self.prec = -1
c = self.peekchr()
if c == 'h' or c == 'l' or c == 'L':
self.forward()
return w_value
def peel_flags(self):
self.f_ljust = False
self.f_sign = False
self.f_blank = False
self.f_alt = False
self.f_zero = False
while True:
c = self.peekchr()
if c == '-':
self.f_ljust = True
elif c == '+':
self.f_sign = True
elif c == ' ':
self.f_blank = True
elif c == '#':
self.f_alt = True
elif c == '0':
self.f_zero = True
else:
break
self.forward()
def peel_num(self):
space = self.space
c = self.peekchr()
if c == '*':
self.forward()
w_value = self.nextinputvalue()
return space.int_w(maybe_int(space, w_value))
result = 0
while True:
n = ord(c) - ord('0')
if not (0 <= n < 10):
break
try:
result = ovfcheck(ovfcheck(result * 10) + n)
except OverflowError:
raise OperationError(space.w_OverflowError,
space.wrap("precision too large"))
self.forward()
c = self.peekchr()
return result
def format(self):
result = [] # list of characters or unichars
self.result = result
while True:
# fast path: consume as many characters as possible
fmt = self.fmt
i = i0 = self.fmtpos
while i < len(fmt):
if fmt[i] == '%':
break
i += 1
else:
result += fmt[i0:]
break # end of 'fmt' string
result += fmt[i0:i]
self.fmtpos = i + 1
# interpret the next formatter
w_value = self.parse_fmt()
c = self.peekchr()
self.forward()
if c == '%':
self.std_wp('%')
continue
if w_value is None:
w_value = self.nextinputvalue()
# dispatch on the formatter
# (this turns into a switch after translation)
for c1 in FORMATTER_CHARS:
if c == c1:
# 'c1' is an annotation constant here,
# so this getattr() is ok
do_fmt = getattr(self, 'fmt_' + c1)
do_fmt(w_value)
break
else:
self.unknown_fmtchar()
self.checkconsumed()
return result
def unknown_fmtchar(self):
space = self.space
c = self.fmt[self.fmtpos - 1]
if do_unicode:
w_defaultencoding = space.call_function(
space.sys.get('getdefaultencoding'))
w_s = space.call_method(space.newunicode([c]),
"encode",
w_defaultencoding,
space.wrap('replace'))
s = space.str_w(w_s)
else:
s = c
msg = "unsupported format character '%s' (0x%x) at index %d" % (
s, ord(c), self.fmtpos)
raise OperationError(space.w_ValueError, space.wrap(msg))
def std_wp(self, r):
length = len(r)
prec = self.prec
if prec >= 0 and prec < length:
length = prec # ignore the end of the string if too long
result = self.result
padding = self.width - length
if not self.f_ljust:
result += ' ' * padding # add any padding at the left of 'r'
padding = 0
result += r[:length] # add 'r' itself
result += ' ' * padding # add any remaining padding at the right
std_wp._annspecialcase_ = 'specialize:argtype(1)'
def std_wp_number(self, r, prefix=''):
# add a '+' or ' ' sign if necessary
sign = r.startswith('-')
if not sign:
if self.f_sign:
r = '+' + r
sign = True
elif self.f_blank:
r = ' ' + r
sign = True
# do the padding requested by self.width and the flags,
# without building yet another RPython string but directly
# by pushing the pad character into self.result
result = self.result
padding = self.width - len(r) - len(prefix)
if self.f_ljust:
padnumber = '<'
elif self.f_zero:
padnumber = '0'
else:
padnumber = '>'
if padnumber == '>':
result += ' ' * padding # pad with spaces on the left
if sign:
result.append(r[0]) # the sign
result += prefix # the prefix
if padnumber == '0':
result += '0' * padding # pad with zeroes
result += r[int(sign):] # the rest of the number
if padnumber == '<': # spaces on the right
result += ' ' * padding
def fmt_s(self, w_value):
space = self.space
got_unicode = space.is_true(space.isinstance(w_value,
space.w_unicode))
if not do_unicode:
if got_unicode:
raise NeedUnicodeFormattingError
s = space.str_w(space.str(w_value))
else:
if not got_unicode:
w_value = space.call_function(space.w_unicode, w_value)
s = space.unichars_w(w_value)
self.std_wp(s)
def fmt_r(self, w_value):
self.std_wp(self.space.str_w(self.space.repr(w_value)))
def fmt_c(self, w_value):
self.prec = -1 # just because
space = self.space
if space.is_true(space.isinstance(w_value, space.w_str)):
s = space.str_w(w_value)
if len(s) != 1:
raise OperationError(space.w_TypeError,
space.wrap("%c requires int or char"))
self.std_wp(s)
elif space.is_true(space.isinstance(w_value, space.w_unicode)):
if not do_unicode:
raise NeedUnicodeFormattingError
lst = space.unichars_w(w_value)
if len(lst) != 1:
raise OperationError(space.w_TypeError,
space.wrap("%c requires int or unichar"))
self.std_wp(lst)
else:
n = space.int_w(w_value)
if do_unicode:
c = unichr(n)
# XXX no range checking, but our unichr() builtin needs
# to be fixed too
self.std_wp([c])
else:
try:
s = chr(n)
except ValueError: # chr(out-of-range)
raise OperationError(space.w_OverflowError,
space.wrap("character code not in range(256)"))
self.std_wp(s)
return StringFormatter
class NeedUnicodeFormattingError(Exception):
pass
StringFormatter = make_formatter_subclass(do_unicode=False)
UnicodeFormatter = make_formatter_subclass(do_unicode=True)
UnicodeFormatter.__name__ = 'UnicodeFormatter'
# an "unrolling" list of all the known format characters,
# collected from which fmt_X() functions are defined in the class
FORMATTER_CHARS = unrolling_iterable(
[_name[-1] for _name in dir(StringFormatter)
if len(_name) == 5 and _name.startswith('fmt_')])
def format(space, w_fmt, values_w, w_valuedict=None, do_unicode=False):
"Entry point"
if not do_unicode:
fmt = space.str_w(w_fmt)
formatter = StringFormatter(space, fmt, values_w, w_valuedict)
try:
result = formatter.format()
except NeedUnicodeFormattingError:
# fall through to the unicode case
fmt = [c for c in fmt] # string => list of unichars
else:
return space.wrap(''.join(result))
else:
fmt = space.unichars_w(w_fmt)
formatter = UnicodeFormatter(space, fmt, values_w, w_valuedict)
result = formatter.format()
return space.newunicode(result)
def mod_format(space, w_format, w_values, do_unicode=False):
if space.is_true(space.isinstance(w_values, space.w_tuple)):
values_w = space.unpackiterable(w_values)
return format(space, w_format, values_w, None, do_unicode)
else:
# we check directly for dict to avoid obscure checking
# in simplest case
if space.is_true(space.isinstance(w_values, space.w_dict)) or \
(space.lookup(w_values, '__getitem__') and
not space.is_true(space.isinstance(w_values, space.w_basestring))):
return format(space, w_format, [w_values], w_values, do_unicode)
else:
return format(space, w_format, [w_values], None, do_unicode)
# ____________________________________________________________
# Formatting helpers
def maybe_int(space, w_value):
# make sure that w_value is a wrapped integer
return space.int(w_value)
def maybe_float(space, w_value):
# make sure that w_value is a wrapped float
return space.float(w_value)
def format_num_helper_generator(fmt, digits):
def format_num_helper(space, w_value):
w_value = maybe_int(space, w_value)
try:
value = space.int_w(w_value)
return fmt % (value,)
except OperationError, operr:
if not operr.match(space, space.w_OverflowError):
raise
num = space.bigint_w(w_value)
return num.format(digits)
format_num_helper.func_name = 'base%d_num_helper' % len(digits)
return format_num_helper
int_num_helper = format_num_helper_generator('%d', '0123456789')
oct_num_helper = format_num_helper_generator('%o', '01234567')
hex_num_helper = format_num_helper_generator('%x', '0123456789abcdef')
# isinf isn't too hard...
def isinf(v):
return v != 0 and v*2.0 == v
# To get isnan, working x-platform and both on 2.3 and 2.4, is a
# horror. I think this works (for reasons I don't really want to talk
# about), and probably when implemented on top of pypy, too.
def isnan(v):
return v != v*1.0 or (v == 1.0 and v == 2.0)
| Python |
from pypy.tool.sourcetools import compile2
class FailedToImplement(Exception):
def __init__(self, w_type=None, w_value=None):
self.w_type = w_type
self.w_value = w_value
def raiseFailedToImplement():
raise FailedToImplement
class MultiMethodTable:
def __init__(self, arity, root_class, argnames_before=[], argnames_after=[]):
"""NOT_RPYTHON: cannot create new multimethods dynamically.
MultiMethod-maker dispatching on exactly 'arity' arguments.
"""
if arity < 1:
raise ValueError, "multimethods cannot dispatch on nothing"
self.arity = arity
self.root_class = root_class
self.dispatch_tree = {}
self.argnames_before = list(argnames_before)
self.argnames_after = list(argnames_after)
def register(self, function, *types, **kwds):
assert len(types) == self.arity
assert kwds.keys() == [] or kwds.keys() == ['order']
order = kwds.get('order', 0)
node = self.dispatch_tree
for type in types[:-1]:
node = node.setdefault(type, {})
lst = node.setdefault(types[-1], [])
if order >= len(lst):
lst += [None] * (order+1 - len(lst))
assert lst[order] is None, "duplicate function for %r@%d" % (
types, order)
lst[order] = function
def install(self, prefix, list_of_typeorders, baked_perform_call=True,
base_typeorder=None, installercls=None):
"NOT_RPYTHON: initialization-time only"
assert len(list_of_typeorders) == self.arity
installercls = installercls or Installer
installer = installercls(self, prefix, list_of_typeorders,
baked_perform_call=baked_perform_call,
base_typeorder=base_typeorder)
return installer.install()
def install_if_not_empty(self, prefix, list_of_typeorders,
base_typeorder=None, installercls=None):
"NOT_RPYTHON: initialization-time only"
assert len(list_of_typeorders) == self.arity
installercls = installercls or Installer
installer = installercls(self, prefix, list_of_typeorders,
base_typeorder=base_typeorder)
if installer.is_empty():
return None
else:
return installer.install()
# ____________________________________________________________
# limited dict-like interface to the dispatch table
def getfunctions(self, types):
assert len(types) == self.arity
node = self.dispatch_tree
for type in types:
node = node[type]
return [fn for fn in node if fn is not None]
def has_signature(self, types):
try:
self.getfunctions(types)
except KeyError:
return False
else:
return True
def signatures(self):
"""NOT_RPYTHON"""
result = []
def enum_keys(types_so_far, node):
for type, subnode in node.items():
next_types = types_so_far+(type,)
if isinstance(subnode, dict):
enum_keys(next_types, subnode)
else:
assert len(next_types) == self.arity
result.append(next_types)
enum_keys((), self.dispatch_tree)
return result
# ____________________________________________________________
# Installer version 1
class InstallerVersion1:
"""NOT_RPYTHON"""
instance_counter = 0
mmfunccache = {}
prefix_memo = {}
def __init__(self, multimethod, prefix, list_of_typeorders,
baked_perform_call=True, base_typeorder=None):
self.__class__.instance_counter += 1
self.multimethod = multimethod
# avoid prefix clashes, user code should supply different prefixes
# itself for nice names in tracebacks
base_prefix = prefix
n = 1
while prefix in self.prefix_memo:
n += 1
prefix = "%s%d" % (base_prefix, n)
self.prefix = prefix
self.prefix_memo[prefix] = 1
self.list_of_typeorders = list_of_typeorders
self.subtree_cache = {}
self.to_install = []
self.non_empty = self.build_tree([], multimethod.dispatch_tree)
self.baked_perform_call = baked_perform_call
if self.non_empty:
perform = [(None, prefix, 0)]
else:
perform = []
self.perform_call = self.build_function(None, prefix+'_perform_call',
None, perform)
def is_empty(self):
return not self.non_empty
def install(self):
#f = open('LOGFILE', 'a')
#print >> f, '_'*60
#import pprint
#pprint.pprint(self.list_of_typeorders, f)
for target, funcname, func, source, fallback in self.to_install:
if target is not None:
if hasattr(target, funcname) and fallback:
continue
#print >> f, target.__name__, funcname
#if source:
# print >> f, source
#else:
# print >> f, '*\n'
setattr(target, funcname, func)
#f.close()
return self.perform_call
def build_tree(self, types_so_far, dispatch_node):
key = tuple(types_so_far)
if key in self.subtree_cache:
return self.subtree_cache[key]
non_empty = False
typeorder = self.list_of_typeorders[len(types_so_far)]
for next_type in typeorder:
if self.build_single_method(typeorder, types_so_far, next_type,
dispatch_node):
non_empty = True
self.subtree_cache[key] = non_empty
return non_empty
def build_single_method(self, typeorder, types_so_far, next_type,
dispatch_node):
funcname = '__'.join([self.prefix] + [t.__name__ for t in types_so_far])
order = typeorder[next_type]
#order = [(next_type, None)] + order
things_to_call = []
for type, conversion in order:
if type not in dispatch_node:
# there is no possible completion of types_so_far+[type]
# that could lead to a registered function.
continue
match = dispatch_node[type]
if isinstance(match, dict):
if self.build_tree(types_so_far+[type], match):
call = funcname + '__' + type.__name__
call_selfarg_index = len(types_so_far) + 1
things_to_call.append((conversion, call,
call_selfarg_index))
else:
for func in match: # list of functions
if func is not None:
things_to_call.append((conversion, func, None))
if things_to_call:
funcname = intern(funcname)
self.build_function(next_type, funcname, len(types_so_far),
things_to_call)
return True
else:
return False
def build_function(self, target, funcname, func_selfarg_index,
things_to_call):
# support for inventing names for the entries in things_to_call
# which are real function objects instead of strings
miniglobals = {'FailedToImplement': FailedToImplement}
def invent_name(obj):
if isinstance(obj, str):
return obj
name = obj.__name__
n = 1
while name in miniglobals:
n += 1
name = '%s%d' % (obj.__name__, n)
miniglobals[name] = obj
return name
funcargs = ['arg%d' % i for i in range(self.multimethod.arity)]
bodylines = []
for conversion, call, call_selfarg_index in things_to_call:
callargs = funcargs[:]
if conversion is not None:
to_convert = func_selfarg_index
convert_callargs = (self.multimethod.argnames_before +
[callargs[to_convert]])
callargs[to_convert] = '%s(%s)' % (
invent_name(conversion), ', '.join(convert_callargs))
callname = invent_name(call)
if call_selfarg_index is not None:
# fallback on root_class
self.build_function(self.multimethod.root_class,
callname, call_selfarg_index, [])
callname = '%s.%s' % (callargs.pop(call_selfarg_index), callname)
callargs = (self.multimethod.argnames_before +
callargs + self.multimethod.argnames_after)
bodylines.append('return %s(%s)' % (callname, ', '.join(callargs)))
fallback = False
if not bodylines:
miniglobals['raiseFailedToImplement'] = raiseFailedToImplement
bodylines = ['return raiseFailedToImplement()']
fallback = True
# protect all lines apart from the last one by a try:except:
for i in range(len(bodylines)-2, -1, -1):
bodylines[i:i+1] = ['try:',
' ' + bodylines[i],
'except FailedToImplement:',
' pass']
if func_selfarg_index is not None:
selfargs = [funcargs.pop(func_selfarg_index)]
else:
selfargs = []
funcargs = (selfargs + self.multimethod.argnames_before +
funcargs + self.multimethod.argnames_after)
if target is None and not self.baked_perform_call:
return funcargs, bodylines[0][len('return '):], miniglobals, fallback
# indent mode
bodylines = [' ' + line for line in bodylines]
bodylines.insert(0, 'def %s(%s):' % (funcname, ', '.join(funcargs)))
bodylines.append('')
source = '\n'.join(bodylines)
# XXX find a better place (or way) to avoid duplicate functions
l = miniglobals.items()
l.sort()
l = tuple(l)
key = (source, l)
try:
func = self.mmfunccache[key]
except KeyError:
exec compile2(source) in miniglobals
func = miniglobals[funcname]
self.mmfunccache[key] = func
#else:
# print "avoided duplicate function", func
self.to_install.append((target, funcname, func, source, fallback))
return func
# ____________________________________________________________
# Installer version 2
class MMDispatcher(object):
"""NOT_RPYTHON
Explicit dispatcher class. This is not used in normal execution, which
uses the complex Installer below to install single-dispatch methods to
achieve the same result. The MMDispatcher is only used by
rpython.lltypesystem.rmultimethod. It is also nice for documentation.
"""
_revcache = None
def __init__(self, multimethod, list_of_typeorders):
self.multimethod = multimethod
self.list_of_typeorders = list_of_typeorders
def __call__(self, *args):
# for testing only: this is slow
i = len(self.multimethod.argnames_before)
j = i + self.multimethod.arity
k = j + len(self.multimethod.argnames_after)
assert len(args) == k
prefixargs = args[:i]
dispatchargs = args[i:j]
suffixargs = args[j:]
return self.dispatch([x.__class__ for x in dispatchargs],
prefixargs,
dispatchargs,
suffixargs)
def dispatch(self, argtypes, prefixargs, args, suffixargs):
# for testing only: this is slow
def expr(v):
if isinstance(v, Call):
return v.function(*[expr(w) for w in v.arguments])
else:
return v
e = None
for v in self.expressions(argtypes, prefixargs, args, suffixargs):
try:
return expr(v)
except FailedToImplement, e:
pass
else:
raise e or FailedToImplement()
def expressions(self, argtypes, prefixargs, args, suffixargs):
"""Lists the possible expressions that call the appropriate
function for the given argument types. Each expression is a Call
object. The intent is that at run-time the first Call that doesn't
cause FailedToImplement to be raised is the good one.
"""
prefixargs = tuple(prefixargs)
suffixargs = tuple(suffixargs)
def walktree(node, args_so_far):
if isinstance(node, list):
for func in node:
if func is not None:
result.append(Call(func, prefixargs +
args_so_far +
suffixargs))
else:
index = len(args_so_far)
typeorder = self.list_of_typeorders[index]
next_type = argtypes[index]
for target_type, converter in typeorder[next_type]:
if target_type not in node:
continue
next_arg = args[index]
if converter:
next_arg = Call(converter, prefixargs + (next_arg,))
walktree(node[target_type], args_so_far + (next_arg,))
result = []
walktree(self.multimethod.dispatch_tree, ())
return result
def anychance(self, typesprefix):
# is there any chance that a list of types starting with typesprefix
# could lead to a successful dispatch?
# (START-UP TIME OPTIMIZATION ONLY)
if self._revcache is None:
def build_tree(types_so_far, dispatch_node):
non_empty = False
typeorder = self.list_of_typeorders[len(types_so_far)]
for next_type in typeorder:
if build_single_method(typeorder, types_so_far, next_type,
dispatch_node):
non_empty = True
if non_empty:
self._revcache[types_so_far] = True
return non_empty
def build_single_method(typeorder, types_so_far, next_type,
dispatch_node):
order = typeorder[next_type]
things_to_call = False
for type, conversion in order:
if type not in dispatch_node:
# there is no possible completion of
# types_so_far+[type] that could lead to a
# registered function.
continue
match = dispatch_node[type]
if isinstance(match, dict):
if build_tree(types_so_far+(next_type,), match):
things_to_call = True
elif match:
things_to_call = True
return things_to_call
self._revcache = {}
build_tree((), self.multimethod.dispatch_tree)
return tuple(typesprefix) in self._revcache
class Call(object):
""" Represents a call expression.
The arguments may themselves be Call objects.
"""
def __init__(self, function, arguments):
self.function = function
self.arguments = arguments
class CompressedArray(object):
def __init__(self, null_value):
self.null_value = null_value
self.items = [null_value]
def ensure_length(self, newlen):
if newlen > len(self.items):
self.items.extend([self.null_value] * (newlen - len(self.items)))
def insert_subarray(self, array):
# insert the given array of numbers into the indexlist,
# allowing null values to become non-null
if array.count(self.null_value) == len(array):
return 0
test = 1
while True:
self.ensure_length(test+len(array))
for i in range(len(array)):
if not (array[i] == self.items[test+i] or
array[i] == self.null_value or
self.items[test+i] == self.null_value):
break
else:
# success
for i in range(len(array)):
if array[i] != self.null_value:
self.items[test+i] = array[i]
return test
test += 1
def _freeze_(self):
return True
class MRDTable(object):
# Multi-Method Dispatch Using Multiple Row Displacement,
# Candy Pang, Wade Holst, Yuri Leontiev, and Duane Szafron
# University of Alberta, Edmonton AB T6G 2H1 Canada
# can be found on http://web.cs.ualberta.ca/~yuri/publ.htm
Counter = 0
def __init__(self, list_of_types):
self.id = MRDTable.Counter
MRDTable.Counter += 1
self.list_of_types = list_of_types
self.typenum = dict(zip(list_of_types, range(len(list_of_types))))
self.attrname = '__mrd%d_typenum' % self.id
for t1, num in self.typenum.items():
setattr(t1, self.attrname, num)
self.indexarray = CompressedArray(0)
self.strict_subclasses = {}
for cls1 in list_of_types:
lst = []
for cls2 in list_of_types:
if cls1 is not cls2 and issubclass(cls2, cls1):
lst.append(cls2)
self.strict_subclasses[cls1] = lst
def normalize_length(self, next_array):
# make sure that the indexarray is not smaller than any funcarray
self.indexarray.ensure_length(len(next_array.items))
def invent_name(miniglobals, obj):
if isinstance(obj, str):
return obj
name = obj.__name__
n = 1
while name in miniglobals:
n += 1
name = '%s%d' % (obj.__name__, n)
miniglobals[name] = obj
return name
class FuncEntry(object):
def __init__(self, bodylines, miniglobals, fallback):
self.body = '\n '.join(bodylines)
self.miniglobals = miniglobals
self.fallback = fallback
self.possiblenames = []
self.typetree = {}
self._function = None
def key(self):
lst = self.miniglobals.items()
lst.sort()
return self.body, tuple(lst)
def get_function_name(self):
# pick a name consistently based on self.possiblenames
length = min([len(parts) for parts in self.possiblenames])
result = []
for i in range(length):
choices = {}
for parts in self.possiblenames:
choices[parts[i]] = True
parts = choices.keys()
res = str(len(parts))
for part in parts:
if type(part) is str: # there is a string at this pos
if '0_fail' in choices:
res = '0_fail'
elif len(parts) == 1:
res = part
break
else:
# only types at this location, try to find a common base
basecls = parts[0]
for cls in parts[1:]:
if issubclass(basecls, cls):
basecls = cls
for cls in parts[1:]:
if not issubclass(cls, basecls):
break # no common base
else:
res = basecls.__name__
result.append(res)
return '_'.join(result)
def make_function(self, fnargs, nbargs_before, mrdtable):
if self._function is not None:
return self._function
name = self.get_function_name()
self.compress_typechecks(mrdtable)
checklines = self.generate_typechecks(fnargs[nbargs_before:])
if not checklines:
body = self.body
else:
checklines.append(self.body)
body = '\n '.join(checklines)
source = 'def %s(%s):\n %s\n' % (name, ', '.join(fnargs), body)
if 0: # for debugging the generated mm sources
f = open('/tmp/mm-source/%s' % name, 'a')
for possiblename in self.possiblenames:
print >> f, '#',
for part in possiblename:
print >> f, getattr(part, '__name__', part),
print >> f
print >> f
print >> f, source
f.close()
exec compile2(source) in self.miniglobals
self._function = self.miniglobals[name]
return self._function
def register_valid_types(self, types):
node = self.typetree
for t1 in types[:-1]:
if node is True:
return
node = node.setdefault(t1, {})
if node is True:
return
node[types[-1]] = True
def no_typecheck(self):
self.typetree = True
def compress_typechecks(self, mrdtable):
def full(node):
if node is True:
return 1
fulls = 0
for key, subnode in node.items():
if full(subnode):
node[key] = True
fulls += 1
if fulls == types_total:
return 1
# a word about subclasses: we are using isinstance() to do
# the checks in generate_typechecks(), which is a
# compromize. In theory we should check the type ids
# instead. But using isinstance() is better because the
# annotator can deduce information from that. It is still
# correct to use isinstance() instead of type ids in
# "reasonable" cases, though -- where "reasonable" means
# that classes always have a delegate to their superclasses,
# e.g. W_IntObject delegates to W_Root. If this is true
# then both kind of checks are good enough to spot
# mismatches caused by the compression table.
# Based on this reasoning, we can compress the typechecks a
# bit more - if we accept W_Root, for example, then we
# don't have to specifically accept W_IntObject too.
for cls, subnode in node.items():
for cls2 in mrdtable.strict_subclasses[cls]:
if cls2 in node and node[cls2] == subnode:
del node[cls2]
return 0
types_total = len(mrdtable.list_of_types)
if full(self.typetree):
self.typetree = True
def generate_typechecks(self, args):
def generate(node, level=0):
indent = ' '*level
if node is True:
result.append('%s_failedtoimplement = False' % (indent,))
return
if not node:
result.append('%s_failedtoimplement = True' % (indent,))
return
keyword = 'if'
for key, subnode in node.items():
typename = invent_name(self.miniglobals, key)
result.append('%s%s isinstance(%s, %s):' % (indent, keyword,
args[level],
typename))
generate(subnode, level+1)
keyword = 'elif'
result.append('%selse:' % (indent,))
result.append('%s _failedtoimplement = True' % (indent,))
result = []
if self.typetree is not True:
generate(self.typetree)
result.append('if _failedtoimplement:')
result.append(' raise FailedToImplement')
return result
class InstallerVersion2(object):
"""NOT_RPYTHON"""
instance_counter = 0
mrdtables = {}
def __init__(self, multimethod, prefix, list_of_typeorders,
baked_perform_call=True, base_typeorder=None):
#print 'InstallerVersion2:', prefix
self.__class__.instance_counter += 1
self.multimethod = multimethod
self.prefix = prefix
self.list_of_typeorders = list_of_typeorders
self.baked_perform_call = baked_perform_call
self.mmfunccache = {}
args = ['arg%d' % i for i in range(multimethod.arity)]
self.fnargs = (multimethod.argnames_before + args +
multimethod.argnames_after)
# compute the complete table
base_typeorder = base_typeorder or list_of_typeorders[0]
for typeorder in list_of_typeorders:
for t1 in typeorder:
assert t1 in base_typeorder
lst = list(base_typeorder)
lst.sort()
key = tuple(lst)
try:
self.mrdtable = self.mrdtables[key]
except KeyError:
self.mrdtable = self.mrdtables[key] = MRDTable(key)
dispatcher = MMDispatcher(multimethod, list_of_typeorders)
self.table = {}
def buildtable(prefixtypes):
if len(prefixtypes) == multimethod.arity:
calllist = dispatcher.expressions(prefixtypes,
multimethod.argnames_before,
args,
multimethod.argnames_after)
if calllist:
self.table[prefixtypes] = calllist
elif dispatcher.anychance(prefixtypes):
typeorder = list_of_typeorders[len(prefixtypes)]
for t1 in typeorder:
buildtable(prefixtypes + (t1,))
buildtable(())
self.dispatcher = dispatcher
def is_empty(self):
return len(self.table) == 0
def install(self):
nskip = len(self.multimethod.argnames_before)
null_entry = self.build_funcentry([self.prefix, '0_fail'], [])
null_entry.no_typecheck()
if self.is_empty():
return self.answer(null_entry)
entryarray = CompressedArray(null_entry)
indexarray = self.mrdtable.indexarray
lst = self.mrdtable.list_of_types
indexline = []
def compress(typesprefix, typesnum):
if len(typesprefix) == self.multimethod.arity:
calllist = self.table.get(typesprefix, [])
funcname = [self.prefix]
funcname.extend(typesprefix)
entry = self.build_funcentry(funcname, calllist)
entry.register_valid_types(typesprefix)
return entry
elif self.dispatcher.anychance(typesprefix):
flatline = []
for num1, t1 in enumerate(lst):
item = compress(typesprefix + (t1,), typesnum + (num1,))
flatline.append(item)
if len(typesprefix) == self.multimethod.arity - 1:
array = entryarray
else:
array = indexarray
return array.insert_subarray(flatline)
else:
return 0
master_index = compress((), ())
null_func = null_entry.make_function(self.fnargs, nskip, self.mrdtable)
funcarray = CompressedArray(null_func)
# round up the length to a power of 2
N = 1
while N < len(entryarray.items):
N *= 2
funcarray.ensure_length(N)
for i, entry in enumerate(entryarray.items):
func = entry.make_function(self.fnargs, nskip, self.mrdtable)
funcarray.items[i] = func
self.mrdtable.normalize_length(funcarray)
#print master_index
#print indexarray.items
#print funcarray.items
attrname = self.mrdtable.attrname
exprfn = "%d" % master_index
for n in range(self.multimethod.arity-1):
exprfn = "hint(indexarray.items, deepfreeze=True)[%s + arg%d.%s]" % (exprfn, n, attrname)
n = self.multimethod.arity-1
exprfn = "hint(funcarray.items, deepfreeze=True)[(%s + arg%d.%s) & mmmask]" % (exprfn, n,
attrname)
expr = Call(exprfn, self.fnargs)
entry = self.build_funcentry([self.prefix, '0_perform_call'],
[expr],
indexarray = indexarray,
funcarray = funcarray,
mmmask = N-1)
entry.no_typecheck()
return self.answer(entry)
def answer(self, entry):
if self.baked_perform_call:
nskip = len(self.multimethod.argnames_before)
return entry.make_function(self.fnargs, nskip, self.mrdtable)
else:
assert entry.body.startswith('return ')
expr = entry.body[len('return '):]
return self.fnargs, expr, entry.miniglobals, entry.fallback
def build_funcentry(self, funcnameparts, calllist, **extranames):
def expr(v):
if isinstance(v, Call):
return '%s(%s)' % (invent_name(miniglobals, v.function),
', '.join([expr(w) for w in v.arguments]))
else:
return v
fallback = len(calllist) == 0
if fallback:
miniglobals = {'raiseFailedToImplement': raiseFailedToImplement}
bodylines = ['return raiseFailedToImplement()']
else:
miniglobals = {'FailedToImplement': FailedToImplement}
miniglobals.update(extranames)
bodylines = []
for v in calllist[:-1]:
bodylines.append('try:')
bodylines.append(' return %s' % expr(v))
bodylines.append('except FailedToImplement:')
bodylines.append(' pass')
bodylines.append('return %s' % expr(calllist[-1]))
from pypy.rlib.jit import hint
miniglobals['hint'] = hint
entry = FuncEntry(bodylines, miniglobals, fallback)
key = entry.key()
try:
entry = self.mmfunccache[key]
except KeyError:
self.mmfunccache[key] = entry
entry.possiblenames.append(funcnameparts)
return entry
# ____________________________________________________________
# Selection of the version to use
Installer = InstallerVersion1 # modified by translate.py targetpypystandalone
| Python |
from pypy.objspace.std.stdtypedef import *
# ____________________________________________________________
basestring_typedef = StdTypeDef("basestring",
__doc__ = '''Type basestring cannot be instantiated; it is the base for str and unicode.'''
)
| Python |
from pypy.objspace.std.stdtypedef import *
from pypy.objspace.std.basestringtype import basestring_typedef
from sys import maxint
def wrapstr(space, s):
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.ropeobject import rope, W_RopeObject
if space.config.objspace.std.sharesmallstr:
if space.config.objspace.std.withprebuiltchar:
# share characters and empty string
if len(s) <= 1:
if len(s) == 0:
if space.config.objspace.std.withrope:
return W_RopeObject.EMPTY
return W_StringObject.EMPTY
else:
s = s[0] # annotator hint: a single char
return wrapchar(space, s)
else:
# only share the empty string
if len(s) == 0:
if space.config.objspace.std.withrope:
return W_RopeObject.EMPTY
return W_StringObject.EMPTY
if space.config.objspace.std.withrope:
return W_RopeObject(rope.LiteralStringNode(s))
return W_StringObject(s)
def wrapchar(space, c):
from pypy.objspace.std.stringobject import W_StringObject
from pypy.objspace.std.ropeobject import rope, W_RopeObject
if space.config.objspace.std.withprebuiltchar:
if space.config.objspace.std.withrope:
return W_RopeObject.PREBUILT[ord(c)]
return W_StringObject.PREBUILT[ord(c)]
else:
if space.config.objspace.std.withrope:
return W_RopeObject(rope.LiteralStringNode(c))
return W_StringObject(c)
def sliced(space, s, start, stop):
assert start >= 0
assert stop >= 0
assert not space.config.objspace.std.withrope
if space.config.objspace.std.withstrslice:
from pypy.objspace.std.strsliceobject import W_StringSliceObject
# XXX heuristic, should be improved!
if (stop - start) > len(s) * 0.20 + 40:
return W_StringSliceObject(s, start, stop)
return wrapstr(space, s[start:stop])
def joined(space, strlist):
assert not space.config.objspace.std.withrope
if space.config.objspace.std.withstrjoin:
from pypy.objspace.std.strjoinobject import W_StringJoinObject
return W_StringJoinObject(strlist)
else:
return wrapstr(space, "".join(strlist))
str_join = SMM('join', 2,
doc='S.join(sequence) -> string\n\nReturn a string which is'
' the concatenation of the strings in the\nsequence. '
' The separator between elements is S.')
str_split = SMM('split', 3, defaults=(None,-1),
doc='S.split([sep [,maxsplit]]) -> list of strings\n\nReturn'
' a list of the words in the string S, using sep as'
' the\ndelimiter string. If maxsplit is given, at most'
' maxsplit\nsplits are done. If sep is not specified or'
' is None, any\nwhitespace string is a separator.')
str_rsplit = SMM('rsplit', 3, defaults=(None,-1),
doc='S.rsplit([sep [,maxsplit]]) -> list of'
' strings\n\nReturn a list of the words in the string S,'
' using sep as the\ndelimiter string, starting at the'
' end of the string and working\nto the front. If'
' maxsplit is given, at most maxsplit splits are\ndone.'
' If sep is not specified or is None, any whitespace'
' string\nis a separator.')
str_isdigit = SMM('isdigit', 1,
doc='S.isdigit() -> bool\n\nReturn True if all characters'
' in S are digits\nand there is at least one'
' character in S, False otherwise.')
str_isalpha = SMM('isalpha', 1,
doc='S.isalpha() -> bool\n\nReturn True if all characters'
' in S are alphabetic\nand there is at least one'
' character in S, False otherwise.')
str_isspace = SMM('isspace', 1,
doc='S.isspace() -> bool\n\nReturn True if all characters'
' in S are whitespace\nand there is at least one'
' character in S, False otherwise.')
str_isupper = SMM('isupper', 1,
doc='S.isupper() -> bool\n\nReturn True if all cased'
' characters in S are uppercase and there is\nat'
' least one cased character in S, False otherwise.')
str_islower = SMM('islower', 1,
doc='S.islower() -> bool\n\nReturn True if all cased'
' characters in S are lowercase and there is\nat'
' least one cased character in S, False otherwise.')
str_istitle = SMM('istitle', 1,
doc='S.istitle() -> bool\n\nReturn True if S is a'
' titlecased string and there is at least'
' one\ncharacter in S, i.e. uppercase characters may'
' only follow uncased\ncharacters and lowercase'
' characters only cased ones. Return'
' False\notherwise.')
str_isalnum = SMM('isalnum', 1,
doc='S.isalnum() -> bool\n\nReturn True if all characters'
' in S are alphanumeric\nand there is at least one'
' character in S, False otherwise.')
str_ljust = SMM('ljust', 3, defaults=(' ',),
doc='S.ljust(width[, fillchar]) -> string\n\nReturn S'
' left justified in a string of length width. Padding'
' is\ndone using the specified fill character'
' (default is a space).')
str_rjust = SMM('rjust', 3, defaults=(' ',),
doc='S.rjust(width[, fillchar]) -> string\n\nReturn S'
' right justified in a string of length width.'
' Padding is\ndone using the specified fill character'
' (default is a space)')
str_upper = SMM('upper', 1,
doc='S.upper() -> string\n\nReturn a copy of the string S'
' converted to uppercase.')
str_lower = SMM('lower', 1,
doc='S.lower() -> string\n\nReturn a copy of the string S'
' converted to lowercase.')
str_swapcase = SMM('swapcase', 1,
doc='S.swapcase() -> string\n\nReturn a copy of the'
' string S with uppercase characters\nconverted to'
' lowercase and vice versa.')
str_capitalize = SMM('capitalize', 1,
doc='S.capitalize() -> string\n\nReturn a copy of the'
' string S with only its first'
' character\ncapitalized.')
str_title = SMM('title', 1,
doc='S.title() -> string\n\nReturn a titlecased version'
' of S, i.e. words start with uppercase\ncharacters,'
' all remaining cased characters have lowercase.')
str_find = SMM('find', 4, defaults=(0, maxint),
doc='S.find(sub [,start [,end]]) -> int\n\nReturn the'
' lowest index in S where substring sub is'
' found,\nsuch that sub is contained within'
' s[start,end]. Optional\narguments start and end'
' are interpreted as in slice notation.\n\nReturn -1'
' on failure.')
str_rfind = SMM('rfind', 4, defaults=(0, maxint),
doc='S.rfind(sub [,start [,end]]) -> int\n\nReturn the'
' highest index in S where substring sub is'
' found,\nsuch that sub is contained within'
' s[start,end]. Optional\narguments start and end'
' are interpreted as in slice notation.\n\nReturn -1'
' on failure.')
str_partition = SMM('partition', 2,
doc='S.partition(sep) -> (head, sep, tail)\n\nSearches'
' for the separator sep in S, and returns the part before'
' it,\nthe separator itself, and the part after it. If'
' the separator is not\nfound, returns S and two empty'
' strings.')
str_rpartition = SMM('rpartition', 2,
doc='S.rpartition(sep) -> (tail, sep, head)\n\nSearches'
' for the separator sep in S, starting at the end of S,'
' and returns\nthe part before it, the separator itself,'
' and the part after it. If the\nseparator is not found,'
' returns two empty strings and S.')
str_index = SMM('index', 4, defaults=(0, maxint),
doc='S.index(sub [,start [,end]]) -> int\n\nLike S.find()'
' but raise ValueError when the substring is not'
' found.')
str_rindex = SMM('rindex', 4, defaults=(0, maxint),
doc='S.rindex(sub [,start [,end]]) -> int\n\nLike'
' S.rfind() but raise ValueError when the substring'
' is not found.')
str_replace = SMM('replace', 4, defaults=(-1,),
doc='S.replace (old, new[, count]) -> string\n\nReturn a'
' copy of string S with all occurrences of'
' substring\nold replaced by new. If the optional'
' argument count is\ngiven, only the first count'
' occurrences are replaced.')
str_zfill = SMM('zfill', 2,
doc='S.zfill(width) -> string\n\nPad a numeric string S'
' with zeros on the left, to fill a field\nof the'
' specified width. The string S is never truncated.')
str_strip = SMM('strip', 2, defaults=(None,),
doc='S.strip([chars]) -> string or unicode\n\nReturn a'
' copy of the string S with leading and'
' trailing\nwhitespace removed.\nIf chars is given'
' and not None, remove characters in chars'
' instead.\nIf chars is unicode, S will be converted'
' to unicode before stripping')
str_rstrip = SMM('rstrip', 2, defaults=(None,),
doc='S.rstrip([chars]) -> string or unicode\n\nReturn a'
' copy of the string S with trailing whitespace'
' removed.\nIf chars is given and not None, remove'
' characters in chars instead.\nIf chars is unicode,'
' S will be converted to unicode before stripping')
str_lstrip = SMM('lstrip', 2, defaults=(None,),
doc='S.lstrip([chars]) -> string or unicode\n\nReturn a'
' copy of the string S with leading whitespace'
' removed.\nIf chars is given and not None, remove'
' characters in chars instead.\nIf chars is unicode,'
' S will be converted to unicode before stripping')
str_center = SMM('center', 3, defaults=(' ',),
doc='S.center(width[, fillchar]) -> string\n\nReturn S'
' centered in a string of length width. Padding'
' is\ndone using the specified fill character'
' (default is a space)')
str_count = SMM('count', 4, defaults=(0, maxint),
doc='S.count(sub[, start[, end]]) -> int\n\nReturn the'
' number of occurrences of substring sub in'
' string\nS[start:end]. Optional arguments start and'
' end are\ninterpreted as in slice notation.')
str_endswith = SMM('endswith', 4, defaults=(0, maxint),
doc='S.endswith(suffix[, start[, end]]) -> bool\n\nReturn'
' True if S ends with the specified suffix, False'
' otherwise.\nWith optional start, test S beginning'
' at that position.\nWith optional end, stop'
' comparing S at that position.')
str_expandtabs = SMM('expandtabs', 2, defaults=(8,),
doc='S.expandtabs([tabsize]) -> string\n\nReturn a copy'
' of S where all tab characters are expanded using'
' spaces.\nIf tabsize is not given, a tab size of 8'
' characters is assumed.')
str_splitlines = SMM('splitlines', 2, defaults=(0,),
doc='S.splitlines([keepends]) -> list of'
' strings\n\nReturn a list of the lines in S,'
' breaking at line boundaries.\nLine breaks are not'
' included in the resulting list unless keepends\nis'
' given and true.')
str_startswith = SMM('startswith', 4, defaults=(0, maxint),
doc='S.startswith(prefix[, start[, end]]) ->'
' bool\n\nReturn True if S starts with the specified'
' prefix, False otherwise.\nWith optional start, test'
' S beginning at that position.\nWith optional end,'
' stop comparing S at that position.')
str_translate = SMM('translate', 3, defaults=('',), #unicode mimic not supported now
doc='S.translate(table [,deletechars]) -> string\n\n'
'Return a copy of the string S, where all characters'
' occurring\nin the optional argument deletechars are'
' removed, and the\nremaining characters have been'
' mapped through the given\ntranslation table, which'
' must be a string of length 256.')
str_decode = SMM('decode', 3, defaults=(None, None),
doc='S.decode([encoding[,errors]]) -> object\n\nDecodes S'
' using the codec registered for encoding. encoding'
' defaults\nto the default encoding. errors may be'
' given to set a different error\nhandling scheme.'
" Default is 'strict' meaning that encoding errors"
' raise\na UnicodeDecodeError. Other possible values'
" are 'ignore' and 'replace'\nas well as any other"
' name registerd with codecs.register_error that'
' is\nable to handle UnicodeDecodeErrors.')
str_encode = SMM('encode', 3, defaults=(None, None),
doc='S.encode([encoding[,errors]]) -> object\n\nEncodes S'
' using the codec registered for encoding. encoding'
' defaults\nto the default encoding. errors may be'
' given to set a different error\nhandling scheme.'
" Default is 'strict' meaning that encoding errors"
' raise\na UnicodeEncodeError. Other possible values'
" are 'ignore', 'replace' and\n'xmlcharrefreplace' as"
' well as any other name registered'
' with\ncodecs.register_error that is able to handle'
' UnicodeEncodeErrors.')
# ____________________________________________________________
def descr__new__(space, w_stringtype, w_object=''):
# NB. the default value of w_object is really a *wrapped* empty string:
# there is gateway magic at work
from pypy.objspace.std.stringobject import W_StringObject
w_obj = space.str(w_object)
if space.is_w(w_stringtype, space.w_str):
return w_obj # XXX might be reworked when space.str() typechecks
value = space.str_w(w_obj)
if space.config.objspace.std.withrope:
from pypy.objspace.std.ropeobject import rope, W_RopeObject
w_obj = space.allocate_instance(W_RopeObject, w_stringtype)
W_RopeObject.__init__(w_obj, rope.LiteralStringNode(value))
return w_obj
else:
w_obj = space.allocate_instance(W_StringObject, w_stringtype)
W_StringObject.__init__(w_obj, value)
return w_obj
# ____________________________________________________________
str_typedef = StdTypeDef("str", basestring_typedef,
__new__ = newmethod(descr__new__),
__doc__ = '''str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.'''
)
str_typedef.custom_hash = True
str_typedef.registermethods(globals())
# ____________________________________________________________
# Helpers for several string implementations
def stringendswith(u_self, suffix, start, end):
begin = end - len(suffix)
if begin < start:
return False
for i in range(len(suffix)):
if u_self[begin+i] != suffix[i]:
return False
return True
def stringstartswith(u_self, prefix, start, end):
stop = start + len(prefix)
if stop > end:
return False
for i in range(len(prefix)):
if u_self[start+i] != prefix[i]:
return False
return True
| 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.