[pypy-commit] lang-js default: fixes for translation
stepahn
noreply at buildbot.pypy.org
Fri Dec 28 11:34:51 CET 2012
Author: Stephan <stephan at stzal.com>
Branch:
Changeset: r269:867df8bc6bb9
Date: 2012-07-27 13:35 +0200
http://bitbucket.org/pypy/lang-js/changeset/867df8bc6bb9/
Log: fixes for translation
diff too long, truncating to 2000 out of 2307 lines
diff --git a/js/astbuilder.py b/js/astbuilder.py
--- a/js/astbuilder.py
+++ b/js/astbuilder.py
@@ -1,6 +1,7 @@
from pypy.rlib.rarithmetic import intmask, ovfcheck, ovfcheck_float_to_int
from pypy.rlib.parsing.tree import RPythonVisitor, Symbol, Nonterminal
from pypy.rlib.parsing.parsing import ParseError
+from pypy.rlib.objectmodel import enforceargs
from js import operations
from js.object_map import ROOT_MAP
@@ -207,15 +208,27 @@
def visit_HEXINTEGERLITERAL(self, node):
pos = self.get_pos(node)
- return operations.IntNumber(pos, int(node.additional_info, 16))
+ hexlit = node.additional_info
+ if hexlit.startswith('0x') or hexlit.startswith('0X'):
+ hexlit = hexlit[2:]
+ return operations.IntNumber(pos, int(hexlit, 16))
def visit_OCTALLITERAL(self, node):
pos = self.get_pos(node)
return operations.IntNumber(pos, int(node.additional_info, 8))
def string(self,node):
+ from operations import string_unquote
+ from runistr import unicode_unescape, decode_str_utf8
+
+ # TODO decode utf-8
pos = self.get_pos(node)
- return operations.String(pos, unicode(node.additional_info))
+ s = node.additional_info
+ strval = decode_str_utf8(s)
+ strval = string_unquote(strval)
+ strval = unicode_unescape(strval)
+
+ return operations.String(pos, strval)
visit_DOUBLESTRING = string
visit_SINGLESTRING = string
@@ -703,9 +716,12 @@
tree = builder.dispatch(parse_tree)
return tree
+ at enforceargs(unicode)
def parse_to_ast(code):
#assert isinstance(code, unicode)
from js.jsparser import parse, ParseError
- parse_tree = parse(str(code))
+ from runistr import encode_unicode_utf8
+ src = encode_unicode_utf8(code)
+ parse_tree = parse(src)
ast = parse_tree_to_ast(parse_tree)
return ast
diff --git a/js/builtins.py b/js/builtins.py
--- a/js/builtins.py
+++ b/js/builtins.py
@@ -110,7 +110,6 @@
# 15.3.4.3 Function.prototype.apply
put_intimate_function(w_FunctionPrototype, u'apply', function_builtins.js_apply)
- return
# 15.3.4.4 Function.prototype.call
put_intimate_function(w_FunctionPrototype, u'call', function_builtins.js_call)
diff --git a/js/builtins_array.py b/js/builtins_array.py
--- a/js/builtins_array.py
+++ b/js/builtins_array.py
@@ -1,5 +1,6 @@
from js.jsobj import isnull_or_undefined, _w, w_Undefined
from js.builtins import get_arg
+from js.object_space import w_return
def setup(global_object):
from js.builtins import put_property, put_native_function
@@ -23,18 +24,24 @@
# 15.4.4.2
put_native_function(w_ArrayPrototype, u'toString', to_string)
+
# 15.4.4.5
put_native_function(w_ArrayPrototype, u'join', join, params = [u'separator'])
+
# 15.4.4.6
put_native_function(w_ArrayPrototype, u'pop', pop)
+
# 15.4.4.7
put_native_function(w_ArrayPrototype, u'push', push)
+
# 15.4.4.8
put_native_function(w_ArrayPrototype, u'reverse', reverse)
+
# 15.4.4.11
put_native_function(w_ArrayPrototype, u'sort', sort)
# 15.4.4.7
+ at w_return
def push(this, args):
o = this.ToObject()
len_val = o.get(u'length')
@@ -42,7 +49,7 @@
for item in args:
e = item
- o.put(unicode(n), e, True)
+ o.put(unicode(str(n)), e, True)
n = n + 1
o.put(u'length', _w(n), True)
@@ -50,6 +57,7 @@
return n
# 15.4.4.2
+ at w_return
def to_string(this, args):
array = this.ToObject()
func = array.get(u'join')
@@ -59,6 +67,7 @@
return this.to_string()
# 15.4.4.5
+ at w_return
def join(this, args):
separator = get_arg(args, 0)
@@ -84,9 +93,9 @@
while(k < length):
s = r + sep
- element = o.get(unicode(k))
+ element = o.get(unicode(str(k)))
if isnull_or_undefined(element):
- _next = ''
+ _next = u''
else:
_next = element.to_string()
r = s + _next
@@ -95,6 +104,7 @@
return r
# 15.4.4.6
+ at w_return
def pop(this, args):
o = this.ToObject()
lenVal = o.get(u'length')
@@ -105,13 +115,14 @@
return w_Undefined
else:
indx = l - 1
- indxs = unicode(indx)
+ indxs = unicode(str(indx))
element = o.get(indxs)
o.delete(indxs, True)
o.put(u'length', _w(indx))
return element
# 15.4.4.8
+ at w_return
def reverse(this, args):
o = this.ToObject()
length = o.get(u'length').ToUInt32()
@@ -122,8 +133,8 @@
lower = 0
while lower != middle:
upper = length - lower - 1
- lower_p = unicode(lower)
- upper_p = unicode(upper)
+ lower_p = unicode(str(lower))
+ upper_p = unicode(str(upper))
lower_value = o.get(lower_p)
upper_value = o.get(upper_p)
lower_exists = o.has_property(lower_p)
@@ -142,6 +153,7 @@
lower = lower + 1
# 15.4.4.11
+ at w_return
def sort(this, args):
obj = this
length = this.get(u'length').ToUInt32()
@@ -154,8 +166,8 @@
while True:
swapped = False
for i in xrange(1, length):
- x = unicode(i - 1)
- y = unicode(i)
+ x = unicode(str(i - 1))
+ y = unicode(str(i))
comp = sort_compare(obj, x, y, comparefn)
if comp == 1:
tmp_x = obj.get(x)
@@ -193,6 +205,7 @@
if comparefn is not w_Undefined:
if not comparefn.is_callable():
+ from js.execution import JsTypeError
raise JsTypeError(u'')
res = comparefn.Call(args = [x, y], this = w_Undefined)
@@ -206,51 +219,3 @@
return 1
return 0
-
-#class W_ArraySort(W_NewBuiltin):
- #length = 1
- ##XXX: further optimize this function
- #def Call(self, args=[], this=None):
- #length = this.Get('length').ToUInt32()
-
- ## According to ECMA-262 15.4.4.11, non-existing properties always come after
- ## existing values. Undefined is always greater than any other value.
- ## So we create a list of non-undefined values, sort them, and append undefined again.
- #values = []
- #undefs = r_uint(0)
-
- #for i in range(length):
- #P = str(i)
- #if not this.HasProperty(P):
- ## non existing property
- #continue
- #obj = this.Get(str(i))
- #if obj is w_Undefined:
- #undefs += 1
- #continue
- #values.append(obj)
-
- ## sort all values
- #if len(args) > 0 and args[0] is not w_Undefined:
- #sorter = Sorter(values, compare_fn=args[0])
- #else:
- #sorter = Sorter(values)
- #sorter.sort()
-
- ## put sorted values back
- #values = sorter.list
- #for i in range(len(values)):
- #this.Put(str(i), values[i])
-
- ## append undefined values
- #newlength = len(values)
- #while undefs > 0:
- #undefs -= 1
- #this.Put(str(newlength), w_Undefined)
- #newlength += 1
-
- ## delete non-existing elements on the end
- #while length > newlength:
- #this.Delete(str(newlength))
- #newlength += 1
- #return this
diff --git a/js/builtins_boolean.py b/js/builtins_boolean.py
--- a/js/builtins_boolean.py
+++ b/js/builtins_boolean.py
@@ -1,6 +1,7 @@
from js.jsobj import W_Boolean, W_BooleanObject
from js.execution import JsTypeError
from js.jsobj import _w
+from js.object_space import w_return
def setup(global_object):
from js.builtins import put_property, put_native_function
@@ -35,6 +36,7 @@
put_native_function(w_BooleanPrototype, u'valueOf', value_of)
# 15.6.4.2
+ at w_return
def to_string(this, args):
if isinstance(this, W_Boolean):
b = this
@@ -44,11 +46,12 @@
raise JsTypeError(u'')
if b.to_boolean() == True:
- return 'true'
+ return u'true'
else:
- return 'false'
+ return u'false'
# 15.6.4.3
+ at w_return
def value_of(this, args):
if isinstance(this, W_Boolean):
b = this
diff --git a/js/builtins_date.py b/js/builtins_date.py
--- a/js/builtins_date.py
+++ b/js/builtins_date.py
@@ -1,85 +1,82 @@
from pypy.rlib.rfloat import NAN, isnan
+from js.jsobj import _w
import time
import datetime
from js.builtins import get_arg
+from js.object_space import w_return
def setup(global_object):
from js.builtins import put_property, put_native_function
- from js.builtins_number import w_NAN
- from js.jsobj import W_DateObject, W_DateConstructor, W__Object
+ from js.jsobj import W_DateObject, W_DateConstructor
from js.object_space import object_space
+
##Date
# 15.9.5
-
- w_DatePrototype = W_DateObject(w_NAN)
- object_space.assign_proto(w_DatePrototype, object_space.proto_object)
-
+ w_DatePrototype = W_DateObject(_w(NAN))
+ # TODO
+ #object_space.assign_proto(w_DatePrototype, object_space.proto_object)
object_space.proto_date = w_DatePrototype
- def putf(name, func):
- put_native_function(w_DatePrototype, name, func)
+ put_native_function(w_DatePrototype, u'toString', to_string)
- putf(u'toString', to_string)
+ put_native_function(w_DatePrototype, u'valueOf', value_of)
+ put_native_function(w_DatePrototype, u'getTime', get_time)
- putf(u'valueOf', value_of)
+ #put_native_function(w_DatePrototype, u'getFullYear', get_full_year)
+ #put_native_function(w_DatePrototype, u'getUTCFullYear', get_utc_full_year)
- putf(u'getTime', get_time)
+ #put_native_function(w_DatePrototype, u'getMonth', get_month)
+ #put_native_function(w_DatePrototype, u'getUTCMonth', get_utc_month)
- putf(u'getFullYear', get_full_year)
- putf(u'getUTCFullYear', get_utc_full_year)
+ #put_native_function(w_DatePrototype, u'getDate', get_date)
+ #put_native_function(w_DatePrototype, u'getUTCDate', get_utc_date)
- putf(u'getMonth', get_month)
- putf(u'getUTCMonth', get_utc_month)
+ #put_native_function(w_DatePrototype, u'getDay', get_day)
+ #put_native_function(w_DatePrototype, u'getUTCDay', get_utc_day)
- putf(u'getDate', get_date)
- putf(u'getUTCDate', get_utc_date)
+ #put_native_function(w_DatePrototype, u'getHours', get_hours)
+ #put_native_function(w_DatePrototype, u'getUTCHours', get_utc_hours)
- putf(u'getDay', get_day)
- putf(u'getUTCDay', get_utc_day)
+ #put_native_function(w_DatePrototype, u'getMinutes', get_minutes)
+ #put_native_function(w_DatePrototype, u'getUTCMinutes', get_utc_minutes)
- putf(u'getHours', get_hours)
- putf(u'getUTCHours', get_utc_hours)
+ #put_native_function(w_DatePrototype, u'getSeconds', get_seconds)
+ #put_native_function(w_DatePrototype, u'getUTCSeconds', get_utc_seconds)
- putf(u'getMinutes', get_minutes)
- putf(u'getUTCMinutes', get_utc_minutes)
+ #put_native_function(w_DatePrototype, u'getMilliseconds', get_milliseconds)
+ #put_native_function(w_DatePrototype, u'getUTCMilliseconds', get_utc_milliseconds)
- putf(u'getSeconds', get_seconds)
- putf(u'getUTCSeconds', get_utc_seconds)
+ #put_native_function(w_DatePrototype, u'getTimezoneOffset', get_timezone_offset)
- putf(u'getMilliseconds', get_milliseconds)
- putf(u'getUTCMilliseconds', get_utc_milliseconds)
+ #put_native_function(w_DatePrototype, u'setTime', set_time)
- putf(u'getTimezoneOffset', get_timezone_offset)
+ #put_native_function(w_DatePrototype, u'setMilliseconds', set_milliseconds)
+ #put_native_function(w_DatePrototype, u'setUTCMilliseconds', set_utc_milliseconds)
- putf(u'setTime', set_time)
+ #put_native_function(w_DatePrototype, u'setSeconds', set_seconds)
+ #put_native_function(w_DatePrototype, u'setUTCSeconds', set_utc_seconds)
- putf(u'setMilliseconds', set_milliseconds)
- putf(u'setUTCMilliseconds', set_utc_milliseconds)
+ #put_native_function(w_DatePrototype, u'setMinutes', set_minutes)
+ #put_native_function(w_DatePrototype, u'setUTCMinutes', set_utc_minutes)
- putf(u'setSeconds', set_seconds)
- putf(u'setUTCSeconds', set_utc_seconds)
+ #put_native_function(w_DatePrototype, u'setHours', set_hours)
+ #put_native_function(w_DatePrototype, u'setUTCHours', set_utc_hours)
- putf(u'setMinutes', set_minutes)
- putf(u'setUTCMinutes', set_utc_minutes)
+ #put_native_function(w_DatePrototype, u'setDate', set_date)
+ #put_native_function(w_DatePrototype, u'setUTCDate', set_utc_date)
- putf(u'setHours', set_hours)
- putf(u'setUTCHours', set_utc_hours)
+ #put_native_function(w_DatePrototype, u'setMonth', set_month)
+ #put_native_function(w_DatePrototype, u'setUTCMonth', set_utc_month)
- putf(u'setDate', set_date)
- putf(u'setUTCDate', set_utc_date)
+ #put_native_function(w_DatePrototype, u'setFullYear', set_full_year)
+ #put_native_function(w_DatePrototype, u'setUTCFullYear', set_utc_full_year)
- putf(u'setMonth', set_month)
- putf(u'setUTCMonth', set_utc_month)
+ #put_native_function(w_DatePrototype, u'getYear', get_year)
+ #put_native_function(w_DatePrototype, u'setYear', set_year)
- putf(u'setFullYear', set_full_year)
- putf(u'setUTCFullYear', set_utc_full_year)
-
- putf(u'getYear', get_year)
- putf(u'setYear', set_year)
-
- putf(u'toUTCString', to_utc_string)
- putf(u'toGMTString', to_gmt_string)
+ #put_native_function(w_DatePrototype, u'toUTCString', to_utc_string)
+ #put_native_function(w_DatePrototype, u'toGMTString', to_gmt_string)
# 15.9.3
w_Date = W_DateConstructor()
@@ -92,192 +89,228 @@
put_native_function(w_Date, u'UTC', parse)
+ at w_return
def to_string(this, args):
- d = w_date_to_datetime(this)
- local = to_local(d)
+ #d = w_date_to_datetime(this)
+ #local = to_local(d)
- s = local.strftime('%a %b %d %Y %H:%M:%S GMT%z (%Z)')
- return unicode(s)
+ #s = local.strftime('%a %b %d %Y %H:%M:%S GMT%z (%Z)')
+ return this.PrimitiveValue().to_string()
# 15.9.5.8
+ at w_return
def value_of(this, args):
return get_time(this, args)
# 15.9.5.9
+ at w_return
def get_time(this, args):
return this.PrimitiveValue()
# 15.9.5.10
+ at w_return
def get_full_year(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.year
# 15.9.5.11
+ at w_return
def get_utc_full_year(this, args):
d = w_date_to_datetime(this)
return d.year
# 15.9.5.12
+ at w_return
def get_month(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.month
# 15.9.5.13
+ at w_return
def get_utc_month(this, args):
d = w_date_to_datetime(this)
return d.day
# 15.9.5.14
+ at w_return
def get_date(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.day
# 15.9.5.15
+ at w_return
def get_utc_date(this, args):
d = w_date_to_datetime(this)
return d.day
# 15.9.5.16
+ at w_return
def get_day(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.weekday()
# 15.9.5.17
+ at w_return
def get_utc_day(this, args):
d = w_date_to_datetime(this)
return d.weekday()
# 15.9.5.18
+ at w_return
def get_hours(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.hour
# 15.9.5.19
+ at w_return
def get_utc_hours(this, args):
d = w_date_to_datetime(this)
return d.hour
# 15.9.5.20
+ at w_return
def get_minutes(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.minute
# 15.9.5.21
+ at w_return
def get_utc_minutes(this, args):
d = w_date_to_datetime(this)
return d.minute
# 15.9.5.22
+ at w_return
def get_seconds(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.second
# 15.9.5.23
+ at w_return
def get_utc_seconds(this, args):
d = w_date_to_datetime(this)
return d.second
# 15.9.5.24
+ at w_return
def get_milliseconds(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
return local.microsecond / 1000
# 15.9.5.25
+ at w_return
def get_utc_milliseconds(this, args):
d = w_date_to_datetime(this)
return d.microsecond / 1000
# 15.9.5.26
+ at w_return
def get_timezone_offset(this, args):
d = w_date_to_datetime(this)
offset = -1 * (d.utcoffset().total_seconds() / 60)
return offset
# 15.9.5.27
+ at w_return
def set_time(this, args):
arg0 = get_arg(args, 0)
this._primitive_value_ = arg0
return arg0
# 15.9.5.28
+ at w_return
def set_milliseconds(this, args):
time_args = to_timeargs(args, 1)
return set_datetime(this, time_args)
# 15.9.5.29
+ at w_return
def set_utc_milliseconds(this, args):
time_args = to_timeargs(args, 1)
return set_utc_datetime(this, time_args)
# 15.9.5.30
+ at w_return
def set_seconds(this, args):
time_args = to_timeargs(args, 2)
return set_datetime(this, time_args)
# 15.9.5.30
+ at w_return
def set_utc_seconds(this, args):
time_args = to_timeargs(args, 2)
return set_utc_datetime(this, time_args)
# 15.9.5.32
+ at w_return
def set_minutes(this, args):
time_args = to_timeargs(args, 3)
return set_datetime(this, time_args)
# 15.9.5.33
+ at w_return
def set_utc_minutes(this, args):
time_args = to_timeargs(args, 3)
return set_utc_datetime(this, time_args)
# 15.9.5.34
+ at w_return
def set_hours(this, args):
time_args = to_timeargs(args, 4)
return set_datetime(this, time_args)
# 15.9.5.35
+ at w_return
def set_utc_hours(this, args):
time_args = to_timeargs(args, 4)
return set_utc_datetime(this, time_args)
# 15.9.5.36
+ at w_return
def set_date(this, args):
date_args = to_dateargs(args, 1)
return set_datetime(this, date_args)
# 15.9.5.37
+ at w_return
def set_utc_date(this, args):
date_args = to_dateargs(args, 1)
return set_utc_datetime(this, date_args)
# 15.9.5.38
+ at w_return
def set_month(this, args):
date_args = to_dateargs(args, 2)
return set_datetime(this, date_args)
# 15.9.5.39
+ at w_return
def set_utc_month(this, args):
date_args = to_dateargs(args, 2)
return set_utc_datetime(this, date_args)
# 15.9.5.38
+ at w_return
def set_full_year(this, args):
date_args = to_dateargs(args, 3)
return set_datetime(this, date_args)
# 15.9.5.39
+ at w_return
def set_utc_full_year(this, args):
date_args = to_dateargs(args, 3)
return set_utc_datetime(this, date_args)
# B.2.4
+ at w_return
def get_year(this, args):
d = w_date_to_datetime(this)
local = to_local(d)
@@ -285,6 +318,7 @@
return y
# B.2.5
+ at w_return
def set_year(this, args):
arg0 = get_arg(args, 0)
year = arg0.ToInteger()
@@ -298,21 +332,24 @@
return set_datetime(this, [y])
# 15.9.5.42
+ at w_return
def to_utc_string(this, args):
- d = w_date_to_datetime(d)
+ d = w_date_to_datetime(this)
s = d.strftime('%c %z')
return s
# B.2.6
-
+ at w_return
def to_gmt_string(this, args):
return to_utc_string(this, args)
# 15.9.4.2
+ at w_return
def parse(this, args):
raise NotImplementedError()
# 15.9.4.3
+ at w_return
def utc(this, args):
raise NotImplementedError()
diff --git a/js/builtins_function.py b/js/builtins_function.py
--- a/js/builtins_function.py
+++ b/js/builtins_function.py
@@ -3,14 +3,17 @@
from js.jsobj import w_Undefined, _w, isnull_or_undefined
from js.builtins import get_arg
from js.completion import NormalCompletion
+from js.object_space import w_return
+ at w_return
def to_string(this, args):
from js.jsobj import W_BasicFunction
if not isinstance(this, W_BasicFunction):
raise JsTypeError(u'')
- return _w(this._to_string_())
+ return this._to_string_()
+ at w_return
def empty(this, args):
return w_Undefined
diff --git a/js/builtins_global.py b/js/builtins_global.py
--- a/js/builtins_global.py
+++ b/js/builtins_global.py
@@ -1,7 +1,11 @@
+# -*- coding: utf-8 -*-
+
from pypy.rlib.rfloat import NAN, INFINITY, isnan, isinf
from js.jsobj import W_String
from js.execution import JsTypeError
from js.builtins import get_arg
+from js.object_space import w_return
+from pypy.module.unicodedata import unicodedb
def setup(global_object):
from js.builtins import put_intimate_function, put_native_function, put_property
@@ -26,6 +30,7 @@
put_native_function(global_object, u'parseInt', parse_int, params = [u'string', u'radix'])
# 15.1.2.3
+ # TODO
put_native_function(global_object, u'parseFloat', parse_float, params = [u'string'])
# 15.1.2.4
@@ -39,6 +44,7 @@
put_native_function(global_object, u'print', printjs)
put_native_function(global_object, u'escape', escape, params = [u'string'])
+
put_native_function(global_object, u'unescape', unescape, params = [u'string'])
put_native_function(global_object, u'version', version)
@@ -49,12 +55,14 @@
put_native_function(global_object, u'inspect', inspect)
# 15.1.2.4
+ at w_return
def is_nan(this, args):
if len(args) < 1:
return True
return isnan(args[0].ToNumber())
# 15.1.2.5
+ at w_return
def is_finite(this, args):
if len(args) < 1:
return True
@@ -64,15 +72,44 @@
else:
return True
+def _isspace(uchar):
+ return unicodedb.isspace(ord(uchar))
+
+def _strip(unistr, left = True, right = True):
+ lpos = 0
+ rpos = len(unistr)
+
+ if left:
+ while lpos < rpos and _isspace(unistr[lpos]):
+ lpos += 1
+
+ if right:
+ while rpos > lpos and _isspace(unistr[rpos - 1]):
+ rpos -= 1
+
+ assert rpos >= 0
+ result = unistr[lpos: rpos]
+ return result
+
+def _lstrip(unistr):
+ return _strip(unistr, right = False)
+
+def _string_match_chars(string, chars):
+ for char in string:
+ c = unichr(unicodedb.tolower(ord(char)))
+ if c not in chars:
+ return False
+ return True
# 15.1.2.2
+ at w_return
def parse_int(this, args):
NUMERALS = u'0123456789abcdefghijklmnopqrstuvwxyz'
string = get_arg(args, 0)
radix = get_arg(args, 1)
input_string = string.to_string()
- s = input_string.lstrip()
+ s = _strip(input_string)
sign = 1
if s.startswith(u'-'):
@@ -82,6 +119,7 @@
r = radix.ToInt32()
strip_prefix = True
+
if r != 0:
if r < 2 or r > 36:
return NAN
@@ -90,68 +128,102 @@
else:
r = 10
+
if strip_prefix:
- 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')):
s = s[2:]
r = 16
# TODO this is not specified in ecma 5 but tests expect it and it's implemented in v8!
- elif len(s) > 1 and s.startswith('0'):
+ elif len(s) > 1 and s.startswith(u'0'):
r = 8
numerals = NUMERALS[:r]
- exp = r'[%s]+' % (numerals)
- import re
- match_data = re.match(exp, s, re.I)
- if match_data:
- z = match_data.group()
- else:
- z = ''
+ z = s
+ if not _string_match_chars(s, numerals):
+ z = u''
- if z == '':
+ if z == u'':
return NAN
try:
+ number = int(str(z), r)
try:
- number = int(float(int(z, r)))
- try:
- from pypy.rlib.rarithmetic import ovfcheck_float_to_int
- ovfcheck_float_to_int(number)
- except OverflowError:
- number = float(number)
+ from pypy.rlib.rarithmetic import ovfcheck_float_to_int
+ ovfcheck_float_to_int(number)
except OverflowError:
- number = INFINITY
+ number = float(number)
return sign * number
+ except OverflowError:
+ return INFINITY
except ValueError:
pass
return NAN
# 15.1.2.3
+ at w_return
def parse_float(this, args):
string = get_arg(args, 0)
input_string = string.to_string()
- trimmed_string = input_string.lstrip()
+ trimmed_string = _strip(input_string)
- import re
- match_data = re.match(r'(?:[+-]?((?:(?:\d+)(?:\.\d*)?)|Infinity|(?:\.[0-9]+))(?:[eE][\+\-]?[0-9]*)?)', trimmed_string)
- if match_data is not None:
- try:
- number_string = match_data.group()
- number = float(number_string)
- return number
- except ValueError:
- pass
+ try:
+ result = float(str(trimmed_string))
+ return result
+ except ValueError:
+ pass
return NAN
+ ## pypy/rlib/rsre
+ #import re
+ #match_data = re.match(r'(?:[+-]?((?:(?:\d+)(?:\.\d*)?)|Infinity|(?:\.[0-9]+))(?:[eE][\+\-]?[0-9]*)?)', trimmed_string)
+ #if match_data is not None:
+ # try:
+ # number_string = match_data.group()
+ # number = float(number_string)
+ # return number
+ # except ValueError:
+ # pass
+
+ #return NAN
+
+ at w_return
def alert(this, args):
- pass
+ printjs(this, args)
+ at w_return
def printjs(this, args):
- print ",".join([i.to_string() for i in args])
+ if len(args) == 0:
+ return
+
+ from pypy.rlib.rstring import UnicodeBuilder
+ from runistr import encode_unicode_utf8
+
+ builder = UnicodeBuilder()
+ for arg in args[:-1]:
+ builder.append(arg.to_string())
+ builder.append(u',')
+
+ builder.append(args[-1].to_string())
+
+ u_print_str = builder.build()
+ print_str = encode_unicode_utf8(u_print_str)
+ print(print_str)
+
+def hexing(i, length):
+ h = unicode(hex(i))
+ assert h.startswith('0x')
+ h = h[2:]
+
+ while(len(h) < length):
+ h = u'0' + h
+
+ return h
# B.2.1
+ at w_return
def escape(this, args):
CHARARCERS = u'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./'
string = get_arg(args, 0)
@@ -168,49 +240,47 @@
s = c
elif r6 < 256:
# step 11
- s = '%%%02X' % (r6)
+ s = u'%' + hexing(r6, 2)
else:
- s = '%%u%04X' % (r6)
+ s = u'%u' + hexing(r6, 4)
r += s
k += 1
return r
-
# B.2.2
+ at w_return
def unescape(this, args):
- import re
string = get_arg(args, 0)
r1 = string.to_string()
r2 = len(r1)
r = u''
k = 0
+ hexchars = u'0123456789abcdef'
while k != r2:
c = r1[k]
- if c == '%':
+ if c == u'%':
# 8. 9. 10.
- if (k > r2 - 6) or \
- (r1[k+1] != 'u') or \
- (not re.match(r'[0-9a-f]{4}', r1[k+2:k+6], re.I)):
+ if (k > r2 - 6) or (r1[k+1] != u'u') or (not len(r1) == 6 and _string_match_chars(r1[k+2:k+6], hexchars)):
# got step 14
if k > r2 - 3: # 14.
pass # goto step 18
else:
- if not re.match(r'[0-9a-f]{2}', r1[k+1:k+3], re.I): # 15.
+ if not _string_match_chars(r1[k+1:k+3], hexchars): # 15.
pass # goto step 18
else:
# 16
- hex_numeral = u'00%s' % (r1[k+1:k+3])
- number = int(hex_numeral, 16)
+ hex_numeral = u'00' + r1[k+1:k+3]
+ number = int(str(hex_numeral), 16)
c = unichr(number)
#17
k += 2
else:
# 11.
hex_numeral = r1[k+2:k+6]
- number = int(hex_numeral, 16)
+ number = int(str(hex_numeral), 16)
c = unichr(number)
# 12.
@@ -221,14 +291,16 @@
return r
-
+ at w_return
def pypy_repr(this, args):
o = args[0]
return unicode(o)
+ at w_return
def inspect(this, args):
pass
+ at w_return
def version(this, args):
return '1.0'
@@ -259,14 +331,17 @@
error = e.errorinformation.failure_reasons
error_lineno = e.source_pos.lineno
error_pos = e.source_pos.columnno
- raise JsSyntaxError(msg = error, src = src, line = error_lineno, column = error_pos)
+ #raise JsSyntaxError(msg = unicode(error), src = unicode(src), line = error_lineno, column = error_pos)
+ raise JsSyntaxError()
except FakeParseError, e:
- raise JsSyntaxError(msg = e.msg, src = src)
+ #raise JsSyntaxError(msg = unicode(e.msg), src = unicode(src))
+ raise JsSyntaxError()
except LexerError, e:
error_lineno = e.source_pos.lineno
error_pos = e.source_pos.columnno
error_msg = u'LexerError'
- raise JsSyntaxError(msg = error_msg, src = src, line = error_lineno, column = error_pos)
+ #raise JsSyntaxError(msg = error_msg, src = unicode(src), line = error_lineno, column = error_pos)
+ raise JsSyntaxError(msg = error_msg)
symbol_map = ast.symbol_map
code = ast_to_bytecode(ast, symbol_map)
diff --git a/js/builtins_interpreter.py b/js/builtins_interpreter.py
new file mode 100644
--- /dev/null
+++ b/js/builtins_interpreter.py
@@ -0,0 +1,39 @@
+from js.object_space import w_return
+
+def setup_builtins(global_object, overwrite_eval = False):
+ from js.builtins import put_native_function
+
+ #put_native_function(global_object, u'trace', js_trace)
+ put_native_function(global_object, u'load', js_load)
+ put_native_function(global_object, u'debug', js_debug)
+
+ if overwrite_eval is True:
+ from js.builtins import put_intimate_function
+ del(global_object._properties_[u'eval'])
+ put_intimate_function(global_object, u'eval', overriden_eval, configurable = False, params = [u'x'])
+
+ at w_return
+def js_load(this, args):
+ from js.object_space import object_space
+ filename = args[0].to_string()
+ object_space.interpreter.run_file(str(filename))
+
+ at w_return
+def js_trace(this, args):
+ import pdb; pdb.set_trace()
+
+ at w_return
+def js_debug(this, args):
+ from js.object_space import object_space
+ object_space.DEBUG = not object_space.DEBUG
+ return object_space.DEBUG
+
+def overriden_eval(ctx):
+ from js.builtins_global import js_eval
+ from js.execution import JsException
+ from js.completion import NormalCompletion
+ from js.jsobj import _w
+ try:
+ return js_eval(ctx)
+ except JsException:
+ return NormalCompletion(value = _w("error"))
diff --git a/js/builtins_math.py b/js/builtins_math.py
--- a/js/builtins_math.py
+++ b/js/builtins_math.py
@@ -3,6 +3,7 @@
from pypy.rlib.rfloat import NAN, INFINITY, isnan, isinf
from js.builtins import get_arg
+from js.object_space import w_return
def setup(global_object):
from js.builtins import put_native_function, put_property
@@ -13,10 +14,11 @@
object_space.assign_proto(w_Math)
put_property(global_object, u'Math', w_Math)
+
put_native_function(w_Math, u'abs', js_abs, params = [u'x'])
put_native_function(w_Math, u'floor', floor, params = [u'x'])
put_native_function(w_Math, u'round', js_round, params = [u'x'])
- put_native_function(w_Math, u'random', random)
+ put_native_function(w_Math, u'random', js_random)
put_native_function(w_Math, u'min', js_min, params = [u'value1', u'value2'])
put_native_function(w_Math, u'max', js_max, params = [u'value1', u'value2'])
put_native_function(w_Math, u'pow', js_pow, params = [u'x', u'y'])
@@ -59,6 +61,7 @@
put_property(w_Math, u'SQRT2', _w(SQRT2), writable = False, enumerable = False, configurable = False)
# 15.8.2.9
+ at w_return
def floor(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -69,6 +72,7 @@
return math.floor(x)
# 15.8.2.1
+ at w_return
def js_abs(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -78,7 +82,9 @@
return abs(x)
+
# 15.8.2.15
+ at w_return
def js_round(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -101,7 +107,8 @@
return math.floor(x + 0.5)
def isodd(i):
- return i % 2 == 1
+ import math
+ return math.fmod(i, 2.0) == 1.0
CMP_LT = -1
CMP_GT = 1
@@ -128,6 +135,7 @@
return cmp_signed_zero(a, b) is CMP_EQ
# 15.8.2.13
+ at w_return
def js_pow(this, args):
w_x = get_arg(args, 0)
w_y = get_arg(args, 1)
@@ -183,6 +191,7 @@
return INFINITY
# 15.8.2.17
+ at w_return
def js_sqrt(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -199,6 +208,7 @@
return math.sqrt(x)
# 15.8.2.10
+ at w_return
def js_log(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -218,6 +228,7 @@
return math.log(x)
# 15.8.2.11
+ at w_return
def js_min(this, args):
values = []
for arg in args:
@@ -226,16 +237,24 @@
return NAN
values.append(value)
- if not values:
+ if len(values) == 0:
return INFINITY
- result = min(values)
- if result == 0 and -0.0 in values:
- return -0.0
+ if len(values) == 1:
+ return values[0]
- return result
+ min_ = min(values[0], values[1])
+
+ for i in xrange(2, len(values)):
+ min_ = min(values[i], min_)
+
+ if min_ == 0 and -0.0 in values:
+ min_ = -0.0
+
+ return min_
# 15.8.2.12
+ at w_return
def js_max(this, args):
values = []
for arg in args:
@@ -244,12 +263,21 @@
return NAN
values.append(value)
- if not values:
+ if len(values) == 0:
return -INFINITY
- return max(values)
+ if len(values) == 1:
+ return values[0]
+
+ max_ = max(values[0], values[1])
+
+ for i in xrange(2, len(values)):
+ max_ = max(values[i], max_)
+
+ return max_
# 15.8.2.17
+ at w_return
def js_sin(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -263,6 +291,7 @@
return math.sin(x)
# 15.8.2.18
+ at w_return
def js_tan(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -276,6 +305,7 @@
return math.tan(x)
# 15.8.2.2
+ at w_return
def js_acos(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -289,6 +319,7 @@
return math.acos(x)
# 15.8.2.3
+ at w_return
def js_asin(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -302,6 +333,7 @@
return math.asin(x)
# 15.8.2.4
+ at w_return
def js_atan(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -318,6 +350,7 @@
return math.atan(x)
# 15.8.2.5
+ at w_return
def js_atan2(this, args):
arg0 = get_arg(args, 0)
arg1 = get_arg(args, 1)
@@ -330,6 +363,7 @@
return math.atan2(y, x)
# 15.8.2.6
+ at w_return
def js_ceil(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -346,6 +380,7 @@
return math.ceil(x)
# 15.8.2.7
+ at w_return
def js_cos(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -356,6 +391,7 @@
return math.cos(x)
# 15.8.2.8
+ at w_return
def js_exp(this, args):
arg0 = get_arg(args, 0)
x = arg0.ToNumber()
@@ -373,11 +409,12 @@
import time
from pypy.rlib import rrandom
-_random = rrandom.Random(int(time.time()))
+random = rrandom.Random(int(time.time()))
# 15.8.2.14
-def random(this, args):
- return _random.random()
+ at w_return
+def js_random(this, args):
+ return random.random()
# 15.8.1.1
E = math.e
diff --git a/js/builtins_number.py b/js/builtins_number.py
--- a/js/builtins_number.py
+++ b/js/builtins_number.py
@@ -1,6 +1,7 @@
from pypy.rlib.rfloat import NAN, INFINITY
from js.execution import JsRangeError, JsTypeError
from js.jsobj import W_Number, W_NumericObject, _w
+from js.object_space import w_return
def setup(global_object):
from js.builtins import put_property, put_native_function
@@ -15,9 +16,10 @@
# 15.7.3
put_property(w_Number, u'length', _w(1), writable = False, enumerable = False, configurable = False)
+
# 15.7.4
w_NumberPrototype = W_NumericObject(_w(0))
- object_space.assign_proto(W_NumericObject, object_space.proto_object)
+ object_space.assign_proto(w_NumberPrototype, object_space.proto_object)
object_space.proto_number = w_NumberPrototype
# 15.7.4.1
@@ -63,6 +65,7 @@
w_NEGATIVE_INFINITY = _w(-INFINITY)
# 15.7.4.2
+ at w_return
def to_string(this, args):
if len(args) > 0:
radix = args[0].ToInteger()
@@ -80,6 +83,7 @@
return num.to_string()
# 15.7.4.4
+ at w_return
def value_of(this, args):
if isinstance(this, W_Number):
num = this
diff --git a/js/builtins_string.py b/js/builtins_string.py
--- a/js/builtins_string.py
+++ b/js/builtins_string.py
@@ -2,6 +2,8 @@
from pypy.rlib.rfloat import NAN, INFINITY, isnan
from js.execution import ThrowException, JsTypeError
from js.builtins import get_arg
+from js.object_space import w_return
+from pypy.rlib.rstring import UnicodeBuilder
def setup(global_object):
from js.builtins import put_native_function, put_property
@@ -23,6 +25,7 @@
# 15.5.3.1
object_space.proto_string = w_StringPrototype
+
put_property(w_String, u'prototype', w_StringPrototype, writable = False, enumerable = False, configurable = False)
# 15.5.3.2
@@ -65,14 +68,20 @@
put_native_function(w_StringPrototype, u'toUpperCase', to_upper_case)
# 15.5.3.2
+ at w_return
def from_char_code(this, args):
- temp = []
+ builder = UnicodeBuilder(len(args))
+
for arg in args:
i = arg.ToInt16()
- temp.append(unichr(i))
- return u''.join(temp)
+ c = unichr(i)
+ builder.append(c)
+
+ s = builder.build()
+ return s
# 15.5.4.2
+ at w_return
def to_string(this, args):
if isinstance(this, W_String):
s = this
@@ -81,10 +90,10 @@
else:
raise JsTypeError(u'')
- assert isinstance(s, W_String)
return s.to_string()
# 15.5.4.3
+ at w_return
def value_of(this, args):
if isinstance(this, W_String):
s = this
@@ -97,6 +106,7 @@
return s
# 15.5.4.4
+ at w_return
def char_at(this, args):
pos = w_Undefined
@@ -115,6 +125,7 @@
return string[position]
#15.5.4.5
+ at w_return
def char_code_at(this, args):
pos = get_arg(args, 0)
@@ -130,6 +141,7 @@
return ord(char)
#15.5.4.6
+ at w_return
def concat(this, args):
string = this.to_string()
others = [obj.to_string() for obj in args]
@@ -137,10 +149,12 @@
return string
# 15.5.4.7
+ at w_return
def index_of(this, args):
string = this.to_string()
if len(args) < 1:
return -1
+
substr = args[0].to_string()
size = len(string)
subsize = len(substr)
@@ -148,11 +162,14 @@
pos = 0
else:
pos = args[1].ToInteger()
+
pos = int(min(max(pos, 0), size))
+
assert pos >= 0
return string.find(substr, pos)
# 15.5.4.8
+ at w_return
def last_index_of(this, args):
search_string = get_arg(args,0)
position = get_arg(args, 1)
@@ -175,15 +192,36 @@
search_len = len(search_str)
if isinf(start):
- return s.rfind(search_str)
+ idx = s.rfind(search_str)
+ return idx
- return s.rfind(search_str, 0, start + search_len)
+ end = int(start + search_len)
+ assert end >= 0
+ idx = s.rfind(search_str, 0, end)
+ return idx
+
+# pypy/rlib/rstring
+def _rsplit(value, by, maxsplit=-1):
+ bylen = len(by)
+ if bylen == 0:
+ raise ValueError("empty separator")
+
+ res = []
+ start = 0
+ while maxsplit != 0:
+ next = value.find(by, start)
+ if next < 0:
+ break
+ res.append(value[start:next])
+ start = next + bylen
+ maxsplit -= 1 # NB. if it's already < 0, it stays < 0
+
+ res.append(value[start:len(value)])
+ return res
# 15.5.4.14
+ at w_return
def split(this, args):
- from js.jsobj import W__Array, w_Null
- from js.jsobj import put_property
-
this.check_object_coercible()
separator = get_arg(args, 0, None)
@@ -200,43 +238,69 @@
if lim == 0 or separator is None:
return [string]
+
r = separator.to_string()
- if r == '':
- return list(string)
+ if r == u'':
+ i = 0
+ splitted = []
+ while i < len(string):
+ splitted += [string[i]]
+ i += 1
+ return splitted
else:
- splitted = string.split(r, lim)
+ splitted = _rsplit(string, r, lim)
return splitted
- return a
-
# 15.5.4.15
+ at w_return
def substring(this, args):
string = this.to_string()
size = len(string)
+
if len(args) < 1:
start = 0
else:
start = args[0].ToInteger()
+
if len(args) < 2:
end = size
else:
end = args[1].ToInteger()
+
tmp1 = min(max(start, 0), size)
tmp2 = min(max(end, 0), size)
start = min(tmp1, tmp2)
end = max(tmp1, tmp2)
start = int(start)
end = int(end)
+
+ assert start >= 0
+ assert end >= 0
return string[start:end]
# 15.5.4.16
+ at w_return
def to_lower_case(this, args):
+ from pypy.module.unicodedata import unicodedb
+
string = this.to_string()
- return string.lower()
+ builder = UnicodeBuilder(len(string))
+
+ for char in string:
+ builder.append(unichr(unicodedb.tolower(ord(char))))
+
+ return builder.build()
# 15.5.4.18
+ at w_return
def to_upper_case(this, args):
+ from pypy.module.unicodedata import unicodedb
+
string = this.to_string()
- return string.upper()
+ builder = UnicodeBuilder(len(string))
+ for char in string:
+ builder.append(unichr(unicodedb.toupper(ord(char))))
+
+ return builder.build()
diff --git a/js/environment_record.py b/js/environment_record.py
--- a/js/environment_record.py
+++ b/js/environment_record.py
@@ -68,7 +68,7 @@
if not identifier in self.bindings:
if strict:
from js.execution import JsReferenceError
- raise JsReferenceError
+ raise JsReferenceError(identifier)
else:
return w_Undefined
return self.bindings[identifier]
diff --git a/js/execution.py b/js/execution.py
--- a/js/execution.py
+++ b/js/execution.py
@@ -47,14 +47,14 @@
self.value = value
def _msg(self):
- return u'TypeError: %s' #% (self.value, )
+ return u'TypeError: ' + self.value #% (self.value, )
class JsReferenceError(JsException):
def __init__(self, identifier):
self.identifier = identifier
def _msg(self):
- return u'ReferenceError: %s is not defined' #% (self.identifier, )
+ return u'ReferenceError: '+ self.identifier +u' is not defined'
class JsRangeError(JsException):
def __init__(self, value = None):
@@ -71,7 +71,7 @@
self.column = column
def _msg(self):
- error_src = self.src.encode('unicode_escape')
+ error_src = self.src #self.src.encode('unicode_escape')
if self.error_msg:
return u'SyntaxError: "%s" in "%s" at line:%d, column:%d' #%(self.error_msg, error_src, self.line, self.column)
else:
diff --git a/js/execution_context.py b/js/execution_context.py
--- a/js/execution_context.py
+++ b/js/execution_context.py
@@ -138,6 +138,7 @@
self._variable_environment_ = calling_context.variable_environment()
self._lexical_environment_ = calling_context.lexical_environment()
if self._strict_:
+ from js.lexical_environment import DeclarativeEnvironment
strict_var_env = DeclarativeEnvironment(self._lexical_environment_)
self._variable_environment_ = strict_var_env
self._lexical_environment_ = strict_var_env
diff --git a/js/interpreter.py b/js/interpreter.py
--- a/js/interpreter.py
+++ b/js/interpreter.py
@@ -1,14 +1,14 @@
from pypy.rlib.objectmodel import we_are_translated
from pypy.rlib.streamio import open_file_as_stream
-import js.builtins
-
def load_file(filename):
from js.astbuilder import parse_to_ast
+ from runistr import decode_str_utf8
f = open_file_as_stream(str(filename))
src = f.readall()
- usrc = unicode(src)
+ usrc = decode_str_utf8(src)
+ assert usrc is not None
ast = parse_to_ast(usrc)
f.close()
return ast
@@ -18,37 +18,19 @@
def __init__(self):
from js.jsobj import W_GlobalObject
from js.object_space import object_space
- from js.builtins import setup_builtins
+ import js.builtins
+ import js.builtins_interpreter
self.global_object = W_GlobalObject()
object_space.global_object = self.global_object
+ object_space.interpreter = self
- setup_builtins(self.global_object)
- #self.setup_interpreter_builtins()
+ js.builtins.setup_builtins(self.global_object)
+ js.builtins_interpreter.setup_builtins(self.global_object, overwrite_eval = True)
+
object_space.assign_proto(self.global_object)
- def setup_interpreter_builtins(self):
- global_object = self.global_object
- from js.builtins import put_native_function
- def js_trace(this, args):
- import pdb; pdb.set_trace()
- put_native_function(global_object, u'trace', js_trace)
-
- interp = self
- def js_load(this, args):
- filename = args[0].to_string()
- interp.js_load(str(filename))
-
- put_native_function(global_object, u'load', js_load)
-
- def js_debug(this, args):
- import js.globals
- js.globals.DEBUG = not js.globals.DEBUG
- return js.globals.DEBUG
-
- put_native_function(global_object, u'debug', js_debug)
-
- def js_load(self, filename):
+ def run_file(self, filename):
ast = load_file(filename)
return self.run_ast(ast)
diff --git a/js/js_interactive.py b/js/js_interactive.py
--- a/js/js_interactive.py
+++ b/js/js_interactive.py
@@ -115,8 +115,8 @@
code.InteractiveConsole.interact(self, banner)
def main(inspect = False, debug = False, files=[]):
- import js.globals
- js.globals.DEBUG = debug
+ from js.object_space import object_space
+ object_space.DEBUG = debug
jsi = JSInterpreter()
for filename in files:
jsi.runcodefromfile(filename)
diff --git a/js/jscode.py b/js/jscode.py
--- a/js/jscode.py
+++ b/js/jscode.py
@@ -206,7 +206,8 @@
return self.opcodes[pc]
def run(self, ctx):
- from js.globals import DEBUG
+ from js.object_space import object_space
+ debug = object_space.DEBUG
from js.completion import NormalCompletion, is_completion, is_return_completion, is_empty_completion
from js.opcodes import RETURN, BaseJump
from js.jsobj import w_Undefined
@@ -216,7 +217,7 @@
if len(self.opcodes) == 0:
return NormalCompletion()
- if DEBUG:
+ if debug:
print('start running %s' % (str(self)))
pc = 0
@@ -227,8 +228,11 @@
opcode = self._get_opcode(pc)
result = opcode.eval(ctx)
- if DEBUG:
- print(u'%3d %25s %s %s' % (pc, str(opcode), unicode([unicode(s) for s in ctx._stack_]), str(result)))
+ if debug:
+ d = '%s\t%s' % (str(pc), str(opcode))
+ #d = u'%s' % (unicode(str(pc)))
+ #d = u'%3d %25s %s %s' % (pc, unicode(opcode), unicode([unicode(s) for s in ctx._stack_]), unicode(result))
+ print(d)
if is_return_completion(result):
break;
diff --git a/js/jsobj.py b/js/jsobj.py
--- a/js/jsobj.py
+++ b/js/jsobj.py
@@ -10,6 +10,14 @@
except ValueError:
return False
+def sign(i):
+ if i > 0:
+ return 1
+ if i < 0:
+ return -1
+ return 0
+
+
class W_Root(object):
_type_ = ''
@@ -57,21 +65,11 @@
return r_uint32(num)
def ToInt16(self):
- def sign(i):
- if i > 0:
- return 1
- if i < 0:
- return -1
+ num = self.ToInteger()
+ if num == NAN or num == INFINITY or num == -INFINITY or num == 0:
return 0
- num = self.ToInteger()
- if num == NAN or num == INFINITY or num == -INFINITY:
- return 0
-
- import math
- pos_int = sign(num) * math.floor(abs(num))
- int_16_bit = pos_int % math.pow(2, 16)
- return int(int_16_bit)
+ return r_uint16(num)
def is_callable(self):
return False
@@ -96,6 +94,9 @@
def check_object_coercible(self):
raise JsTypeError(u'W_Undefined.check_object_coercible')
+ def ToObject(self):
+ raise JsTypeError(u'W_Undefined.ToObject')
+
class W_Null(W_Primitive):
_type_ = 'null'
@@ -108,6 +109,9 @@
def check_object_coercible(self):
raise JsTypeError(u'W_Null.check_object_coercible')
+ def ToObject(self):
+ raise JsTypeError(u'W_Null.ToObject')
+
w_Undefined = W_Undefined()
w_Null = W_Null()
@@ -286,7 +290,7 @@
self._properties_ = {}
self._prototype_ = w_Null
desc = proto_desc
- #W_BasicObject.define_own_property(self, u'__proto__', desc)
+ W_BasicObject.define_own_property(self, u'__proto__', desc)
def __str__(self):
return "%s: %s" % (object.__repr__(self), self.klass())
@@ -655,6 +659,7 @@
class W_DateObject(W__PrimitiveObject):
_class_ = 'Date'
+
def default_value(self, hint = 'String'):
if hint is None:
hint = 'String'
@@ -690,7 +695,7 @@
return True
def _to_string_(self):
- return 'function() {}'
+ return u'function() {}'
# 15.3.5.3
def has_instance(self, v):
@@ -729,13 +734,16 @@
obj = object_space.new_obj()
return obj
+ def _to_string_(self):
+ return u'function Object() { [native code] }'
+
# TODO
def Construct(self, args=[]):
return self.Call(args, this=None)
class W_FunctionConstructor(W_BasicFunction):
def _to_string_(self):
- return "function Function() { [native code] }"
+ return u'function Function() { [native code] }'
# 15.3.2.1
def Call(self, args = [], this = None, calling_context = None):
@@ -827,35 +835,37 @@
# 15.9.2
class W_DateConstructor(W_BasicFunction):
- def Call(self, args=[], this=None):
+ def Call(self, args = [], this = None, calling_context = None):
from js.builtins import get_arg
import time
- import datetime
+ # TODO
+ #import datetime
- if len(args) > 1:
- arg0 = get_arg(args, 0);
- arg1 = get_arg(args, 1, _w(0));
- arg2 = get_arg(args, 2, _w(0));
+ #if len(args) > 1:
+ # arg0 = get_arg(args, 0);
+ # arg1 = get_arg(args, 1, _w(0));
+ # arg2 = get_arg(args, 2, _w(0));
- year = arg0.ToInteger()
- month = arg1.ToInteger() + 1
- day = arg2.ToInteger() + 1
+ # year = arg0.ToInteger()
+ # month = arg1.ToInteger() + 1
+ # day = arg2.ToInteger() + 1
- d = datetime.date(year, month, day)
- sec = time.mktime(d.timetuple())
- value = _w(int(sec * 1000))
+ # d = datetime.date(year, month, day)
+ # sec = time.mktime(d.timetuple())
+ # value = _w(int(sec * 1000))
- elif len(args) == 1:
- arg0 = get_arg(args, 0);
- if isinstance(arg0, W_String):
- raise NotImplementedError()
- else:
- num = arg0.ToNumber()
- if isnan(num) or isinf(num):
- raise JsTypeError(unicode(num))
- value = _w(int(num))
- else:
- value = _w(int(time.time() * 1000))
+ #elif len(args) == 1:
+ # arg0 = get_arg(args, 0);
+ # if isinstance(arg0, W_String):
+ # raise NotImplementedError()
+ # else:
+ # num = arg0.ToNumber()
+ # if isnan(num) or isinf(num):
+ # raise JsTypeError(unicode(num))
+ # value = _w(int(num))
+ #else:
+ # value = _w(int(time.time() * 1000))
+ value = _w(int(time.time() * 1000))
from js.object_space import object_space
obj = object_space.new_date(value)
@@ -1062,7 +1072,6 @@
_type_ = 'string'
def __init__(self, strval):
- #assert isinstance(strval, unicode)
assert strval is not None and isinstance(strval, unicode)
self._strval_ = strval
@@ -1164,6 +1173,9 @@
def r_uint32(n):
return intmask(rffi.cast(rffi.UINT, n))
+def r_uint16(n):
+ return intmask(rffi.cast(rffi.USHORT, n))
+
class W_FloatNumber(W_Number):
""" Number known to be a float
"""
@@ -1211,7 +1223,6 @@
return intmask(int(self._floatval_))
-
def isnull_or_undefined(obj):
if obj is w_Null or obj is w_Undefined:
return True
@@ -1373,7 +1384,7 @@
from js.object_space import object_space
a = object_space.new_array()
for index, item in enumerate(value):
- put_property(a, unicode(index), _w(item), writable = True, enumerable = True, configurable = True)
+ put_property(a, unicode(str(index)), _w(item), writable = True, enumerable = True, configurable = True)
return a
raise TypeError, ("ffffuuu %s" % (value,))
diff --git a/js/lexical_environment.py b/js/lexical_environment.py
--- a/js/lexical_environment.py
+++ b/js/lexical_environment.py
@@ -96,7 +96,7 @@
# 8.7.2
def put_value(v, w):
if not isinstance(v, Reference):
- raise JsReferenceError()
+ raise JsReferenceError('unresolvable reference')
if v.is_unresolvable_reference():
if v.is_strict_reference():
diff --git a/js/object_space.py b/js/object_space.py
--- a/js/object_space.py
+++ b/js/object_space.py
@@ -11,6 +11,8 @@
self.proto_array = w_Null
self.proto_date = w_Null
self.proto_object = w_Null
+ self.interpreter = None
+ self.DEBUG = False
def get_global_environment(self):
return self.global_context.variable_environment()
@@ -72,3 +74,9 @@
return obj
object_space = ObjectSpace()
+
+def w_return(fn):
+ def f(*args):
+ from js.jsobj import _w
+ return _w(fn(*args))
+ return f
diff --git a/js/operations.py b/js/operations.py
--- a/js/operations.py
+++ b/js/operations.py
@@ -9,8 +9,8 @@
w_Null, isnull_or_undefined
from pypy.rlib.parsing.ebnfparse import Symbol, Nonterminal
from js.execution import JsTypeError, ThrowException
-from constants import unescapedict
from pypy.rlib.unroll import unrolling_iterable
+from pypy.rlib.objectmodel import enforceargs
import sys
import os
@@ -310,14 +310,10 @@
class MemberDot(Expression):
"this is for object.name"
def __init__(self, pos, left, name):
More information about the pypy-commit
mailing list