[pypy-svn] r55797 - in pypy/branch/js-refactoring-quickhacks/pypy/lang/js: . test test/ecma
santagada at codespeak.net
santagada at codespeak.net
Thu Jun 12 21:53:28 CEST 2008
Author: santagada
Date: Thu Jun 12 21:53:27 2008
New Revision: 55797
Modified:
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/baseop.py
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/interpreter.py
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/js_interactive.py
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jscode.py
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jsobj.py
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/operations.py
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/ecma/conftest.py
pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/test_parser.py
Log:
unicode port, translates, but has limited funcionality tranlated, mostly because of missing split, lower, upper
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/baseop.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/baseop.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/baseop.py Thu Jun 12 21:53:27 2008
@@ -131,9 +131,9 @@
type1 = x.type()
type2 = y.type()
if type1 == type2:
- if type1 == "undefined" or type1 == "null":
+ if type1 == u"undefined" or type1 == u"null":
return True
- if type1 == "number":
+ if type1 == u"number":
n1 = x.ToNumber(ctx)
n2 = y.ToNumber(ctx)
if isnan(n1) or isnan(n2):
@@ -141,37 +141,37 @@
if n1 == n2:
return True
return False
- elif type1 == "string":
+ elif type1 == u"string":
return x.ToString(ctx) == y.ToString(ctx)
- elif type1 == "boolean":
+ elif type1 == u"boolean":
return x.ToBoolean() == x.ToBoolean()
# XXX rethink it here
return x.ToString(ctx) == y.ToString(ctx)
else:
#step 14
- if (type1 == "undefined" and type2 == "null") or \
- (type1 == "null" and type2 == "undefined"):
+ if (type1 == u"undefined" and type2 == u"null") or \
+ (type1 == u"null" and type2 == u"undefined"):
return True
- if type1 == "number" and type2 == "string":
+ if type1 == u"number" and type2 == u"string":
return AbstractEC(ctx, x, W_FloatNumber(y.ToNumber(ctx)))
- if type1 == "string" and type2 == "number":
+ if type1 == u"string" and type2 == u"number":
return AbstractEC(ctx, W_FloatNumber(x.ToNumber(ctx)), y)
- if type1 == "boolean":
+ if type1 == u"boolean":
return AbstractEC(ctx, W_FloatNumber(x.ToNumber(ctx)), y)
- if type2 == "boolean":
+ if type2 == u"boolean":
return AbstractEC(ctx, x, W_FloatNumber(y.ToNumber(ctx)))
- if (type1 == "string" or type1 == "number") and \
- type2 == "object":
+ if (type1 == u"string" or type1 == u"number") and \
+ type2 == u"object":
return AbstractEC(ctx, x, y.ToPrimitive(ctx))
- if (type2 == "string" or type2 == "number") and \
- type1 == "object":
+ if (type2 == u"string" or type2 == u"number") and \
+ type1 == u"object":
return AbstractEC(ctx, x.ToPrimitive(ctx), y)
return False
objtype = x.GetValue().type()
if objtype == y.GetValue().type():
- if objtype == "undefined" or objtype == "null":
+ if objtype == u"undefined" or objtype == u"null":
return True
if isinstance(x, W_String) and isinstance(y, W_String):
@@ -189,9 +189,9 @@
type2 = y.type()
if type1 != type2:
return False
- if type1 == "undefined" or type1 == "null":
+ if type1 == u"undefined" or type1 == u"null":
return True
- if type1 == "number":
+ if type1 == u"number":
n1 = x.ToNumber(ctx)
n2 = y.ToNumber(ctx)
if isnan(n1) or isnan(n2):
@@ -199,20 +199,20 @@
if n1 == n2:
return True
return False
- if type1 == "string":
+ if type1 == u"string":
return x.ToString(ctx) == y.ToString(ctx)
- if type1 == "boolean":
+ if type1 == u"boolean":
return x.ToBoolean() == x.ToBoolean()
return x == y
def commonnew(ctx, obj, args):
if not isinstance(obj, W_PrimitiveObject):
- raise ThrowException(W_String('it is not a constructor'))
+ raise ThrowException(W_String(u'it is not a constructor'))
try:
res = obj.Construct(ctx=ctx, args=args)
except JsTypeError:
- raise ThrowException(W_String('it is not a constructor'))
+ raise ThrowException(W_String(u'it is not a constructor'))
return res
def uminus(obj, ctx):
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/interpreter.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/interpreter.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/interpreter.py Thu Jun 12 21:53:27 2008
@@ -48,7 +48,7 @@
args[0] is w_Null):
# XXX later we could separate builtins and normal objects
return args[0].ToObject(ctx)
- return create_object(ctx, 'Object')
+ return create_object(ctx, u'Object')
class W_BooleanObject(W_NativeObject):
def Call(self, ctx, args=[], this=None):
@@ -60,8 +60,8 @@
def Construct(self, ctx, args=[]):
if len(args) >= 1 and not isnull_or_undefined(args[0]):
Value = newbool(args[0].ToBoolean())
- return create_object(ctx, 'Boolean', Value = Value)
- return create_object(ctx, 'Boolean', Value = newbool(False))
+ return create_object(ctx, u'Boolean', Value = Value)
+ return create_object(ctx, u'Boolean', Value = newbool(False))
class W_NumberObject(W_NativeObject):
def Call(self, ctx, args=[], this=None):
@@ -78,28 +78,28 @@
def Construct(self, ctx, args=[]):
if len(args) >= 1 and not isnull_or_undefined(args[0]):
Value = W_FloatNumber(args[0].ToNumber(ctx))
- return create_object(ctx, 'Number', Value = Value)
- return create_object(ctx, 'Number', Value = W_FloatNumber(0.0))
+ return create_object(ctx, u'Number', Value = Value)
+ return create_object(ctx, u'Number', Value = W_FloatNumber(0.0))
class W_StringObject(W_NativeObject):
def Call(self, ctx, args=[], this=None):
if len(args) >= 1:
return W_String(args[0].ToString(ctx))
else:
- return W_String('')
+ return W_String(u'')
def Construct(self, ctx, args=[]):
if len(args) >= 1:
Value = W_String(args[0].ToString(ctx))
- return create_object(ctx, 'String', Value = Value)
- return create_object(ctx, 'String', Value = W_String(''))
+ return Value.ToObject(ctx)
+ return W_String(u'').ToObject(ctx)
def create_array(ctx, elements=[]):
- proto = ctx.get_global().Get(ctx, 'Array').Get(ctx, 'prototype')
+ proto = ctx.get_global().Get(ctx, u'Array').Get(ctx, u'prototype')
array = W_Array(ctx, Prototype=proto, Class = proto.Class)
i = 0
while i < len(elements):
- array.Put(ctx, str(i), elements[i])
+ array.Put(ctx, unicode(str(i)), elements[i])
i += 1
return array
@@ -108,7 +108,7 @@
def Call(self, ctx, args=[], this=None):
if len(args) == 1 and isinstance(args[0], W_BaseNumber):
array = create_array(ctx)
- array.Put(ctx, 'length', args[0])
+ array.Put(ctx, u'length', args[0])
else:
array = create_array(ctx, args)
return array
@@ -121,7 +121,7 @@
def evaljs(ctx, args, this):
if len(args) >= 1:
if isinstance(args[0], W_String):
- src = args[0].strval
+ src = args[0].ToString(ctx).encode('ascii') # XXX what is the best aproach here?
else:
return args[0]
else:
@@ -129,7 +129,7 @@
try:
node = load_source(src, 'evalcode')
except ParseError, e:
- raise ThrowException(W_String('SyntaxError: '+str(e)))
+ raise ThrowException(W_String(u'SyntaxError: ' + unicode(str(e))))
bytecode = JsCode()
node.emit(bytecode)
@@ -138,18 +138,18 @@
def parseIntjs(ctx, args, this):
if len(args) < 1:
return W_FloatNumber(NAN)
- s = args[0].ToString(ctx).strip(" ")
+ s = args[0].ToString(ctx).strip(u' ')
if len(args) > 1:
radix = args[1].ToInt32(ctx)
else:
radix = 10
- if len(s) >= 2 and (s.startswith('0x') or s.startswith('0X')) :
+ if len(s) >= 2 and (s.startswith(u'0x') or s.startswith(u'0X')) :
radix = 16
s = s[2:]
- if s == '' or radix < 2 or radix > 36:
+ if s == u'' or radix < 2 or radix > 36:
return W_FloatNumber(NAN)
try:
- n = int(s, radix)
+ n = int(s.encode('ascii'), radix)
except ValueError:
return W_FloatNumber(NAN)
return W_IntNumber(n)
@@ -157,16 +157,16 @@
def parseFloatjs(ctx, args, this):
if len(args) < 1:
return W_FloatNumber(NAN)
- s = args[0].ToString(ctx).strip(" ")
+ s = args[0].ToString(ctx).strip(u' ')
try:
- n = float(s)
+ n = float(s.encode('ascii'))
except ValueError:
n = NAN
return W_FloatNumber(n)
def printjs(ctx, args, this):
- writer(",".join([i.ToString(ctx) for i in args]))
+ writer(u','.join([i.ToString(ctx) for i in args]))
return w_Undefined
def isnanjs(ctx, args, this):
@@ -204,35 +204,35 @@
return w_Undefined
def _ishex(ch):
- return ((ch >= 'a' and ch <= 'f') or (ch >= '0' and ch <= '9') or
- (ch >= 'A' and ch <= 'F'))
+ return ((ch >= u'a' and ch <= u'f') or (ch >= u'0' and ch <= u'9') or
+ (ch >= u'A' and ch <= u'F'))
def unescapejs(ctx, args, this):
# XXX consider using StringBuilder here
res = []
if not isinstance(args[0], W_String):
- raise JsTypeError(W_String("Expected string"))
+ raise JsTypeError(W_String(u'Expected string'))
strval = args[0].strval
lgt = len(strval)
i = 0
while i < lgt:
ch = strval[i]
- if ch == '%':
+ if ch == u'%':
if (i + 2 < lgt and _ishex(strval[i+1]) and _ishex(strval[i+2])):
- ch = chr(int(strval[i + 1] + strval[i + 2], 16))
+ ch = unichr(int((strval[i + 1] + strval[i + 2]).encode('ascii'), 16))
i += 2
elif (i + 5 < lgt and strval[i + 1] == 'u' and
_ishex(strval[i + 2]) and _ishex(strval[i + 3]) and
_ishex(strval[i + 4]) and _ishex(strval[i + 5])):
- ch = unichr(int(strval[i+2:i+6], 16))
+ ch = unichr(int((strval[i+2:i+6]).encode('ascii'), 16))
i += 5
i += 1
res.append(ch)
- return W_String(''.join(res))
+ return W_String(u''.join(res))
class W_ToString(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
- return W_String("[object %s]"%this.Class)
+ return W_String(u'[object ' + this.Class + u']')
class W_ValueOf(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
@@ -273,10 +273,12 @@
argslist = []
for i in range(tam-1):
argslist.append(args[i].ToString(ctx))
- fargs = ','.join(argslist)
- functioncode = "function (%s) {%s}"%(fargs, fbody)
+ fargs = u','.join(argslist)
+ functioncode = u'function (' + fargs + u') {' + fbody + u'}'
else:
- functioncode = "function () {}"
+ functioncode = u'function () {}'
+
+ functioncode = unicode(functioncode).encode('ascii') # XXX this is potentialy very bad
#remove program and sourcelements node
funcnode = parse(functioncode).children[0].children[0]
ast = ASTBUILDER.dispatch(funcnode)
@@ -287,15 +289,15 @@
def Construct(self, ctx, args=[]):
return self.Call(ctx, args, this=None)
-functionstring= 'function (arguments go here!) {\n'+ \
- ' [lots of stuff :)]\n'+ \
- '}'
+functionstring= u'function (arguments go here!) {\n'+ \
+ u' [lots of stuff :)]\n'+ \
+ u'}'
class W_FToString(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
- if this.Class == 'Function':
+ if this.Class == u'Function':
return W_String(functionstring)
else:
- raise JsTypeError('this is not a function object')
+ raise JsTypeError(u'this is not a function object')
class W_Apply(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
@@ -314,7 +316,7 @@
elif isnull_or_undefined(arrayArgs):
callargs = []
else:
- raise JsTypeError('arrayArgs is not an Array or Arguments object')
+ raise JsTypeError(u'arrayArgs is not an Array or Arguments object')
except IndexError:
callargs = []
return this.Call(ctx, callargs, this=thisArg)
@@ -334,21 +336,21 @@
class W_ValueToString(W_NewBuiltin):
"this is the toString function for objects with Value"
- mytype = ''
+ mytype = u''
def Call(self, ctx, args=[], this=None):
if this.Value.type() != self.mytype:
- raise JsTypeError('Wrong type')
+ raise JsTypeError(u'Wrong type')
return W_String(this.Value.ToString(ctx))
class W_NumberValueToString(W_ValueToString):
- mytype = 'number'
+ mytype = u'number'
class W_BooleanValueToString(W_ValueToString):
- mytype = 'boolean'
+ mytype = u'boolean'
class W_StringValueToString(W_ValueToString):
- mytype = 'string'
+ mytype = u'string'
@specialize.memo()
@@ -357,7 +359,7 @@
"this is the valueOf function for objects with Value"
def Call(self, ctx, args=[], this=None):
if type != this.Class:
- raise JsTypeError('%s.prototype.valueOf called with incompatible type' % self.type())
+ raise JsTypeError(self.type() + u'.prototype.valueOf called with incompatible type')
return this.Value
return W_ValueValueOf
@@ -366,12 +368,27 @@
temp = []
for arg in args:
i = arg.ToInt32(ctx) % 65536 # XXX should be uint16
- if i > 255:
- temp.append(unichr(i))
- else:
- temp.append(chr(i))
+ temp.append(unichr(i))
- return W_String(''.join(temp))
+ return W_String(u''.join(temp))
+
+class W_ToLower(W_NewBuiltin):
+ def Call(self, ctx, args=[], this=None):
+ string = this.ToString(ctx)
+ if we_are_translated():
+ temp = string.encode('ascii')
+ return W_String(unicode(temp.lower())) # XXX rpython unicode doesn't have lower
+ else:
+ return W_String(string.lower())
+
+class W_ToUpper(W_NewBuiltin):
+ def Call(self, ctx, args=[], this=None):
+ string = this.ToString(ctx)
+ if we_are_translated():
+ temp = string.encode('ascii')
+ return W_String(unicode(temp.upper())) # XXX rpython unicode doesn't have upper
+ else:
+ return W_String(string.upper())
class W_CharAt(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
@@ -379,16 +396,27 @@
if len(args)>=1:
pos = args[0].ToInt32(ctx)
if (not pos >=0) or (pos > len(string) - 1):
- return W_String('')
+ return W_String(u'')
else:
- return W_String('')
+ return W_String(u'')
return W_String(string[pos])
+class W_CharCodeAt(W_NewBuiltin):
+ def Call(self, ctx, args=[], this=None):
+ string = this.ToString(ctx)
+ if len(args)>=1:
+ pos = args[0].ToInt32(ctx)
+ if (not pos >=0) or (pos > len(string) - 1):
+ return W_String(u'')
+ else:
+ return W_String(u'')
+ return W_IntNumber(ord(string[pos]))
+
class W_Concat(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
string = this.ToString(ctx)
others = [obj.ToString(ctx) for obj in args]
- string += ''.join(others)
+ string += u''.join(others)
return W_String(string)
class W_IndexOf(W_NewBuiltin):
@@ -434,30 +462,38 @@
separator = args[0].ToString(ctx)
if len(args) >= 2:
- limit = args[1].ToUInt32(ctx)
- raise ThrowException(W_String("limit not implemented"))
+ #limit = args[1].ToUInt32(ctx)
+ raise ThrowException(W_String(u'limit not implemented'))
# array = string.split(separator, limit)
else:
- array = string.split(separator)
+ if we_are_translated():
+ temp = string.encode('ascii')
+ tempsep = separator.encode('ascii')
+ arrtemp = temp.split(tempsep)
+ array = []
+ for i in arrtemp:
+ array.append(unicode(i))
+ else:
+ array = string.split(separator)
w_array = create_array(ctx)
i = 0
while i < len(array):
w_str = W_String(array[i])
- w_array.Put(ctx, str(i), w_str)
+ w_array.Put(ctx, unicode(str(i)), w_str)
i += 1
return w_array
-def common_join(ctx, this, sep=','):
- length = this.Get(ctx, 'length').ToUInt32(ctx)
+def common_join(ctx, this, sep=u','):
+ length = this.Get(ctx, u'length').ToUInt32(ctx)
l = []
i = 0
while i < length:
- item = this.Get(ctx, str(i))
+ item = this.Get(ctx, unicode(str(i)))
if isnull_or_undefined(item):
- item_string = ''
+ item_string = u''
else:
item_string = item.ToString(ctx)
l.append(item_string)
@@ -467,21 +503,21 @@
class W_ArrayToString(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
- return W_String(common_join(ctx, this, sep=','))
+ return W_String(common_join(ctx, this, sep=u','))
class W_ArrayJoin(W_NewBuiltin):
def Call(self, ctx, args=[], this=None):
if len(args) >= 1 and not args[0] is w_Undefined:
sep = args[0].ToString(ctx)
else:
- sep = ','
+ sep = u','
return W_String(common_join(ctx, this, sep))
class W_ArrayReverse(W_NewBuiltin):
length = 0
def Call(self, ctx, args=[], this=None):
- r2 = this.Get(ctx, 'length').ToUInt32(ctx)
+ r2 = this.Get(ctx, u'length').ToUInt32(ctx)
k = r_uint(0)
r3 = r_uint(math.floor( float(r2)/2.0 ))
if r3 == k:
@@ -489,8 +525,8 @@
while k < r3:
r6 = r2 - k - 1
- r7 = str(k)
- r8 = str(r6)
+ r7 = unicode(str(k))
+ r8 = unicode(str(r6))
r9 = this.Get(ctx, r7)
r10 = this.Get(ctx, r8)
@@ -503,10 +539,10 @@
class W_DateFake(W_NewBuiltin): # XXX This is temporary
def Call(self, ctx, args=[], this=None):
- return create_object(ctx, 'Object')
+ return create_object(ctx, u'Object')
def Construct(self, ctx, args=[]):
- return create_object(ctx, 'Object')
+ return create_object(ctx, u'Object')
def pypy_repr(ctx, repr, w_arg):
return W_String(w_arg.__class__.__name__)
@@ -519,175 +555,178 @@
"""Creates a js interpreter"""
def __init__(self):
allon = DE | DD | RO
- w_Global = W_Object(Class="global")
+ w_Global = W_Object(Class=u'global')
ctx = global_context(w_Global)
- w_ObjPrototype = W_Object(Prototype=None, Class='Object')
+ w_ObjPrototype = W_Object(Prototype=None, Class=u'Object')
- w_Function = W_Function(ctx, Class='Function',
+ w_Function = W_Function(ctx, Class=u'Function',
Prototype=w_ObjPrototype)
- w_Function.Put(ctx, 'length', W_IntNumber(1), flags = allon)
- w_Global.Put(ctx, 'Function', w_Function)
+ w_Function.Put(ctx, u'length', W_IntNumber(1), flags = allon)
+ w_Global.Put(ctx, u'Function', w_Function)
- w_Object = W_ObjectObject('Object', w_Function)
- w_Object.Put(ctx, 'prototype', w_ObjPrototype, flags = allon)
- w_Object.Put(ctx, 'length', W_IntNumber(1), flags = RO | DD)
- w_Global.Put(ctx, 'Object', w_Object)
+ w_Object = W_ObjectObject(u'Object', w_Function)
+ w_Object.Put(ctx, u'prototype', w_ObjPrototype, flags = allon)
+ w_Object.Put(ctx, u'length', W_IntNumber(1), flags = RO | DD)
+ w_Global.Put(ctx, u'Object', w_Object)
w_Global.Prototype = w_ObjPrototype
w_FncPrototype = w_Function.Call(ctx, this=w_Function)
- w_Function.Put(ctx, 'prototype', w_FncPrototype, flags = allon)
- w_Function.Put(ctx, 'constructor', w_Function)
+ w_Function.Put(ctx, u'prototype', w_FncPrototype, flags = allon)
+ w_Function.Put(ctx, u'constructor', w_Function)
toString = W_ToString(ctx)
put_values(ctx, w_ObjPrototype, {
- 'constructor': w_Object,
- '__proto__': w_FncPrototype,
- 'toString': toString,
- 'toLocaleString': toString,
- 'valueOf': W_ValueOf(ctx),
- 'hasOwnProperty': W_HasOwnProperty(ctx),
- 'isPrototypeOf': W_IsPrototypeOf(ctx),
- 'propertyIsEnumerable': W_PropertyIsEnumerable(ctx),
+ u'constructor': w_Object,
+ u'__proto__': w_FncPrototype,
+ u'toString': toString,
+ u'toLocaleString': toString,
+ u'valueOf': W_ValueOf(ctx),
+ u'hasOwnProperty': W_HasOwnProperty(ctx),
+ u'isPrototypeOf': W_IsPrototypeOf(ctx),
+ u'propertyIsEnumerable': W_PropertyIsEnumerable(ctx),
})
#properties of the function prototype
put_values(ctx, w_FncPrototype, {
- 'constructor': w_Function,
- '__proto__': w_FncPrototype,
- 'toString': W_FToString(ctx),
- 'apply': W_Apply(ctx),
- 'call': W_Call(ctx),
- 'arguments': w_Null,
+ u'constructor': w_Function,
+ u'__proto__': w_FncPrototype,
+ u'toString': W_FToString(ctx),
+ u'apply': W_Apply(ctx),
+ u'call': W_Call(ctx),
+ u'arguments': w_Null,
})
- w_Boolean = W_BooleanObject('Boolean', w_FncPrototype)
- w_Boolean.Put(ctx, 'constructor', w_FncPrototype, flags = allon)
- w_Boolean.Put(ctx, 'length', W_IntNumber(1), flags = allon)
+ w_Boolean = W_BooleanObject(u'Boolean', w_FncPrototype)
+ w_Boolean.Put(ctx, u'constructor', w_FncPrototype, flags = allon)
+ w_Boolean.Put(ctx, u'length', W_IntNumber(1), flags = allon)
- w_BoolPrototype = create_object(ctx, 'Object', Value=newbool(False))
- w_BoolPrototype.Class = 'Boolean'
+ w_BoolPrototype = create_object(ctx, u'Object', Value=newbool(False))
+ w_BoolPrototype.Class = u'Boolean'
put_values(ctx, w_BoolPrototype, {
- 'constructor': w_FncPrototype,
- '__proto__': w_ObjPrototype,
- 'toString': W_BooleanValueToString(ctx),
- 'valueOf': get_value_of('Boolean')(ctx),
+ u'constructor': w_FncPrototype,
+ u'__proto__': w_ObjPrototype,
+ u'toString': W_BooleanValueToString(ctx),
+ u'valueOf': get_value_of(u'Boolean')(ctx),
})
- w_Boolean.Put(ctx, 'prototype', w_BoolPrototype, flags = allon)
- w_Global.Put(ctx, 'Boolean', w_Boolean)
+ w_Boolean.Put(ctx, u'prototype', w_BoolPrototype, flags = allon)
+ w_Global.Put(ctx, u'Boolean', w_Boolean)
#Number
- w_Number = W_NumberObject('Number', w_FncPrototype)
+ w_Number = W_NumberObject(u'Number', w_FncPrototype)
- w_empty_fun = w_Function.Call(ctx, args=[W_String('')])
+ w_empty_fun = w_Function.Call(ctx, args=[W_String(u'')])
- w_NumPrototype = create_object(ctx, 'Object', Value=W_FloatNumber(0.0))
- w_NumPrototype.Class = 'Number'
+ w_NumPrototype = create_object(ctx, u'Object', Value=W_FloatNumber(0.0))
+ w_NumPrototype.Class = u'Number'
put_values(ctx, w_NumPrototype, {
- 'constructor': w_Number,
- '__proto__': w_empty_fun,
- 'toString': W_NumberValueToString(ctx),
- 'valueOf': get_value_of('Number')(ctx),
+ u'constructor': w_Number,
+ u'__proto__': w_empty_fun,
+ u'toString': W_NumberValueToString(ctx),
+ u'valueOf': get_value_of(u'Number')(ctx),
})
put_values(ctx, w_Number, {
- 'constructor': w_FncPrototype,
- 'prototype': w_NumPrototype,
- '__proto__': w_empty_fun,
- 'length' : W_IntNumber(1),
+ u'constructor': w_FncPrototype,
+ u'prototype': w_NumPrototype,
+ u'__proto__': w_empty_fun,
+ u'length' : W_IntNumber(1),
})
- w_Number.propdict['prototype'].flags |= RO
- w_Number.Put(ctx, 'MAX_VALUE', W_FloatNumber(1.7976931348623157e308), flags = RO|DD)
- w_Number.Put(ctx, 'MIN_VALUE', W_FloatNumber(0), flags = RO|DD)
- w_Number.Put(ctx, 'NaN', W_FloatNumber(NAN), flags = RO|DD)
+ w_Number.propdict[u'prototype'].flags |= RO
+ w_Number.Put(ctx, u'MAX_VALUE', W_FloatNumber(1.7976931348623157e308), flags = RO|DD)
+ w_Number.Put(ctx, u'MIN_VALUE', W_FloatNumber(0.0), flags = RO|DD)
+ w_Number.Put(ctx, u'NaN', W_FloatNumber(NAN), flags = RO|DD)
# ^^^ this is exactly in test case suite
- w_Number.Put(ctx, 'POSITIVE_INFINITY', W_FloatNumber(INFINITY), flags = RO|DD)
- w_Number.Put(ctx, 'NEGATIVE_INFINITY', W_FloatNumber(-INFINITY), flags = RO|DD)
+ w_Number.Put(ctx, u'POSITIVE_INFINITY', W_FloatNumber(INFINITY), flags = RO|DD)
+ w_Number.Put(ctx, u'NEGATIVE_INFINITY', W_FloatNumber(-INFINITY), flags = RO|DD)
- w_Global.Put(ctx, 'Number', w_Number)
+ w_Global.Put(ctx, u'Number', w_Number)
#String
- w_String = W_StringObject('String', w_FncPrototype)
+ w_String = W_StringObject(u'String', w_FncPrototype)
- w_StrPrototype = create_object(ctx, 'Object', Value=W_String(''))
- w_StrPrototype.Class = 'String'
+ w_StrPrototype = create_object(ctx, u'Object', Value=W_String(u''))
+ w_StrPrototype.Class = u'String'
put_values(ctx, w_StrPrototype, {
- 'constructor': w_FncPrototype,
- '__proto__': w_StrPrototype,
- 'toString': W_StringValueToString(ctx),
- 'valueOf': get_value_of('String')(ctx),
- 'charAt': W_CharAt(ctx),
- 'concat': W_Concat(ctx),
- 'indexOf': W_IndexOf(ctx),
- 'substring': W_Substring(ctx),
- 'split': W_Split(ctx),
+ u'constructor': w_FncPrototype,
+ u'__proto__': w_StrPrototype,
+ u'toString': W_StringValueToString(ctx),
+ u'valueOf': get_value_of(u'String')(ctx),
+ u'toLowerCase': W_ToLower(ctx),
+ u'toUpperCase': W_ToUpper(ctx),
+ u'charAt': W_CharAt(ctx),
+ u'charCodeAt': W_CharCodeAt(ctx),
+ u'concat': W_Concat(ctx),
+ u'indexOf': W_IndexOf(ctx),
+ u'substring': W_Substring(ctx),
+ u'split': W_Split(ctx),
})
- w_String.Put(ctx, 'prototype', w_StrPrototype)
- w_String.Put(ctx, 'fromCharCode', W_FromCharCode(ctx))
- w_Global.Put(ctx, 'String', w_String)
+ w_String.Put(ctx, u'prototype', w_StrPrototype)
+ w_String.Put(ctx, u'fromCharCode', W_FromCharCode(ctx))
+ w_Global.Put(ctx, u'String', w_String)
- w_Array = W_ArrayObject('Array', w_FncPrototype)
+ w_Array = W_ArrayObject(u'Array', w_FncPrototype)
w_ArrPrototype = W_Array(Prototype=w_ObjPrototype)
w_arr_join = W_ArrayJoin(ctx)
- w_arr_join.Put(ctx, 'length', W_IntNumber(1), flags=allon)
+ w_arr_join.Put(ctx, u'length', W_IntNumber(1), flags=allon)
put_values(ctx, w_ArrPrototype, {
- 'constructor': w_FncPrototype,
- '__proto__': w_ArrPrototype,
- 'toString': W_ArrayToString(ctx),
- 'join': w_arr_join,
- 'reverse': W_ArrayReverse(ctx),
+ u'constructor': w_FncPrototype,
+ u'__proto__': w_ArrPrototype,
+ u'toString': W_ArrayToString(ctx),
+ u'join': w_arr_join,
+ u'reverse': W_ArrayReverse(ctx),
})
- w_Array.Put(ctx, 'prototype', w_ArrPrototype, flags = allon)
- w_Array.Put(ctx, '__proto__', w_FncPrototype, flags = allon)
- w_Array.Put(ctx, 'length', W_IntNumber(1), flags = allon)
- w_Global.Put(ctx, 'Array', w_Array)
+ w_Array.Put(ctx, u'prototype', w_ArrPrototype, flags = allon)
+ w_Array.Put(ctx, u'__proto__', w_FncPrototype, flags = allon)
+ w_Array.Put(ctx, u'length', W_IntNumber(1), flags = allon)
+ w_Global.Put(ctx, u'Array', w_Array)
#Math
- w_math = W_Object(Class='Math')
- w_Global.Put(ctx, 'Math', w_math)
- w_math.Put(ctx, '__proto__', w_ObjPrototype)
- w_math.Put(ctx, 'prototype', w_ObjPrototype, flags = allon)
- w_math.Put(ctx, 'abs', W_Builtin(absjs, Class='function'))
- w_math.Put(ctx, 'floor', W_Builtin(floorjs, Class='function'))
- w_math.Put(ctx, 'pow', W_Builtin(powjs, Class='function'))
- w_math.Put(ctx, 'sqrt', W_Builtin(sqrtjs, Class='function'))
- w_math.Put(ctx, 'E', W_FloatNumber(math.e))
- w_math.Put(ctx, 'PI', W_FloatNumber(math.pi))
+ w_math = W_Object(Class=u'Math')
+ w_Global.Put(ctx, u'Math', w_math)
+ w_math.Put(ctx, u'__proto__', w_ObjPrototype)
+ w_math.Put(ctx, u'prototype', w_ObjPrototype, flags = allon)
+ w_math.Put(ctx, u'abs', W_Builtin(absjs, Class=u'function'))
+ w_math.Put(ctx, u'floor', W_Builtin(floorjs, Class=u'function'))
+ w_math.Put(ctx, u'pow', W_Builtin(powjs, Class=u'function'))
+ w_math.Put(ctx, u'sqrt', W_Builtin(sqrtjs, Class=u'function'))
+ w_math.Put(ctx, u'E', W_FloatNumber(math.e))
+ w_math.Put(ctx, u'PI', W_FloatNumber(math.pi))
- w_Global.Put(ctx, 'version', W_Builtin(versionjs))
+ w_Global.Put(ctx, u'version', W_Builtin(versionjs))
#Date
- w_Date = W_DateFake(ctx, Class='Date')
- w_Global.Put(ctx, 'Date', w_Date)
+ w_Date = W_DateFake(ctx, Class=u'Date')
+ w_Global.Put(ctx, u'Date', w_Date)
- w_Global.Put(ctx, 'NaN', W_FloatNumber(NAN), flags = DE|DD)
- w_Global.Put(ctx, 'Infinity', W_FloatNumber(INFINITY), flags = DE|DD)
- w_Global.Put(ctx, 'undefined', w_Undefined, flags = DE|DD)
- w_Global.Put(ctx, 'eval', W_Builtin(evaljs))
- w_Global.Put(ctx, 'parseInt', W_Builtin(parseIntjs))
- w_Global.Put(ctx, 'parseFloat', W_Builtin(parseFloatjs))
- w_Global.Put(ctx, 'isNaN', W_Builtin(isnanjs))
- w_Global.Put(ctx, 'isFinite', W_Builtin(isfinitejs))
- w_Global.Put(ctx, 'print', W_Builtin(printjs))
- w_Global.Put(ctx, 'unescape', W_Builtin(unescapejs))
+ w_Global.Put(ctx, u'NaN', W_FloatNumber(NAN), flags = DE|DD)
+ w_Global.Put(ctx, u'Infinity', W_FloatNumber(INFINITY), flags = DE|DD)
+ w_Global.Put(ctx, u'undefined', w_Undefined, flags = DE|DD)
+ w_Global.Put(ctx, u'eval', W_Builtin(evaljs))
+ w_Global.Put(ctx, u'parseInt', W_Builtin(parseIntjs))
+ w_Global.Put(ctx, u'parseFloat', W_Builtin(parseFloatjs))
+ w_Global.Put(ctx, u'isNaN', W_Builtin(isnanjs))
+ w_Global.Put(ctx, u'isFinite', W_Builtin(isfinitejs))
+ w_Global.Put(ctx, u'print', W_Builtin(printjs))
+ w_Global.Put(ctx, u'unescape', W_Builtin(unescapejs))
- w_Global.Put(ctx, 'this', w_Global)
+ w_Global.Put(ctx, u'this', w_Global)
# DEBUGGING
if 0:
- w_Global.Put(ctx, 'pypy_repr', W_Builtin(pypy_repr))
+ w_Global.Put(ctx, u'pypy_repr', W_Builtin(pypy_repr))
self.global_context = ctx
self.w_Global = w_Global
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/js_interactive.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/js_interactive.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/js_interactive.py Thu Jun 12 21:53:27 2008
@@ -50,9 +50,9 @@
code.InteractiveConsole.__init__(self, locals, filename)
self.interpreter = Interpreter()
ctx = self.interpreter.global_context
- self.interpreter.w_Global.Put(ctx, 'quit', W_Builtin(quitjs))
- self.interpreter.w_Global.Put(ctx, 'load', W_Builtin(loadjs))
- self.interpreter.w_Global.Put(ctx, 'trace', W_Builtin(tracejs))
+ self.interpreter.w_Global.Put(ctx, u'quit', W_Builtin(quitjs))
+ self.interpreter.w_Global.Put(ctx, u'load', W_Builtin(loadjs))
+ self.interpreter.w_Global.Put(ctx, u'trace', W_Builtin(tracejs))
def runcodefromfile(self, filename):
@@ -68,11 +68,12 @@
"""
try:
res = self.interpreter.run(ast, interactive=True)
+ ctx = self.interpreter.global_context
if res not in (None, w_Undefined):
try:
- print res.ToString(self.interpreter.w_Global)
+ print res.ToString(ctx)
except ThrowException, exc:
- print exc.exception.ToString(self.interpreter.w_Global)
+ print exc.exception.ToString(ctx)
except SystemExit:
raise
except ThrowException, exc:
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jscode.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jscode.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jscode.py Thu Jun 12 21:53:27 2008
@@ -114,12 +114,12 @@
def emit_break(self):
if not self.endlooplabel:
- raise ThrowException(W_String("Break outside loop"))
+ raise ThrowException(W_String(u'Break outside loop'))
self.emit('JUMP', self.endlooplabel[-1])
def emit_continue(self):
if not self.startlooplabel:
- raise ThrowError(W_String("Continue outside loop"))
+ raise ThrowError(W_String(u'Continue outside loop'))
self.emit('JUMP', self.startlooplabel[-1])
def emit(self, operation, *args):
@@ -324,10 +324,10 @@
self.counter = counter
def eval(self, ctx, stack):
- proto = ctx.get_global().Get(ctx, 'Array').Get(ctx, 'prototype')
+ proto = ctx.get_global().Get(ctx, u'Array').Get(ctx, u'prototype')
array = W_Array(ctx, Prototype=proto, Class = proto.Class)
for i in range(self.counter):
- array.Put(ctx, str(self.counter - i - 1), stack.pop())
+ array.Put(ctx, unicode(str(self.counter - i - 1)), stack.pop())
stack.append(array)
def __repr__(self):
@@ -352,13 +352,13 @@
self.funcobj = funcobj
def eval(self, ctx, stack):
- proto = ctx.get_global().Get(ctx, 'Function').Get(ctx, 'prototype')
- w_func = W_Object(ctx=ctx, Prototype=proto, Class='Function',
+ proto = ctx.get_global().Get(ctx, u'Function').Get(ctx, u'prototype')
+ w_func = W_Object(ctx=ctx, Prototype=proto, Class=u'Function',
callfunc=self.funcobj)
- w_func.Put(ctx, 'length', W_IntNumber(len(self.funcobj.params)))
- w_obj = create_object(ctx, 'Object')
- w_obj.Put(ctx, 'constructor', w_func, flags = jsobj.DE)
- w_func.Put(ctx, 'prototype', w_obj)
+ w_func.Put(ctx, u'length', W_IntNumber(len(self.funcobj.params)))
+ w_obj = create_object(ctx, u'Object')
+ w_obj.Put(ctx, u'constructor', w_func, flags = jsobj.DE)
+ w_func.Put(ctx, u'prototype', w_obj)
stack.append(w_func)
def __repr__(self):
@@ -381,7 +381,7 @@
self.counter = counter
def eval(self, ctx, stack):
- w_obj = create_object(ctx, 'Object')
+ w_obj = create_object(ctx, u'Object')
for _ in range(self.counter):
name = stack.pop().ToString(ctx)
w_elem = stack.pop()
@@ -424,7 +424,7 @@
class IN(BaseBinaryOperation):
def operation(self, ctx, left, right):
if not isinstance(right, W_Object):
- raise ThrowException(W_String("TypeError"))
+ raise ThrowException(W_String(u'TypeError'))
name = left.ToString(ctx)
return newbool(right.HasProperty(name))
@@ -442,7 +442,7 @@
var = ctx.resolve_identifier(ctx, self.name)
stack.append(W_String(var.type()))
except ThrowException:
- stack.append(W_String('undefined'))
+ stack.append(W_String(u'undefined'))
#class Typeof(UnaryOp):
# def eval(self, ctx):
@@ -732,12 +732,12 @@
def eval(self, ctx, stack):
# function declaration actyally don't run anything
- proto = ctx.get_global().Get(ctx, 'Function').Get(ctx, 'prototype')
- w_func = W_Object(ctx=ctx, Prototype=proto, Class='Function', callfunc=self.funcobj)
- w_func.Put(ctx, 'length', W_IntNumber(len(self.funcobj.params)))
- w_obj = create_object(ctx, 'Object')
- w_obj.Put(ctx, 'constructor', w_func, flags = jsobj.DE)
- w_func.Put(ctx, 'prototype', w_obj)
+ proto = ctx.get_global().Get(ctx, u'Function').Get(ctx, u'prototype')
+ w_func = W_Object(ctx=ctx, Prototype=proto, Class=u'Function', callfunc=self.funcobj)
+ w_func.Put(ctx, u'length', W_IntNumber(len(self.funcobj.params)))
+ w_obj = create_object(ctx, u'Object')
+ w_obj.Put(ctx, u'constructor', w_func, flags = jsobj.DE)
+ w_func.Put(ctx, u'prototype', w_obj)
if self.funcobj.name is not None:
ctx.scope[-1].Put(ctx, self.funcobj.name, w_func)
@@ -770,11 +770,11 @@
def common_call(ctx, r1, args, this, name):
if not isinstance(r1, W_PrimitiveObject):
- raise ThrowException(W_String("%s is not a callable (%s)"%(r1.ToString(ctx), name)))
+ raise ThrowException(W_String(r1.ToString(ctx) + u' is not a callable (' + name + u')'))
try:
res = r1.Call(ctx=ctx, args=args.tolist(), this=this)
except JsTypeError:
- raise ThrowException(W_String("%s is not a function (%s)"%(r1.ToString(ctx), name)))
+ raise ThrowException(W_String(r1.ToString(ctx) + u' is not a function (' + name + u')'))
return res
class CALL(Opcode):
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jsobj.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jsobj.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/jsobj.py Thu Jun 12 21:53:27 2008
@@ -35,7 +35,7 @@
return self
def ToString(self, ctx):
- return ''
+ return u''
def ToObject(self, ctx):
# XXX should raise not implemented
@@ -82,36 +82,36 @@
return False
def ToString(self, ctx):
- return "undefined"
+ return u"undefined"
def type(self):
- return 'undefined'
+ return u'undefined'
class W_Null(W_Root):
def __str__(self):
- return "null"
+ return u'null'
def ToBoolean(self):
return False
def ToString(self, ctx):
- return "null"
+ return u'null'
def type(self):
- return 'null'
+ return u'null'
w_Undefined = W_Undefined()
w_Null = W_Null()
class W_PrimitiveObject(W_Root):
- def __init__(self, ctx=None, Prototype=None, Class='Object',
+ def __init__(self, ctx=None, Prototype=None, Class=u'Object',
Value=w_Undefined, callfunc=None):
self.propdict = {}
self.Prototype = Prototype
if Prototype is None:
Prototype = w_Undefined
- self.propdict['prototype'] = Property('prototype', Prototype, flags = DE|DD)
+ self.propdict[u'prototype'] = Property(u'prototype', Prototype, flags = DE|DD)
self.Class = Class
self.callfunc = callfunc
if callfunc is not None:
@@ -122,7 +122,7 @@
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')
+ raise JsTypeError(u'not a function')
act = ActivationObject()
paramn = len(self.callfunc.params)
for i in range(paramn):
@@ -132,21 +132,21 @@
except IndexError:
value = w_Undefined
act.Put(ctx, paramname, value)
- act.Put(ctx, 'this', this)
+ act.Put(ctx, u'this', this)
w_Arguments = W_Arguments(self, args)
- act.Put(ctx, 'arguments', w_Arguments)
+ act.Put(ctx, u'arguments', w_Arguments)
newctx = function_context(self.Scope, act, this)
val = self.callfunc.run(ctx=newctx)
return val
def Construct(self, ctx, args=[]):
- obj = W_Object(Class='Object')
- prot = self.Get(ctx, 'prototype')
+ obj = W_Object(Class=u'Object')
+ prot = self.Get(ctx, u'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(ctx, 'Object').Get(ctx, 'prototype')
+ obj.Prototype = ctx.get_global().Get(ctx, u'Object').Get(ctx, u'prototype')
try: #this is a hack to be compatible to spidermonkey
self.Call(ctx, args, this=obj)
return obj
@@ -206,9 +206,9 @@
def DefaultValue(self, ctx, hint=""):
if hint == "String":
- return self.internal_def_value(ctx, "toString", "valueOf")
+ return self.internal_def_value(ctx, u"toString", u"valueOf")
else: # hint can only be empty, String or Number
- return self.internal_def_value(ctx, "valueOf", "toString")
+ return self.internal_def_value(ctx, u"valueOf", u"toString")
ToPrimitive = DefaultValue
@@ -219,17 +219,17 @@
try:
res = self.ToPrimitive(ctx, 'String')
except JsTypeError:
- return "[object %s]"%(self.Class,)
+ return u'[object ' + self.Class + u']'
return res.ToString(ctx)
def __str__(self):
- return "<Object class: %s>" % self.Class
+ return u"<Object class: %s>" % self.Class
def type(self):
if self.callfunc is not None:
- return 'function'
+ return u'function'
else:
- return 'object'
+ return u'object'
class W_Primitive(W_Root):
@@ -241,19 +241,19 @@
return W_String(this.ToString(ctx))
class W_Object(W_PrimitiveObject):
- def __init__(self, ctx=None, Prototype=None, Class='Object',
+ def __init__(self, ctx=None, Prototype=None, Class=u'Object',
Value=w_Undefined, callfunc=None):
W_PrimitiveObject.__init__(self, ctx, Prototype,
Class, Value, callfunc)
def ToNumber(self, ctx):
- return self.Get(ctx, 'valueOf').Call(ctx, args=[], this=self).ToNumber(ctx)
+ return self.Get(ctx, u'valueOf').Call(ctx, args=[], this=self).ToNumber(ctx)
class W_NewBuiltin(W_PrimitiveObject):
- def __init__(self, ctx, Prototype=None, Class='function',
+ def __init__(self, ctx, Prototype=None, Class=u'function',
Value=w_Undefined, callfunc=None):
if Prototype is None:
- proto = ctx.get_global().Get(ctx, 'Function').Get(ctx, 'prototype')
+ proto = ctx.get_global().Get(ctx, u'Function').Get(ctx, u'prototype')
Prototype = proto
W_PrimitiveObject.__init__(self, ctx, Prototype, Class, Value, callfunc)
@@ -265,7 +265,7 @@
return self.Class
class W_Builtin(W_PrimitiveObject):
- def __init__(self, builtin=None, ctx=None, Prototype=None, Class='function',
+ def __init__(self, builtin=None, ctx=None, Prototype=None, Class=u'function',
Value=w_Undefined, callfunc=None):
W_PrimitiveObject.__init__(self, ctx, Prototype, Class, Value, callfunc)
self.set_builtin_call(builtin)
@@ -280,60 +280,60 @@
return self.callfuncbi(ctx, args, None)
def type(self):
- return 'builtin'
+ return u'builtin'
class W_ListObject(W_PrimitiveObject):
def tolist(self):
l = []
for i in range(self.length):
- l.append(self.propdict[str(i)].value)
+ l.append(self.propdict[unicode(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"]
+ W_PrimitiveObject.__init__(self, Class=u'Arguments')
+ del self.propdict[u'prototype']
# XXX None can be dangerous here
- self.Put(None, 'callee', callee)
- self.Put(None, 'length', W_IntNumber(len(args)))
+ self.Put(None, u'callee', callee)
+ self.Put(None, u'length', W_IntNumber(len(args)))
for i in range(len(args)):
- self.Put(None, str(i), args[i])
+ self.Put(None, unicode(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"]
+ W_PrimitiveObject.__init__(self, Class=u'Activation')
+ del self.propdict[u'prototype']
def __repr__(self):
- return str(self.propdict)
+ return unicode(self.propdict)
class W_Array(W_ListObject):
- def __init__(self, ctx=None, Prototype=None, Class='Array',
+ def __init__(self, ctx=None, Prototype=None, Class=u'Array',
Value=w_Undefined, callfunc=None):
W_ListObject.__init__(self, ctx, Prototype, Class, Value, callfunc)
- self.Put(ctx, 'length', W_IntNumber(0), flags = DD)
+ self.Put(ctx, u'length', W_IntNumber(0), flags = DD)
self.length = r_uint(0)
def set_length(self, newlength):
if newlength < self.length:
i = newlength
while i < self.length:
- key = str(i)
+ key = unicode(str(i))
if key in self.propdict:
del self.propdict[key]
i += 1
self.length = newlength
- self.propdict['length'].value = W_FloatNumber(newlength)
+ self.propdict[u'length'].value = W_FloatNumber(float(str(newlength)))
def Put(self, ctx, P, V, flags = 0):
if not self.CanPut(P): return
if not P in self.propdict:
self.propdict[P] = Property(P, V, flags = flags)
else:
- if P != 'length':
+ if P != u'length':
self.propdict[P].value = V
else:
length = V.ToUInt32(ctx)
@@ -344,11 +344,11 @@
return
try:
- arrayindex = r_uint(float(P))
+ arrayindex = r_uint(float(P.encode('ascii')))
except ValueError:
return
- if (arrayindex < self.length) or (arrayindex != float(P)):
+ if (arrayindex < self.length) or (arrayindex != float(P.encode('ascii'))):
return
else:
if (arrayindex + 1) == 0:
@@ -360,12 +360,12 @@
self.boolval = bool(boolval)
def ToObject(self, ctx):
- return create_object(ctx, 'Boolean', Value=self)
+ return create_object(ctx, u'Boolean', Value=self)
def ToString(self, ctx=None):
if self.boolval == True:
- return "true"
- return "false"
+ return u"true"
+ return u"false"
def ToNumber(self, ctx):
if self.boolval:
@@ -376,22 +376,23 @@
return self.boolval
def type(self):
- return 'boolean'
+ return u'boolean'
def __repr__(self):
- return "<W_Bool "+str(self.boolval)+" >"
+ return u'<W_Bool %s >' % unicode(str(self.boolval))
class W_String(W_Primitive):
def __init__(self, strval):
W_Primitive.__init__(self)
+ assert isinstance(strval, unicode)
self.strval = strval
def __repr__(self):
- return 'W_String(%s)' % (self.strval,)
+ return u'W_String(%s)' % self.strval
def ToObject(self, ctx):
- o = create_object(ctx, 'String', Value=self)
- o.Put(ctx, 'length', W_IntNumber(len(self.strval)), flags = RO|DD)
+ o = create_object(ctx, u'String', Value=self)
+ o.Put(ctx, u'length', W_IntNumber(len(self.strval)), flags = RO|DD|DE)
return o
def ToString(self, ctx=None):
@@ -404,7 +405,7 @@
return True
def type(self):
- return 'string'
+ return u'string'
def GetPropertyName(self):
return self.ToString()
@@ -413,7 +414,7 @@
if not self.strval:
return 0.0
try:
- return float(self.strval)
+ return float(self.strval.encode('ascii'))
except ValueError:
return NAN
@@ -422,13 +423,13 @@
and those known to be integers
"""
def ToObject(self, ctx):
- return create_object(ctx, 'Number', Value=self)
+ return create_object(ctx, u'Number', Value=self)
def Get(self, ctx, P):
return w_Undefined
def type(self):
- return 'number'
+ return u'number'
class W_IntNumber(W_BaseNumber):
""" Number known to be an integer
@@ -439,7 +440,7 @@
def ToString(self, ctx=None):
# XXX incomplete, this doesn't follow the 9.8.1 recommendation
- return str(self.intval)
+ return unicode(str(self.intval))
def ToBoolean(self):
return bool(self.intval)
@@ -458,33 +459,34 @@
return self.ToString()
def __repr__(self):
- return 'W_IntNumber(%s)' % (self.intval,)
+ return u'W_IntNumber(%s)' % (self.intval,)
class W_FloatNumber(W_BaseNumber):
""" Number known to be a float
"""
def __init__(self, floatval):
W_BaseNumber.__init__(self)
- self.floatval = float(floatval)
+ assert isinstance(floatval, float)
+ self.floatval = floatval
def ToString(self, ctx = None):
# XXX incomplete, this doesn't follow the 9.8.1 recommendation
if isnan(self.floatval):
- return 'NaN'
+ return u'NaN'
if isinf(self.floatval):
if self.floatval > 0:
- return 'Infinity'
+ return u'Infinity'
else:
- return '-Infinity'
+ return u'-Infinity'
try:
intval = ovfcheck_float_to_int(self.floatval)
if intval == self.floatval:
- return str(intval)
+ return unicode(str(intval))
except OverflowError:
pass
- res = str(self.floatval)
- if (res[-3] == '+' or res[-3] == '-') and res[-2] == '0':
+ res = unicode(str(self.floatval))
+ if (res[-3] == u'+' or res[-3] == u'-') and res[-2] == u'0':
cut = len(res) - 2
assert cut >= 0
res = res[:cut] + res[-1]
@@ -509,7 +511,7 @@
return r_uint(self.floatval)
def __repr__(self):
- return 'W_FloatNumber(%s)' % (self.floatval,)
+ return u'W_FloatNumber(%s)' % (self.floatval,)
class W_List(W_Root):
def __init__(self, list_w):
@@ -528,7 +530,7 @@
return self.list_w
def __repr__(self):
- return 'W_List(%s)' % (self.list_w,)
+ return u'W_List(%s)' % (self.list_w,)
class ExecutionContext(object):
def __init__(self, scope, this=None, variable=None,
@@ -546,12 +548,12 @@
self.debug = debug
if jsproperty is None:
#Attribute flags for new vars
- self.property = Property('',w_Undefined)
+ self.property = Property(u'',w_Undefined)
else:
self.property = jsproperty
def __str__(self):
- return "<ExCtx %s, var: %s>"%(self.scope, self.variable)
+ return u'<ExCtx %s, var: %s>' % (self.scope, self.variable)
def assign(self, name, value):
assert name is not None
@@ -601,21 +603,21 @@
assert isinstance(obj, W_PrimitiveObject)
if obj.HasProperty(identifier):
return obj.Get(ctx, identifier)
- raise ThrowException(W_String("ReferenceError: %s is not defined" % identifier))
+ raise ThrowException(W_String(u'ReferenceError: ' + identifier + u' is not defined'))
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, flags = DD))
+ jsproperty = Property(u'', w_Undefined, flags = DD))
return ctx
def function_context(scope, activation, this=None):
newscope = scope[:]
ctx = ExecutionContext(newscope,
this = this,
- jsproperty = Property('', w_Undefined, flags = DD))
+ jsproperty = Property(u'', w_Undefined, flags = DD))
ctx.push_object(activation)
return ctx
@@ -623,7 +625,7 @@
ctx = ExecutionContext(calling_context.scope[:],
this = calling_context.this,
variable = calling_context.variable,
- jsproperty = Property('', w_Undefined))
+ jsproperty = Property(u'', w_Undefined))
return ctx
def empty_context():
@@ -631,7 +633,7 @@
ctx = ExecutionContext([obj],
this = obj,
variable = obj,
- jsproperty = Property('', w_Undefined))
+ jsproperty = Property(u'', w_Undefined))
return ctx
class W_Iterator(W_Root):
@@ -646,7 +648,7 @@
return len(self.elements_w) == 0
def create_object(ctx, prototypename, callfunc=None, Value=w_Undefined):
- proto = ctx.get_global().Get(ctx, prototypename).Get(ctx, 'prototype')
+ proto = ctx.get_global().Get(ctx, prototypename).Get(ctx, u'prototype')
obj = W_Object(ctx, callfunc = callfunc,Prototype=proto,
Class = proto.Class, Value = Value)
return obj
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/operations.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/operations.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/operations.py Thu Jun 12 21:53:27 2008
@@ -109,7 +109,7 @@
def emit(self, bytecode):
self.expr.emit(bytecode)
if isinstance(self.lefthand, Identifier):
- bytecode.emit('LOAD_STRINGCONSTANT', self.lefthand.name)
+ bytecode.emit('LOAD_STRINGCONSTANT', unicode(self.lefthand.name))
else:
self.lefthand.emit(bytecode)
@@ -167,7 +167,7 @@
if self.right is not None:
self.right.emit(bytecode)
bytecode_name = 'STORE' + self._get_name()
- bytecode.emit_store(bytecode_name, self.identifier)
+ bytecode.emit_store(bytecode_name, unicode(self.identifier))
class VariableAssignment(Assignment):
def __init__(self, pos, left, right, operand):
@@ -180,7 +180,7 @@
def emit(self, bytecode):
self.right.emit(bytecode)
- bytecode.emit('STORE_VAR', self.depth, self.identifier)
+ bytecode.emit('STORE_VAR', self.depth, unicode(self.identifier))
class MemberAssignment(Assignment):
def __init__(self, pos, what, item, right, operand, prefix=''):
@@ -213,7 +213,7 @@
# XXX optimize this a bit
if self.right is not None:
self.right.emit(bytecode)
- bytecode.emit('LOAD_STRINGCONSTANT', self.itemname)
+ bytecode.emit('LOAD_STRINGCONSTANT', unicode(self.itemname))
self.what.emit(bytecode)
bytecode.emit_store_member('STORE_MEMBER' + self._get_name())
@@ -262,7 +262,7 @@
if isinstance(left, MemberDot):
left.left.emit(bytecode)
# XXX optimise
- bytecode.emit('LOAD_STRINGCONSTANT', left.name)
+ bytecode.emit('LOAD_STRINGCONSTANT', unicode(left.name))
bytecode.emit('CALL_METHOD')
elif isinstance(left, Member):
raise NotImplementedError
@@ -300,7 +300,7 @@
def emit(self, bytecode):
self.left.emit(bytecode)
- bytecode.emit('LOAD_MEMBER', self.name)
+ bytecode.emit('LOAD_MEMBER', unicode(self.name))
class FunctionStatement(Statement):
def __init__(self, pos, name, params, body):
@@ -310,13 +310,19 @@
else:
self.name = name.get_literal()
self.body = body
- self.params = params
+ self.params = [unicode(param) for param in params]
def emit(self, bytecode):
code = JsCode()
if self.body is not None:
self.body.emit(code)
- funcobj = JsFunction(self.name, self.params, code)
+
+ if self.name is None:
+ func_name = None
+ else:
+ func_name = unicode(self.name)
+
+ funcobj = JsFunction(func_name, self.params, code)
bytecode.emit('DECLARE_FUNCTION', funcobj)
if self.name is None:
bytecode.emit('LOAD_FUNCTION', funcobj)
@@ -331,7 +337,7 @@
self.name = name
def emit(self, bytecode):
- bytecode.emit('LOAD_VARIABLE', self.name)
+ bytecode.emit('LOAD_VARIABLE', unicode(self.name))
def get_literal(self):
return self.name
@@ -442,7 +448,7 @@
def emit(self, bytecode):
# obscure hack to be compatible
if isinstance(self.left, Identifier):
- bytecode.emit('TYPEOF_VARIABLE', self.left.name)
+ bytecode.emit('TYPEOF_VARIABLE', unicode(self.left.name))
else:
self.left.emit(bytecode)
bytecode.emit('TYPEOF')
@@ -455,13 +461,13 @@
def emit(self, bytecode):
what = self.what
if isinstance(what, Identifier):
- bytecode.emit('DELETE', what.name)
+ bytecode.emit('DELETE', unicode(what.name))
elif isinstance(what, VariableIdentifier):
- bytecode.emit('DELETE', what.identifier)
+ bytecode.emit('DELETE', unicode(what.identifier))
elif isinstance(what, MemberDot):
what.left.emit(bytecode)
# XXX optimize
- bytecode.emit('LOAD_STRINGCONSTANT', what.name)
+ bytecode.emit('LOAD_STRINGCONSTANT', unicode(what.name))
bytecode.emit('DELETE_MEMBER')
elif isinstance(what, Member):
what.left.emit(bytecode)
@@ -553,7 +559,7 @@
self.strval = self.string_unquote(strval)
def emit(self, bytecode):
- bytecode.emit('LOAD_STRINGCONSTANT', self.strval)
+ bytecode.emit('LOAD_STRINGCONSTANT', unicode(self.strval))
def string_unquote(self, string):
# XXX I don't think this works, it's very unlikely IMHO
@@ -601,7 +607,7 @@
def emit(self, bytecode):
for varname in self.var_decl:
- bytecode.emit('DECLARE_VAR', varname)
+ bytecode.emit('DECLARE_VAR', unicode(varname))
for funcname, funccode in self.func_decl.items():
funccode.emit(bytecode)
@@ -659,7 +665,7 @@
self.finallyblock.emit(finallycode)
else:
finallycode = None
- bytecode.emit('TRYCATCHBLOCK', trycode, self.catchparam.get_literal(),
+ bytecode.emit('TRYCATCHBLOCK', trycode, unicode(self.catchparam.get_literal()),
catchcode, finallycode)
class VariableDeclaration(Expression):
@@ -671,7 +677,7 @@
def emit(self, bytecode):
if self.expr is not None:
self.expr.emit(bytecode)
- bytecode.emit('STORE', self.identifier)
+ bytecode.emit('STORE', unicode(self.identifier))
class VariableIdentifier(Expression):
def __init__(self, pos, depth, identifier):
@@ -680,7 +686,7 @@
self.identifier = identifier
def emit(self, bytecode):
- bytecode.emit('LOAD_VARIABLE', self.identifier)
+ bytecode.emit('LOAD_VARIABLE', unicode(self.identifier))
def get_literal(self):
return self.identifier
@@ -729,7 +735,7 @@
self.body = body
def emit(self, bytecode):
- bytecode.emit('WITH_START', self.identifier)
+ bytecode.emit('WITH_START', unicode(self.identifier))
self.body.emit(bytecode)
bytecode.emit('WITH_END')
@@ -770,13 +776,13 @@
def emit(self, bytecode):
- bytecode.emit('DECLARE_VAR', self.iteratorname)
+ bytecode.emit('DECLARE_VAR', unicode(self.iteratorname))
self.object.emit(bytecode)
bytecode.emit('LOAD_ITERATOR')
precond = bytecode.emit_startloop_label()
finish = bytecode.prealocate_endloop_label()
bytecode.emit('JUMP_IF_ITERATOR_EMPTY', finish)
- bytecode.emit('NEXT_ITERATOR', self.iteratorname)
+ bytecode.emit('NEXT_ITERATOR', unicode(self.iteratorname))
self.body.emit(bytecode)
bytecode.emit('JUMP', precond)
bytecode.emit_endloop_label(finish)
@@ -796,7 +802,7 @@
precond = bytecode.emit_startloop_label()
finish = bytecode.prealocate_endloop_label()
bytecode.emit('JUMP_IF_ITERATOR_EMPTY', finish)
- bytecode.emit('NEXT_ITERATOR', self.iteratorname)
+ bytecode.emit('NEXT_ITERATOR', unicode(self.iteratorname))
self.body.emit(bytecode)
bytecode.emit('JUMP', precond)
bytecode.emit_endloop_label(finish)
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/ecma/conftest.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/ecma/conftest.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/ecma/conftest.py Thu Jun 12 21:53:27 2008
@@ -16,7 +16,7 @@
try:
return evaljs(ctx, args, this)
except JsBaseExcept:
- return W_String("error")
+ return W_String(u'error')
passing_tests = ['Number', 'Boolean']
Modified: pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/test_parser.py
==============================================================================
--- pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/test_parser.py (original)
+++ pypy/branch/js-refactoring-quickhacks/pypy/lang/js/test/test_parser.py Thu Jun 12 21:53:27 2008
@@ -451,7 +451,7 @@
def test_function_decl(self):
self.check('function f(x, y, z) {x;}',
- ['DECLARE_FUNCTION f [\'x\', \'y\', \'z\'] [\n LOAD_VARIABLE "x"\n POP\n]'])
+ ['DECLARE_FUNCTION f [u\'x\', u\'y\', u\'z\'] [\n LOAD_VARIABLE "x"\n POP\n]'])
def test_function_expression(self):
self.check('var x = function() {return x}',[
More information about the Pypy-commit
mailing list