[pypy-svn] r41851 - in pypy/dist/pypy/translator/js: . jssrc test

fijal at codespeak.net fijal at codespeak.net
Tue Apr 3 16:07:46 CEST 2007


Author: fijal
Date: Tue Apr  3 16:07:44 2007
New Revision: 41851

Added:
   pypy/dist/pypy/translator/js/test/test_str.py
Modified:
   pypy/dist/pypy/translator/js/_class.py
   pypy/dist/pypy/translator/js/function.py
   pypy/dist/pypy/translator/js/jsbuiltin.py
   pypy/dist/pypy/translator/js/jssrc/misc.js
   pypy/dist/pypy/translator/js/opcodes.py
   pypy/dist/pypy/translator/js/test/runtest.py
   pypy/dist/pypy/translator/js/test/test_rclass.py
   pypy/dist/pypy/translator/js/test/test_rpbc.py
   pypy/dist/pypy/translator/js/test/test_runtest.py
Log:
* A bit of wacking
* A bit of skipping
* bunch of new tests
* improved testing machinery
= we've got test_str, somehow working.


Modified: pypy/dist/pypy/translator/js/_class.py
==============================================================================
--- pypy/dist/pypy/translator/js/_class.py	(original)
+++ pypy/dist/pypy/translator/js/_class.py	Tue Apr  3 16:07:44 2007
@@ -11,6 +11,7 @@
         self.cts = db.genoo.TypeSystem(db)
         self.classdef = classdef
         self.name = classdef._name.replace('.', '_')#[-1]
+        self.real_name = classdef._name
 
         if not self.is_root(classdef):
             self.parent = self.db.pending_class(classdef._superclass)
@@ -50,7 +51,7 @@
         
         # begin to_String method
         ilasm.begin_method("toString", self.name, [])
-        ilasm.load_str("'<%s instance>'" % self.name)
+        ilasm.load_str("'<%s object>'" % self.real_name)
         ilasm.ret()
         ilasm.end_function()
 

Modified: pypy/dist/pypy/translator/js/function.py
==============================================================================
--- pypy/dist/pypy/translator/js/function.py	(original)
+++ pypy/dist/pypy/translator/js/function.py	Tue Apr  3 16:07:44 2007
@@ -28,6 +28,8 @@
                 self.ilasm.load_local(v)
         elif isinstance(v, flowmodel.Constant):
             self.db.load_const(v.concretetype, v.value, self.ilasm)
+        elif isinstance(v, str):
+            self.ilasm.load_const("'" + v + "'")
         else:
             assert False
 

Modified: pypy/dist/pypy/translator/js/jsbuiltin.py
==============================================================================
--- pypy/dist/pypy/translator/js/jsbuiltin.py	(original)
+++ pypy/dist/pypy/translator/js/jsbuiltin.py	Tue Apr  3 16:07:44 2007
@@ -42,8 +42,16 @@
                 'll_substring' : CallBuiltin('substring'),
                 'll_lower' : lambda g, op: Call._render_builtin_method(g, 'toLowerCase', [op.args[1]]),
                 'll_upper' : lambda g, op: Call._render_builtin_method(g, 'toUpperCase', [op.args[1]]),
-                'll_find' : lambda g, op: Call._render_builtin_method(g, 'search', [op.args[1], op.args[2]]),
-                'll_find_char' : lambda g, op: Call._render_builtin_method(g, 'search', [op.args[1], op.args[2]]),
+                'll_find' : CallBuiltin('findIndexOf'),
+                'll_find_char' : CallBuiltin('findIndexOf'),
+                #'ll_find' : lambda g, op: Call._render_builtin_method(g, 'indexOf', [op.args[1], op.args[2], op.args[3]]),
+                #'ll_find_char' : lambda g, op: Call._render_builtin_method(g, 'indexOf', [op.args[1], op.args[2], op.args[3]]),
+                'll_contains' : CallBuiltin('findIndexOfTrue'),
+                'll_replace_chr_chr' : lambda g, op:
+                     Call._render_builtin_method(g, 'replace',
+                     [op.args[1], op.args[2], op.args[3], 'g']),
+                'll_count_char' : CallBuiltin('countCharOf'),
+                'll_count' : CallBuiltin('countOf'),
             },
             ootype.List: {
                 'll_setitem_fast' : ListSetitem,

Modified: pypy/dist/pypy/translator/js/jssrc/misc.js
==============================================================================
--- pypy/dist/pypy/translator/js/jssrc/misc.js	(original)
+++ pypy/dist/pypy/translator/js/jssrc/misc.js	Tue Apr  3 16:07:44 2007
@@ -175,4 +175,46 @@
         delete(d[elem]);
     }
 }
+
+function findIndexOf(s1, s2, start, end) {
+    if (start > end || start > s1.length) {
+        return -1;
+    }
+    s1 = s1.substr(start, end-start);
+    res = s1.indexOf(s2);
+    if (res == -1) {
+        return -1;
+    }
+    return res + start;
+}
+
+function findIndexOfTrue(s1, s2) {
+    return findIndexOf(s1, s2, 0, s1.length) != -1;
+}
+
+function countCharOf(s, c, start, end) {
+    s = s.substring(start, end);
+    var i = 0;
+    for (c1 in s) {
+        if (s[c1] == c) {
+            i++;
+        }
+    }
+    return(i);
+}
+
+function countOf(s, s1, start, end) {
+    var ret = findIndexOf(s, s1, start, end);
+    var i = 0;
+    var lgt = 1;
+    if (s1.length > 0) {
+        lgt = s1.length;
+    }
+    while (ret != -1) {
+        i++;
+        ret = findIndexOf(s, s1, ret + lgt, end);
+    }
+    return (i);
+}
+    
 // ends hand written code

Modified: pypy/dist/pypy/translator/js/opcodes.py
==============================================================================
--- pypy/dist/pypy/translator/js/opcodes.py	(original)
+++ pypy/dist/pypy/translator/js/opcodes.py	Tue Apr  3 16:07:44 2007
@@ -130,6 +130,7 @@
     'oononnull'  : [PushAllArgs,_Prefix('!!')],
     'oostring'   : [PushArg(0),CastString],
     'ooparse_int' : [PushAllArgs,_CastFun("parseInt",2)],
+    'ooparse_float' : [PushAllArgs,_CastFun("parseFloat",1)],
     'oois'       : '===',
     # when casting from bool we want that every truth value is casted
     # to 1: we can't simply DoNothing, because the CLI stack could

Modified: pypy/dist/pypy/translator/js/test/runtest.py
==============================================================================
--- pypy/dist/pypy/translator/js/test/runtest.py	(original)
+++ pypy/dist/pypy/translator/js/test/runtest.py	Tue Apr  3 16:07:44 2007
@@ -1,6 +1,3 @@
-'''
-    Sests with DONT in front of them will probably not be fixed for the time being.
-'''
 
 import py, os, re, subprocess
 from pypy.translator.translator import TranslationContext
@@ -12,6 +9,7 @@
 from pypy.conftest import option
 from pypy.rpython.test.tool import BaseRtypingTest, OORtypeMixin
 from pypy.rlib.nonconst import NonConstant
+from pypy.rpython.ootypesystem import ootype
 
 from pypy.rpython.llinterp import LLException
 
@@ -21,6 +19,9 @@
 
 port = 8080
 
+class JSException(LLException):
+    pass
+
 def _CLI_is_on_path():
     if py.path.local.sysfind('js') is None:  #we recommend Spidermonkey
         return False
@@ -104,18 +105,22 @@
             input = "load(%r);\n" % self.js.filename.strpath
             for call in self.function_calls[:-1]:
                 input += "%s;\n" % call
-            input += "print(%s);\n" % self.function_calls[-1]
+            input += "print(\"'\" + %s + \"'\");\n" % self.function_calls[-1]
             js.stdin.write(input)
             stdout, stderr = js.communicate()
             output = (stderr + stdout).strip()
         for s in output.split('\n'):
             log(s)
 
-        return self.reinterpret(s)
+        m = re.match("'(.*)'", output, re.DOTALL)
+        if not m:
+            log("Error: %s" % output)
+            raise JSException(output)
+        return self.reinterpret(m.group(1))
 
     def reinterpret(cls, s):
-        while s.startswith(" "):
-            s = s[1:] # :-) quite inneficient, but who cares
+        #while s.startswith(" "):
+        #    s = s[1:] # :-) quite inneficient, but who cares
         if s == 'false':
             res = False
         elif s == 'true':
@@ -126,8 +131,6 @@
             res = 1e300 * 1e300
         elif s == 'NaN':
             res = (1e300 * 1e300) / (1e300 * 1e300)
-        elif s.startswith("uncaught exception:"):
-            raise LLException(str(s))
         elif s.startswith('[') or s.startswith('('):
             l = s[1:-1].split(',')
             res = [cls.reinterpret(i) for i in l]
@@ -144,6 +147,9 @@
 class JsTest(BaseRtypingTest, OORtypeMixin):
     def _compile(self, _fn, args, policy=None):
         argnames = _fn.func_code.co_varnames[:_fn.func_code.co_argcount]
+        func_name = _fn.func_name
+        if func_name == '<lambda>':
+            func_name = 'func'
         source = py.code.Source("""
         def %s():
             from pypy.rlib.nonconst import NonConstant
@@ -152,10 +158,13 @@
                 return None
             else:
                 return str(res)"""
-        % (_fn.func_name, ",".join(["%s=NonConstant(%s)" % (name,i) for
+        % (func_name, ",".join(["%s=NonConstant(%r)" % (name, i) for
                                    name, i in zip(argnames, args)])))
         exec source.compile() in locals()
-        return compile_function(locals()[_fn.func_name], [], policy=policy)
+        return compile_function(locals()[func_name], [], policy=policy)
+
+    def string_to_ll(self, s):
+        return s
     
     def interpret(self, fn, args, policy=None):
         f = self._compile(fn, args, policy)
@@ -168,7 +177,7 @@
         #import pdb; pdb.set_trace()
         try:
             res = self.interpret(fn, args)
-        except LLException, e:
+        except JSException, e:
             s = e.args[0]
             assert s.startswith('uncaught exception:')
             assert re.search(str(exception), s)
@@ -180,7 +189,7 @@
         #    assert False, 'function did raise no exception at all'
 
     def ll_to_string(self, s):
-        return s
+        return str(s)
 
     def ll_to_list(self, l):
         return l

Modified: pypy/dist/pypy/translator/js/test/test_rclass.py
==============================================================================
--- pypy/dist/pypy/translator/js/test/test_rclass.py	(original)
+++ pypy/dist/pypy/translator/js/test/test_rclass.py	Tue Apr  3 16:07:44 2007
@@ -73,11 +73,3 @@
     def test_isinstance(self):
         py.test.skip("WIP")
 
-#class TestJsPBC(JsTest, BaseTestRPBC):
-#    pass
-##
-#class TestJsRtuple(JsTest, BaseTestRtuple):
-#    pass
-##
-#class TestJsStr(JsTest, BaseTestRstr):
-#    pass

Modified: pypy/dist/pypy/translator/js/test/test_rpbc.py
==============================================================================
--- pypy/dist/pypy/translator/js/test/test_rpbc.py	(original)
+++ pypy/dist/pypy/translator/js/test/test_rpbc.py	Tue Apr  3 16:07:44 2007
@@ -35,5 +35,6 @@
     def test_conv_from_None(self):
         py.test.skip("WIP")
 
-
-
+    def test_multiple_ll_one_hl_op(self):
+        py.test.skip("XXX fix me soon")
+        

Modified: pypy/dist/pypy/translator/js/test/test_runtest.py
==============================================================================
--- pypy/dist/pypy/translator/js/test/test_runtest.py	(original)
+++ pypy/dist/pypy/translator/js/test/test_runtest.py	Tue Apr  3 16:07:44 2007
@@ -56,6 +56,12 @@
     assert rp('[a,b]') == ["a", "b"]
     #assert rp('(true,[a,b])') == [True, ["a", "b"]]
 
+def test_return_newline():
+    def fun_newline():
+        return "\n"
+    fun = compile_function(fun_newline, [])
+    assert fun() == "\n"
+
 ##def test_multiple_function():
 ##    def one():
 ##        return 1

Added: pypy/dist/pypy/translator/js/test/test_str.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/translator/js/test/test_str.py	Tue Apr  3 16:07:44 2007
@@ -0,0 +1,63 @@
+
+import py
+from pypy.translator.js.test.runtest import JsTest
+import pypy.translator.oosupport.test_template.string as oostring
+
+class TestJsString(JsTest, oostring.BaseTestString):
+    def test_unichar_const(self):
+        py.test.skip("Cannot test it yet")
+
+    def test_unichar_eq(self):
+        py.test.skip("Cannot test it yet")
+
+    def test_unichar_ord(self):
+        py.test.skip("Cannot test it yet")
+
+    def test_unichar_hash(self):
+        py.test.skip("Cannot test it yet")
+
+    def test_rfind(self):
+        py.test.skip("Not implemented")
+
+    def test_rfind_empty_string(self):
+        py.test.skip("Not implemented")
+
+    def test_find_char(self):
+        py.test.skip("Not implemented")
+
+    def test_strip(self):
+        py.test.skip("Not implemented")
+        
+    def test_upper(self):
+        #XXX Testing machinery is quite confused by js print
+        strings = ['', ' ', 'upper', 'UpPeR', ',uppEr,']
+        #for i in range(256):
+        #    if chr(i) != "\x00" and chr(i) != '(' and chr(i) != '[':
+        #        strings.append(chr(i))
+        def fn(i):
+            return strings[i].upper()
+        for i in range(len(strings)):
+            res = self.interpret(fn, [i])
+            assert self.ll_to_string(res) == fn(i)
+
+    def test_lower(self):
+        #XXX Testing machinery is quite confused by js print
+        strings = ['', ' ', 'lower', 'LoWeR', ',lowEr,']
+        #for i in range(256): strings.append(chr(i))
+        def fn(i):
+            return strings[i].lower()
+        for i in range(len(strings)):
+            res = self.interpret(fn, [i])
+            assert self.ll_to_string(res) == fn(i)
+
+    def test_strformat(self):
+        py.test.skip("string formatting not implemented for base different than 10")
+
+    def test_float(self):
+        py.test.skip("returning NaN instead of raising ValueError")
+
+    def test_hash(self):
+        py.test.skip("Not implemented")
+
+    def test_hash_value(self):
+        py.test.skip("Not implemented")



More information about the Pypy-commit mailing list