Author: Stephan <[email protected]>
Branch: 
Changeset: r270:4ef704b2d955
Date: 2012-07-29 00:11 +0200
http://bitbucket.org/pypy/lang-js/changeset/4ef704b2d955/

Log:    wip

diff --git a/js/bench/v8/v1/run.js b/js/bench/v8/v1/run.js
--- a/js/bench/v8/v1/run.js
+++ b/js/bench/v8/v1/run.js
@@ -29,9 +29,9 @@
 load('base.js');
 load('looping.js');
 load('richards.js');
-load('deltablue.js');
+//load('deltablue.js');
 load('crypto.js');
-//load('raytrace.js');
+////load('raytrace.js');
 load('earley-boyer.js');
 
 
diff --git a/js/builtins_global.py b/js/builtins_global.py
--- a/js/builtins_global.py
+++ b/js/builtins_global.py
@@ -164,31 +164,31 @@
 # 15.1.2.3
 @w_return
 def parse_float(this, args):
+    from pypy.rlib.rsre import rsre_re as re
+    from runistr import encode_unicode_utf8
+
     string = get_arg(args, 0)
     input_string = string.to_string()
     trimmed_string = _strip(input_string)
+    str_trimmed_string = encode_unicode_utf8(trimmed_string)
+
+    number_string = str_trimmed_string
+
+    #rexp = 
r'(?:[+-]?((?:(?:\d+)(?:\.\d*)?)|Infinity|(?:\.[0-9]+))(?:[eE][\+\-]?[0-9]*)?)'
+    #match_data = re.match(rexp, str_trimmed_string)
+    #if match_data is not None:
+        #number_string = match_data.group()
+    #else:
+        #number_string = ''
 
     try:
-        result = float(str(trimmed_string))
-        return result
+        number = float(number_string)
+        return number
     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
-
 @w_return
 def alert(this, args):
     printjs(this, args)
@@ -213,8 +213,8 @@
     print(print_str)
 
 def hexing(i, length):
-    h = unicode(hex(i))
-    assert h.startswith('0x')
+    h = unicode(hex(i).upper())
+    assert h.startswith('0X')
     h = h[2:]
 
     while(len(h) < length):
diff --git a/js/js_interactive.py b/js/js_interactive.py
deleted file mode 100755
--- a/js/js_interactive.py
+++ /dev/null
@@ -1,145 +0,0 @@
-#!/usr/bin/env python
-# encoding: utf-8
-"""
-js_interactive.py
-"""
-
-import sys
-import getopt
-from js.interpreter import Interpreter, load_file
-from js.jsparser import parse, ParseError
-from js.jsobj import W_String, w_Undefined, W_Boolean
-from pypy.rlib.streamio import open_file_as_stream
-
-#sys.setrecursionlimit(100)
-
-import code
-sys.ps1 = 'js> '
-sys.ps2 = '... '
-
-try:
-    # Setup Readline
-    import readline
-    import os
-    histfile = os.path.join(os.environ["HOME"], ".jspypyhist")
-    try:
-        getattr(readline, "clear_history", lambda : None)()
-        readline.read_history_file(histfile)
-    except IOError:
-        pass
-    import atexit
-    atexit.register(readline.write_history_file, histfile)
-except ImportError:
-    pass
-
-
-def quitjs(this, args):
-    sys.exit(0)
-
-class JSInterpreter(code.InteractiveConsole):
-    def __init__(self, locals=None, filename="<console>"):
-        code.InteractiveConsole.__init__(self, locals, filename)
-        self.interpreter = Interpreter()
-        #ctx = self.interpreter.global_context
-        #from builtins import new_native_function
-        #self.interpreter.w_Global.Put('quit', new_native_function(ctx, 
quitjs))
-
-    def runcodefromfile(self, filename):
-        f = open_file_as_stream(filename)
-        self.runsource(f.readall(), filename)
-        f.close()
-
-    def runcode(self, ast):
-        """Run the javascript code in the AST. All exceptions raised
-        by javascript code must be caught and handled here. When an
-        exception occurs, self.showtraceback() is called to display a
-        traceback.
-        """
-        from js.execution import JsException
-        try:
-            res = self.interpreter.run_ast(ast)
-            try:
-                print res.to_string()
-            except JsException, exc:
-                self.showtraceback(exc)
-        except SystemExit:
-            raise
-        except JsException, exc:
-            self.showtraceback(exc)
-        else:
-            if code.softspace(sys.stdout, 0):
-                print
-
-    def runsource(self, source, filename="<input>"):
-        from js.astbuilder import parse_to_ast
-        """Parse and run source in the interpreter.
-
-        One of these cases can happen:
-        1) The input is incorrect. Prints a nice syntax error message.
-        2) The input in incomplete. More input is required. Returns None.
-        3) The input is complete. Executes the source code.
-        """
-        try:
-            ast = parse_to_ast(unicode(source))
-        except ParseError, exc:
-            if exc.source_pos.i == len(source):
-                # Case 2
-                return True # True means that more input is needed
-            else:
-                # Case 1
-                self.showsyntaxerror(filename, exc, source)
-                return False
-
-        # Case 3
-        self.runcode(ast)
-        return False
-
-    def showtraceback(self, exc):
-        # XXX format exceptions nicier
-        print exc._msg()
-
-    def showsyntaxerror(self, filename, exc, source):
-        # XXX format syntax errors nicier
-        marker_indent = ' ' * exc.source_pos.columnno
-        error = exc.errorinformation.failure_reasons
-        error_lineno = exc.source_pos.lineno
-        error_line = (source.splitlines())[error_lineno]
-        print 'Syntax Error in: %s:%d' % (filename, error_lineno)
-        print '%s' % (error_line)
-        print '%s^' %(marker_indent)
-        print 'Error: %s' %(error)
-
-    def interact(self, banner=None):
-        if banner is None:
-            banner = 'PyPy JavaScript Interpreter'
-        code.InteractiveConsole.interact(self, banner)
-
-def main(inspect = False, debug = False, files=[]):
-    from js.object_space import object_space
-    object_space.DEBUG = debug
-    jsi = JSInterpreter()
-    for filename in files:
-        jsi.runcodefromfile(filename)
-    if (not files) or inspect:
-        jsi.interact()
-
-if __name__ == '__main__':
-    from optparse import OptionParser
-    parser = OptionParser(usage='%prog [options] [files] ...',
-                          description='PyPy JavaScript Interpreter')
-    parser.add_option('-i', dest='inspect',
-                    action='store_true', default=False,
-                    help='inspect interactively after running script')
-
-    parser.add_option('-d', dest='debug',
-                    action='store_true', default=False,
-                    help='debug')
-
-    # ... (add other options)
-    opts, args = parser.parse_args()
-
-    if args:
-        main(inspect=opts.inspect, debug = opts.debug, files=args)
-    else:
-        main(inspect=opts.inspect, debug = opts.debug)
-    sys.exit(0)
diff --git a/js/jsobj.py b/js/jsobj.py
--- a/js/jsobj.py
+++ b/js/jsobj.py
@@ -1,12 +1,13 @@
 # encoding: utf-8
 from pypy.rpython.lltypesystem import rffi
-from pypy.rlib.rarithmetic import r_uint, intmask, ovfcheck_float_to_int
+from pypy.rlib.rarithmetic import intmask, ovfcheck_float_to_int
 from pypy.rlib.rfloat import isnan, isinf, NAN, formatd, INFINITY
 from js.execution import JsTypeError, JsRangeError, ReturnException
+from pypy.rlib.objectmodel import enforceargs
 
 def is_array_index(p):
     try:
-        return unicode(str(r_uint32(abs(int(p))))) == p
+        return unicode(str(uint32(abs(int(p))))) == p
     except ValueError:
         return False
 
@@ -17,7 +18,6 @@
         return -1
     return 0
 
-
 class W_Root(object):
     _type_ = ''
 
@@ -47,29 +47,30 @@
         if num == NAN:
             return 0
         if num == INFINITY or num == -INFINITY:
-            return num
+            raise Exception('dafuq?')
+            return 0
 
         return int(num)
 
     def ToInt32(self):
         num = self.ToInteger()
-        if num == NAN or num == INFINITY or num == -INFINITY:
-            return 0
+        #if num == NAN or num == INFINITY or num == -INFINITY:
+            #return 0
 
-        return r_int32(num)
+        return int32(num)
 
     def ToUInt32(self):
         num = self.ToInteger()
-        if num == NAN or num == INFINITY or num == -INFINITY:
-            return 0
-        return r_uint32(num)
+        #if num == NAN or num == INFINITY or num == -INFINITY:
+            #return 0
+        return uint32(num)
 
     def ToInt16(self):
         num = self.ToInteger()
-        if num == NAN or num == INFINITY or num == -INFINITY or num == 0:
-            return 0
+        #if num == NAN or num == INFINITY or num == -INFINITY or num == 0:
+            #return 0
 
-        return r_uint16(num)
+        return uint16(num)
 
     def is_callable(self):
         return False
@@ -1105,12 +1106,16 @@
             return 0.0
 
         strval = str(u_strval)
+        print(strval)
 
         try:
             return float(strval)
         except ValueError:
             try:
-                return float(int(strval, 16))
+                s = strval
+                if len(s) > 2 and (s.startswith('0x') or s.startswith('0X')):
+                  s = s[2:]
+                return float(int(s, 16))
             except ValueError:
                 try:
                     return float(int(strval, 8))
@@ -1167,14 +1172,25 @@
         # XXX incomplete, this doesn't follow the 9.8.1 recommendation
         return unicode(str(self.ToInteger()))
 
-def r_int32(n):
-    return intmask(rffi.cast(rffi.INT, n))
+MASK_32 = (2 ** 32) - 1
+MASK_16 = (2 ** 16) - 1
 
-def r_uint32(n):
-    return intmask(rffi.cast(rffi.UINT, n))
+@enforceargs(int)
+def int32(n):
+    if n & (1 << (32 - 1)):
+      res = n | ~MASK_32
+    else:
+      res = n & MASK_32
 
-def r_uint16(n):
-    return intmask(rffi.cast(rffi.USHORT, n))
+    return res
+
+@enforceargs(int)
+def uint32(n):
+    return n & MASK_32
+
+@enforceargs(int)
+def uint16(n):
+    return n & MASK_16
 
 class W_FloatNumber(W_Number):
     """ Number known to be a float
@@ -1219,7 +1235,7 @@
             return 0
 
         if self._floatval_ == 0 or isinf(self._floatval_):
-            return self._floatval_
+            return int(self._floatval_)
 
         return intmask(int(self._floatval_))
 
@@ -1341,7 +1357,7 @@
             assert p is not None and isinstance(p, unicode)
 
             # a
-            index = r_uint32(int(p))
+            index = uint32(int(p))
             # b
             if index >= old_len and old_len_desc.writable is False:
                 return reject(throw)
diff --git a/js/opcodes.py b/js/opcodes.py
--- a/js/opcodes.py
+++ b/js/opcodes.py
@@ -294,21 +294,40 @@
 
 class URSH(BaseBinaryBitwiseOp):
     def eval(self, ctx):
-        op2 = ctx.stack_pop().ToUInt32()
-        op1 = ctx.stack_pop().ToUInt32()
-        # XXX check if it could fit into int
-        f = float(op1 >> (op2 & 0x1F))
-        ctx.stack_append(W_FloatNumber(f))
+        rval = ctx.stack_pop()
+        lval = ctx.stack_pop()
+
+        rnum = rval.ToUInt32()
+        lnum = lval.ToUInt32()
+
+        from pypy.rlib.rarithmetic import ovfcheck_float_to_int
+
+        shift_count = rnum & 0x1F
+        res = lnum >> shift_count
+
+        try:
+            ovfcheck_float_to_int(res)
+            w_res = _w(res)
+        except OverflowError:
+            w_res = _w(float(res))
+
+        ctx.stack_append(w_res)
 
 class RSH(BaseBinaryBitwiseOp):
     def eval(self, ctx):
-        op2 = ctx.stack_pop().ToUInt32()
-        op1 = ctx.stack_pop().ToInt32()
-        ctx.stack_append(W_IntNumber(op1 >> intmask(op2 & 0x1F)))
+        rval = ctx.stack_pop()
+        lval = ctx.stack_pop()
+
+        rnum = rval.ToUInt32()
+        lnum = lval.ToInt32()
+        shift_count = rnum & 0x1F
+        res = lnum >> shift_count
+
+        ctx.stack_append(_w(res))
 
 class LSH(BaseBinaryBitwiseOp):
     def eval(self, ctx):
-        from js.jsobj import r_int32
+        from js.jsobj import int32
         rval = ctx.stack_pop()
         lval = ctx.stack_pop()
 
@@ -316,7 +335,7 @@
         rnum = rval.ToUInt32()
 
         shift_count = intmask(rnum & 0x1F)
-        res = r_int32(lnum << shift_count)
+        res = int32(lnum << shift_count)
 
         ctx.stack_append(_w(res))
 
diff --git a/js/targetjsstandalone.py b/js/targetjsstandalone.py
deleted file mode 100644
--- a/js/targetjsstandalone.py
+++ /dev/null
@@ -1,44 +0,0 @@
-"""
-A simple standalone target for the javascript interpreter.
-"""
-
-import sys
-from js.interpreter import Interpreter
-from js.execution import ExecutionReturned
-
-# __________  Entry point  __________
-
-
-def entry_point(argv):
-    debug = False
-
-    for i in xrange(len(argv)):
-        if argv[i] == '-d':
-            debug = True
-            del(argv[i])
-            break
-
-    if len(argv) == 2:
-        from js.object_space import object_space
-        object_space.DEBUG = debug
-        interp = Interpreter()
-        interp.run_file(argv[1])
-        return 0
-    elif argv[0] == 'foo':
-        raise ExecutionReturned(None)
-    else:
-        print "Usage: %s jsourcefile" % argv[0]
-        return 1
-
-# _____ Define and setup target ___
-
-def target(driver, args):
-    driver.exe_name = 'js-%(backend)s'
-    return entry_point, None
-
-def jitpolicy(driver):
-    from pypy.jit.codewriter.policy import JitPolicy
-    return JitPolicy()
-
-if __name__ == '__main__':
-    entry_point(sys.argv)
diff --git a/js/test/test_helpers.py b/js/test/test_helpers.py
--- a/js/test/test_helpers.py
+++ b/js/test/test_helpers.py
@@ -1,24 +1,5 @@
 import py
 
-def test_hexing():
-    from js.builtins_global import hexing
-    assert u'%02X' % 4 == hexing(4, 2)
-    assert u'%02X' % 8 == hexing(8, 2)
-    assert u'%02X' % 16 == hexing(16, 2)
-    assert u'%02X' % 32 == hexing(32, 2)
-    assert u'%02X' % 64 == hexing(64, 2)
-    assert u'%02X' % 128 == hexing(128, 2)
-    assert u'%02X' % 256 == hexing(256, 2)
-
-    assert u'%04X' % 4 == hexing(4, 4)
-    assert u'%04X' % 8 == hexing(8, 4)
-    assert u'%04X' % 16 == hexing(16, 4)
-    assert u'%04X' % 32 == hexing(32, 4)
-    assert u'%04X' % 64 == hexing(64, 4)
-    assert u'%04X' % 128 == hexing(128, 4)
-    assert u'%04X' % 256 == hexing(256, 4)
-    assert u'%04X' % 1024 == hexing(1024, 4)
-
 def test_string_match_chars():
     from js.builtins_global import _string_match_chars
     assert _string_match_chars(u'abccab', u'abc') is True
_______________________________________________
pypy-commit mailing list
[email protected]
http://mail.python.org/mailman/listinfo/pypy-commit

Reply via email to