[pypy-svn] r48160 - in pypy/dist/pypy: lang/smalltalk lang/smalltalk/test translator/goal

cfbolz at codespeak.net cfbolz at codespeak.net
Mon Oct 29 16:43:04 CET 2007


Author: cfbolz
Date: Mon Oct 29 16:43:04 2007
New Revision: 48160

Added:
   pypy/dist/pypy/lang/smalltalk/error.py
   pypy/dist/pypy/lang/smalltalk/utility.py
Modified:
   pypy/dist/pypy/lang/smalltalk/model.py
   pypy/dist/pypy/lang/smalltalk/objtable.py
   pypy/dist/pypy/lang/smalltalk/primitives.py
   pypy/dist/pypy/lang/smalltalk/shadow.py
   pypy/dist/pypy/lang/smalltalk/squeakimage.py
   pypy/dist/pypy/lang/smalltalk/test/test_interpreter.py
   pypy/dist/pypy/lang/smalltalk/test/test_primitives.py
   pypy/dist/pypy/lang/smalltalk/test/test_shadow.py
   pypy/dist/pypy/translator/goal/targetfibsmalltalk.py
   pypy/dist/pypy/translator/goal/targetimageloadingmalltalk.py
Log:
put all the (un)wrap_* functions into a utility module


Added: pypy/dist/pypy/lang/smalltalk/error.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/lang/smalltalk/error.py	Mon Oct 29 16:43:04 2007
@@ -0,0 +1,17 @@
+# some exception classes for the Smalltalk VM
+
+class SmalltalkException(Exception):
+    """Base class for Smalltalk exception hierarchy"""
+
+class PrimitiveFailedError(SmalltalkException):
+    pass
+
+class PrimitiveNotYetWrittenError(PrimitiveFailedError):
+    pass
+
+class UnwrappingError(PrimitiveFailedError):
+    pass
+
+class WrappingError(PrimitiveFailedError):
+    pass
+

Modified: pypy/dist/pypy/lang/smalltalk/model.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/model.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/model.py	Mon Oct 29 16:43:04 2007
@@ -56,14 +56,6 @@
             return False
         return self.value == other.value
 
-class UnwrappingError(Exception):
-    pass
-
-def unwrap_int(w_value):
-    if isinstance(w_value, W_SmallInteger):
-        return w_value.value
-    raise UnwrappingError("expected a W_SmallInteger, got %s" % (w_value,))
-
 class W_Float(W_Object):
     def __init__(self, value):
         self.value = value
@@ -196,12 +188,12 @@
         self.bytes = ['\x00'] * size
 
     def at0(self, index0):
-        from pypy.lang.smalltalk import objtable
-        return objtable.wrap_int(ord(self.getchar(index0)))
+        from pypy.lang.smalltalk import utility
+        return utility.wrap_int(ord(self.getchar(index0)))
        
     def atput0(self, index0, w_value):
-        # XXX use to-be-written unwrap_char
-        self.setchar(index0, chr(unwrap_int(w_value)))
+        from pypy.lang.smalltalk import utility
+        self.setchar(index0, chr(utility.unwrap_int(w_value)))
 
     def getchar(self, n0):
         return self.bytes[n0]
@@ -241,11 +233,12 @@
         self.words = [0] * size
         
     def at0(self, index0):
-        from pypy.lang.smalltalk import objtable
-        return objtable.wrap_int(self.getword(index0))
+        from pypy.lang.smalltalk import utility
+        return utility.wrap_int(self.getword(index0))
        
     def atput0(self, index0, w_value):
-        self.setword(index0, unwrap_int(w_value))
+        from pypy.lang.smalltalk import utility
+        self.setword(index0, utility.unwrap_int(w_value))
 
     def getword(self, n):
         return self.words[n]
@@ -353,15 +346,16 @@
 
     def at0(self, index0):
         # XXX
-        from pypy.lang.smalltalk import objtable
+        from pypy.lang.smalltalk import utility
         index0 = index0 - self.staticsize()
         if index0 < 0:
             # XXX Do something useful with this.... we are not a block
             # of memory as smalltalk expects but wrapped in py-os
             raise NotImplementedError()
-        return objtable.wrap_int(ord(self.bytes[index0]))
+        return utility.wrap_int(ord(self.bytes[index0]))
         
     def atput0(self, index0, w_value):
+        from pypy.lang.smalltalk import utility
         index0 = index0 - self.staticsize()
         if index0 < 0:
             # XXX Do something useful with this.... we are not a block
@@ -369,7 +363,7 @@
             raise NotImplementedError()
         else:
             # XXX use to-be-written unwrap_char
-            self.setchar(index0, chr(unwrap_int(w_value)))
+            self.setchar(index0, chr(utility.unwrap_int(w_value)))
 
     def setchar(self, index0, character):
         self.bytes = (self.bytes[:index0] + character +
@@ -394,16 +388,16 @@
     # Imitate the primitive accessors
     
     def fetch(self, index):
-        from pypy.lang.smalltalk import objtable
+        from pypy.lang.smalltalk import utility, objtable
         if index == constants.CTXPART_SENDER_INDEX:
             if self.w_sender:
                 return self.w_sender
             else:
                 return objtable.w_nil
         elif index == constants.CTXPART_PC_INDEX:
-            return objtable.wrap_int(self.pc)
+            return utility.wrap_int(self.pc)
         elif index == constants.CTXPART_STACKP_INDEX:
-            return objtable.wrap_int(len(self.stack))
+            return utility.wrap_int(len(self.stack))
         
         # Invalid!
         raise IndexError
@@ -488,11 +482,11 @@
         return w_BlockContext
     
     def fetch(self, index):
-        from pypy.lang.smalltalk import objtable
+        from pypy.lang.smalltalk import utility
         if index == constants.BLKCTX_BLOCK_ARGUMENT_COUNT_INDEX:
-            return objtable.wrap_int(self.argcnt)
+            return utility.wrap_int(self.argcnt)
         elif index == constants.BLKCTX_INITIAL_IP_INDEX:
-            return objtable.wrap_int(self.initialip)
+            return utility.wrap_int(self.initialip)
         elif index == constants.BLKCTX_HOME_INDEX:
             return self.w_home
         elif index >= constants.BLKCTX_TEMP_FRAME_START:
@@ -504,10 +498,11 @@
     def store(self, index, value):
         # THIS IS ALL UNTESTED CODE and we're a bit unhappy about it
         # because it crashd the translation N+4 times :-(
+        from pypy.lang.smalltalk import utility
         if index == constants.BLKCTX_BLOCK_ARGUMENT_COUNT_INDEX:
-            self.argcnt = unwrap_int(value)
+            self.argcnt = utility.unwrap_int(value)
         elif index == constants.BLKCTX_INITIAL_IP_INDEX:
-            self.pc = unwrap_int(value)
+            self.pc = utility.unwrap_int(value)
         elif index == constants.BLKCTX_HOME_INDEX:
             assert isinstance(value, W_MethodContext)
             self.w_home = value

Modified: pypy/dist/pypy/lang/smalltalk/objtable.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/objtable.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/objtable.py	Mon Oct 29 16:43:04 2007
@@ -3,50 +3,6 @@
 from pypy.lang.smalltalk import model
 
 # ___________________________________________________________________________
-# Utility Methods
-
-def wrap_int(i):
-    if i <= 0x3FFFFFFF and i >= -0x40000000:
-        return model.W_SmallInteger(i)
-    raise NotImplementedError
-
-def wrap_float(i):
-    return model.W_Float(i)
-
-def wrap_string(string):
-    w_inst = classtable.w_String.as_class_get_shadow().new(len(string))
-    for i in range(len(string)):
-        w_inst.setchar(i, string[i])
-    return w_inst
-
-def wrap_char(c):
-    return CharacterTable[ord(c)]
-
-def ord_w_char(w_c):
-    assert w_c.getclass() is classtable.w_Character
-    w_ord = w_c.fetch(constants.CHARACTER_VALUE_INDEX)
-    assert w_ord.getclass() is classtable.w_SmallInteger
-    assert isinstance(w_ord, model.W_SmallInteger)
-    return w_ord.value
-
-def wrap_bool(bool):
-    if bool:
-        return w_true
-    else:
-        return w_false
-
-def wrap_list(lst_w_obj):
-    """
-    Converts a Python list of wrapper objects into
-    a wrapped smalltalk array
-    """
-    lstlen = len(lit)
-    res = classtable.w_Array.as_class_get_shadow().new(lstlen)
-    for i in range(lstlen):
-        res.storevarpointer(i, fakeliteral(lit[i]))
-    return res
-
-# ___________________________________________________________________________
 # Global Data
 
 def wrap_char_table():

Modified: pypy/dist/pypy/lang/smalltalk/primitives.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/primitives.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/primitives.py	Mon Oct 29 16:43:04 2007
@@ -1,18 +1,14 @@
 import inspect
 import math
 import operator
-from pypy.lang.smalltalk import model, shadow
+from pypy.lang.smalltalk import model, shadow, utility
 from pypy.lang.smalltalk import classtable
 from pypy.lang.smalltalk import objtable
 from pypy.lang.smalltalk import constants
+from pypy.lang.smalltalk.error import PrimitiveFailedError, \
+    PrimitiveNotYetWrittenError
 from pypy.rlib import rarithmetic
 
-class PrimitiveFailedError(Exception):
-    pass
-
-class PrimitiveNotYetWrittenError(PrimitiveFailedError):
-    pass
-
 def unwrap_float(w_v):
     if isinstance(w_v, model.W_Float): return w_v.value
     elif isinstance(w_v, model.W_SmallInteger): return float(w_v.value)
@@ -27,9 +23,9 @@
     if isinstance(w_obj, model.W_PointersObject):
         return w_obj.fetch(idx)
     elif isinstance(w_obj, model.W_WordsObject):
-        return objtable.wrap_int(w_obj.getword(idx))
+        return utility.wrap_int(w_obj.getword(idx))
     elif isinstance(w_obj, model.W_BytesObject):
-        return objtable.wrap_int(w_obj.getchar(idx))
+        return utility.wrap_int(w_obj.getchar(idx))
     raise PrimitiveFailedError()
 
 def assert_bounds(n0, minimum, maximum):
@@ -105,9 +101,9 @@
                     index = -len_unwrap_spec + i
                     w_arg = frame.stack[index]
                     if spec is int:
-                        args += (unwrap_int(w_arg), )
+                        args += (utility.unwrap_int(w_arg), )
                     elif spec is index1_0:
-                        args += (unwrap_int(w_arg)-1, )
+                        args += (utility.unwrap_int(w_arg)-1, )
                     elif spec is float:
                         args += (unwrap_float(w_arg), )
                     elif spec is object:
@@ -132,24 +128,7 @@
 # ___________________________________________________________________________
 # SmallInteger Primitives
 
-def unwrap_int(w_value):
-    if isinstance(w_value, model.W_SmallInteger): 
-        return w_value.value
-    raise PrimitiveFailedError()
-
-def unwrap_char(w_char):
-    if w_char.getclass() is not classtable.w_Character:
-        raise PrimitiveFailedError()
-    return chr(objtable.ord_w_char(w_char))
-
 
-def wrap_int(value):
-    if value > constants.TAGGED_MAXINT:
-        raise PrimitiveFailedError()
-    if value < constants.TAGGED_MININT:
-        raise PrimitiveFailedError()
-    return objtable.wrap_int(value)
-    
 ADD         = 1
 SUBTRACT    = 2
 MULTIPLY    = 9
@@ -175,7 +154,7 @@
                 res = rarithmetic.ovfcheck(op(receiver, argument))
             except OverflowError:
                 raise PrimitiveFailedError()
-            return wrap_int(res)
+            return utility.wrap_int(res)
     make_func(op)
 
 bitwise_binary_ops = {
@@ -188,7 +167,7 @@
         @expose_primitive(code, unwrap_spec=[int, int])
         def func(interp, receiver, argument):
             res = op(receiver, argument)
-            return wrap_int(res)
+            return utility.wrap_int(res)
     make_func(op)
 
 # #/ -- return the result of a division, only succeed if the division is exact
@@ -198,28 +177,28 @@
         raise PrimitiveFailedError()
     if receiver % argument != 0:
         raise PrimitiveFailedError()
-    return wrap_int(receiver // argument)
+    return utility.wrap_int(receiver // argument)
 
 # #\\ -- return the remainder of a division
 @expose_primitive(MOD, unwrap_spec=[int, int])
 def func(interp, receiver, argument):
     if argument == 0:
         raise PrimitiveFailedError()
-    return wrap_int(receiver % argument)
+    return utility.wrap_int(receiver % argument)
 
 # #// -- return the result of a division, rounded towards negative zero
 @expose_primitive(DIV, unwrap_spec=[int, int])
 def func(interp, receiver, argument):
     if argument == 0:
         raise PrimitiveFailedError()
-    return wrap_int(receiver // argument)
+    return utility.wrap_int(receiver // argument)
     
 # #// -- return the result of a division, rounded towards negative infinity
 @expose_primitive(QUO, unwrap_spec=[int, int])
 def func(interp, receiver, argument):
     if argument == 0:
         raise PrimitiveFailedError()
-    return wrap_int(receiver // argument)
+    return utility.wrap_int(receiver // argument)
     
 # #bitShift: -- return the shifted value
 @expose_primitive(BIT_SHIFT, unwrap_spec=[int, int])
@@ -230,11 +209,11 @@
         shifted = receiver << argument
         if (shifted >> argument) != receiver:
             raise PrimitiveFailedError()
-        return wrap_int(shifted)
+        return utility.wrap_int(shifted)
             
     # right shift, ok to lose bits
     else:
-        return wrap_int(receiver >> -argument)
+        return utility.wrap_int(receiver >> -argument)
    
 
 # ___________________________________________________________________________
@@ -265,35 +244,35 @@
     def make_func(op):
         @expose_primitive(code, unwrap_spec=[float, float])
         def func(interp, v1, v2):
-            w_res = objtable.wrap_float(op(v1, v2))
+            w_res = utility.wrap_float(op(v1, v2))
             return w_res
     make_func(op)
 
 @expose_primitive(FLOAT_TRUNCATED, unwrap_spec=[float])
 def func(interp, f): 
-    w_res = objtable.wrap_int(int(f))
+    w_res = utility.wrap_int(int(f))
     return w_res
 
 @expose_primitive(FLOAT_TIMES_TWO_POWER, unwrap_spec=[float, int])
 def func(interp, rcvr, arg): 
-    w_res = objtable.wrap_float(math.ldexp(rcvr, arg))
+    w_res = utility.wrap_float(math.ldexp(rcvr, arg))
     return w_res
 
 @expose_primitive(FLOAT_SQUARE_ROOT, unwrap_spec=[float])
 def func(interp, f): 
     if f < 0.0:
         raise PrimitiveFailedError
-    w_res = objtable.wrap_float(math.sqrt(f))
+    w_res = utility.wrap_float(math.sqrt(f))
     return w_res
 
 @expose_primitive(FLOAT_SIN, unwrap_spec=[float])
 def func(interp, f): 
-    w_res = objtable.wrap_float(math.sin(f))
+    w_res = utility.wrap_float(math.sin(f))
     return w_res
 
 @expose_primitive(FLOAT_ARCTAN, unwrap_spec=[float])
 def func(interp, f): 
-    w_res = objtable.wrap_float(math.atan(f))
+    w_res = utility.wrap_float(math.atan(f))
     return w_res
 
 @expose_primitive(FLOAT_LOG_N, unwrap_spec=[float])
@@ -304,11 +283,11 @@
         res = rarithmetic.NAN
     else:
         res = math.log(f)
-    return objtable.wrap_float(res)
+    return utility.wrap_float(res)
 
 @expose_primitive(FLOAT_EXP, unwrap_spec=[float])
 def func(interp, f): 
-    w_res = objtable.wrap_float(math.exp(f))
+    w_res = utility.wrap_float(math.exp(f))
     return w_res
 
 
@@ -329,17 +308,14 @@
 @expose_primitive(AT_PUT, unwrap_spec=[object, index1_0, object])
 def func(interp, w_obj, n0, w_val):
     n0 = assert_valid_index(n0, w_obj)
-    try:
-        w_obj.atput0(n0, w_val)
-        return w_val
-    except model.UnwrappingError:
-        raise PrimitiveFailedError()
+    w_obj.atput0(n0, w_val)
+    return w_val
 
 @expose_primitive(SIZE, unwrap_spec=[object])
 def func(interp, w_obj):
     if not w_obj.shadow_of_my_class().isvariable():
         raise PrimitiveFailedError()
-    return objtable.wrap_int(w_obj.varsize())
+    return utility.wrap_int(w_obj.varsize())
 
 @expose_primitive(STRING_AT, unwrap_spec=[object, index1_0])
 def func(interp, w_obj, n0):
@@ -348,11 +324,11 @@
     # make sure that getbyte is only performed on W_BytesObjects
     if not isinstance(w_obj, model.W_BytesObject):
         raise PrimitiveFailedError
-    return objtable.wrap_char(w_obj.getchar(n0))
+    return utility.wrap_char(w_obj.getchar(n0))
 
 @expose_primitive(STRING_AT_PUT, unwrap_spec=[object, index1_0, object])
 def func(interp, w_obj, n0, w_val):
-    val = unwrap_char(w_val)
+    val = utility.unwrap_char(w_val)
     n0 = assert_valid_index(n0, w_obj)
     w_obj.setchar(n0, val)
     return w_val
@@ -402,12 +378,11 @@
         raise PrimitiveFailedError()
     return shadow.new()
 
- at expose_primitive(NEW_WITH_ARG, unwrap_spec=[object, object])
-def func(interp, w_cls, w_size):
+ at expose_primitive(NEW_WITH_ARG, unwrap_spec=[object, int])
+def func(interp, w_cls, size):
     shadow = w_cls.as_class_get_shadow()
     if not shadow.isvariable():
         raise PrimitiveFailedError()
-    size = unwrap_int(w_size)
     return shadow.new(size)
 
 @expose_primitive(ARRAY_BECOME_ONE_WAY, unwrap_spec=[object, object])
@@ -437,7 +412,7 @@
 def func(interp, w_rcvr):
     if isinstance(w_rcvr, model.W_SmallInteger):
         raise PrimitiveFailedError()
-    return wrap_int(w_rcvr.gethash())
+    return utility.wrap_int(w_rcvr.gethash())
 
 @expose_primitive(STORE_STACKP, unwrap_spec=[object, object])
 def func(interp, w_obj1, w_obj2):
@@ -460,7 +435,8 @@
 
 @expose_primitive(NEW_METHOD, unwrap_spec=[object, int, object])
 def func(interp, w_class, bytecount, w_header):
-    header = unwrap_int(w_header)
+    # XXX untested
+    header = utility.unwrap_int(w_header)
     literalcount = ((header >> 10) & 255) + 1
     w_method = w_class.as_class_get_shadow().new(literalcount)
     # XXX not sure this is correct
@@ -483,7 +459,7 @@
 
 @expose_primitive(EQUIVALENT, unwrap_spec=[object, object])
 def func(interp, w_arg, w_rcvr):
-    return objtable.wrap_bool(w_arg.equals(w_rcvr))
+    return utility.wrap_bool(w_arg.equals(w_rcvr))
 
 @expose_primitive(CLASS, unwrap_spec=[object])
 def func(interp, w_obj):
@@ -535,7 +511,7 @@
 INC_GC = 131
 
 def fake_bytes_left():
-    return wrap_int(2**20) # XXX we don't know how to do this :-(
+    return utility.wrap_int(2**20) # XXX we don't know how to do this :-(
 
 @expose_primitive(INC_GC, unwrap_spec=[object])
 @expose_primitive(FULL_GC, unwrap_spec=[object])
@@ -553,13 +529,13 @@
 def func(interp, w_arg):
     import time
     import math
-    return wrap_int(int(math.fmod(time.time()*1000, constants.TAGGED_MAXINT/2)))
+    return utility.wrap_int(int(math.fmod(time.time()*1000, constants.TAGGED_MAXINT/2)))
 
 @expose_primitive(SECONDS_CLOCK, unwrap_spec=[object])
 def func(interp, w_arg):
     import time
-    return wrap_int(0x23910d6c)      # HACK: too big for a small int!
-    #return wrap_int(int(time.time()))
+    return utility.wrap_int(0x23910d6c)      # HACK: too big for a small int!
+    #return utility.wrap_int(int(time.time()))
 
 # ___________________________________________________________________________
 # Boolean Primitives
@@ -591,7 +567,7 @@
         @expose_primitive(code, unwrap_spec=[int, int])
         def func(interp, v1, v2):
             res = op(v1, v2)
-            w_res = objtable.wrap_bool(res)
+            w_res = utility.wrap_bool(res)
             return w_res
     make_func(op)
 
@@ -600,7 +576,7 @@
         @expose_primitive(code+_FLOAT_OFFSET, unwrap_spec=[float, float])
         def func(interp, v1, v2):
             res = op(v1, v2)
-            w_res = objtable.wrap_bool(res)
+            w_res = utility.wrap_bool(res)
             return w_res
     make_func(op)
     
@@ -650,10 +626,9 @@
 PRIMITIVE_SUSPEND = 88
 PRIMITIVE_FLUSH_CACHE = 89
 
- at expose_primitive(PRIMITIVE_BLOCK_COPY, unwrap_spec=[object, object])
-def func(interp, w_context, w_argcnt):
+ at expose_primitive(PRIMITIVE_BLOCK_COPY, unwrap_spec=[object, int])
+def func(interp, w_context, argcnt):
     frame = interp.w_active_context
-    argcnt = unwrap_int(w_argcnt)
 
     # From B.B.: If receiver is a MethodContext, then it becomes
     # the new BlockContext's home context.  Otherwise, the home

Modified: pypy/dist/pypy/lang/smalltalk/shadow.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/shadow.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/shadow.py	Mon Oct 29 16:43:04 2007
@@ -1,5 +1,5 @@
 import weakref
-from pypy.lang.smalltalk import model, constants
+from pypy.lang.smalltalk import model, constants, utility, error
 
 class AbstractShadow(object):
     """A shadow is an optional extra bit of information that
@@ -17,12 +17,11 @@
 WEAK_POINTERS = 3
 COMPILED_METHOD = 4
 
-unwrap_int = model.unwrap_int
 
-class MethodNotFound(Exception):
+class MethodNotFound(error.SmalltalkException):
     pass
 
-class ClassShadowError(Exception):
+class ClassShadowError(error.SmalltalkException):
     pass
 
 class ClassShadow(AbstractShadow):
@@ -49,7 +48,8 @@
 
         w_self = self.w_self
         # read and painfully decode the format
-        classformat = unwrap_int(w_self.fetch(constants.CLASS_FORMAT_INDEX))
+        classformat = utility.unwrap_int(
+            w_self.fetch(constants.CLASS_FORMAT_INDEX))
         # The classformat in Squeak, as an integer value, is:
         #    <2 bits=instSize//64><5 bits=cClass><4 bits=instSpec>
         #                                    <6 bits=instSize\\64><1 bit=0>

Modified: pypy/dist/pypy/lang/smalltalk/squeakimage.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/squeakimage.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/squeakimage.py	Mon Oct 29 16:43:04 2007
@@ -1,7 +1,7 @@
 import py
 import os
 from pypy.lang.smalltalk import model
-from pypy.lang.smalltalk import objtable
+from pypy.lang.smalltalk import objtable, utility
 from pypy.rlib import objectmodel
 from pypy.lang.smalltalk.tool.bitmanipulation import splitter
 
@@ -225,7 +225,7 @@
         self.owner = reader
         self.value = value
         self.size = -1
-        self.w_object = objtable.wrap_int(value)
+        self.w_object = utility.wrap_int(value)
 
     def initialize(self, chunk, reader):
         self.owner = reader

Modified: pypy/dist/pypy/lang/smalltalk/test/test_interpreter.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/test/test_interpreter.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/test/test_interpreter.py	Mon Oct 29 16:43:04 2007
@@ -1,7 +1,8 @@
 import py
 from pypy.lang.smalltalk import model, interpreter, primitives, shadow
-from pypy.lang.smalltalk import objtable, classtable
-from pypy.lang.smalltalk.objtable import wrap_int, wrap_char
+from pypy.lang.smalltalk import objtable, classtable, utility
+from pypy.lang.smalltalk.utility import wrap_int, wrap_char, wrap_string, \
+    unwrap_int
 
 mockclass = classtable.bootstrap_class
 
@@ -45,7 +46,7 @@
     try:
         return _cache[s]
     except KeyError:
-        result = _cache[s] = objtable.wrap_string(s)
+        result = _cache[s] = wrap_string(s)
         return result
 
 def fakeliterals(*literals):
@@ -209,7 +210,7 @@
 def test_pushConstantMinusOneBytecode():
     interp = new_interpreter(pushConstantMinusOneBytecode)
     interp.step()
-    assert interp.w_active_context.pop() == interp.MONE
+    assert interp.w_active_context.pop() == interp.MINUS_ONE
     assert interp.w_active_context.stack == []
 
 def test_pushConstantZeroBytecode():
@@ -403,7 +404,7 @@
     interp.w_active_context.push(w_object)
     interp.w_active_context.push(wrap_int(8))
     result = interp.interpret()
-    assert primitives.unwrap_int(result) == 34
+    assert unwrap_int(result) == 34
 
 def test_send_to_primitive():
 
@@ -417,7 +418,7 @@
         assert interp.w_active_context is callerContext
         assert len(interp.w_active_context.stack) == 1
         w_result = interp.w_active_context.pop()
-        assert primitives.unwrap_int(w_result) == 42
+        assert unwrap_int(w_result) == 42
         
     run_with_faked_methods(
         [[classtable.w_SmallInteger, primitives.SUBTRACT,
@@ -720,10 +721,10 @@
     w_fakeinst.store(0, wrap_char("a")) # static slot 0: instance variable
     w_fakeinst.store(1, wrap_char("b")) # varying slot 1
     def test():
-        assert objtable.ord_w_char(interpret_bc(
+        assert utility.unwrap_char(interpret_bc(
             [112, 118, 192, 124],
             fakeliterals(),
-            receiver=w_fakeinst)) == ord("b")
+            receiver=w_fakeinst)) == "b"
     run_with_faked_methods(
         [[w_fakeclass, primitives.AT, 1, "at:"]],
         test)
@@ -735,12 +736,12 @@
     w_fakeinst.store(0, wrap_char("a")) # static slot 0: instance variable
     w_fakeinst.store(1, wrap_char("a")) # varying slot 1
     def test():
-        assert objtable.ord_w_char(interpret_bc(
+        assert utility.unwrap_char(interpret_bc(
             [0x70, 0x76, 0x20, 0xc1, 0x7c],
             fakeliterals(wrap_char("b")),
-            receiver=w_fakeinst)) == ord("b")
-        assert objtable.ord_w_char(w_fakeinst.fetch(0)) == ord("a")
-        assert objtable.ord_w_char(w_fakeinst.fetch(1)) == ord("b")
+            receiver=w_fakeinst)) == "b"
+        assert utility.unwrap_char(w_fakeinst.fetch(0)) == "a"
+        assert utility.unwrap_char(w_fakeinst.fetch(1)) == "b"
     run_with_faked_methods(
         [[w_fakeclass, primitives.AT_PUT, 2, "at:put:"]],
         test)

Modified: pypy/dist/pypy/lang/smalltalk/test/test_primitives.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/test/test_primitives.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/test/test_primitives.py	Mon Oct 29 16:43:04 2007
@@ -2,10 +2,8 @@
 import math
 from pypy.lang.smalltalk.primitives import prim_table, PrimitiveFailedError
 from pypy.lang.smalltalk import model, shadow
-from pypy.lang.smalltalk import interpreter
-from pypy.lang.smalltalk import classtable
-from pypy.lang.smalltalk import objtable
-from pypy.lang.smalltalk import constants
+from pypy.lang.smalltalk import interpreter, utility
+from pypy.lang.smalltalk import classtable, objtable, constants
 from pypy.rlib.rarithmetic import INFINITY, NAN, isinf, isnan
 from pypy.lang.smalltalk import primitives
 
@@ -16,11 +14,11 @@
         self.stack = stack
 
 def wrap(x):
-    if isinstance(x, int): return objtable.wrap_int(x)
-    if isinstance(x, float): return objtable.wrap_float(x)
+    if isinstance(x, int): return utility.wrap_int(x)
+    if isinstance(x, float): return utility.wrap_float(x)
     if isinstance(x, model.W_Object): return x
-    if isinstance(x, str) and len(x) == 1: return objtable.wrap_char(x)
-    if isinstance(x, str): return objtable.wrap_string(x)
+    if isinstance(x, str) and len(x) == 1: return utility.wrap_char(x)
+    if isinstance(x, str): return utility.wrap_string(x)
     raise NotImplementedError
     
 def mock(stack):

Modified: pypy/dist/pypy/lang/smalltalk/test/test_shadow.py
==============================================================================
--- pypy/dist/pypy/lang/smalltalk/test/test_shadow.py	(original)
+++ pypy/dist/pypy/lang/smalltalk/test/test_shadow.py	Mon Oct 29 16:43:04 2007
@@ -1,5 +1,6 @@
 import random
 from pypy.lang.smalltalk import model, shadow, classtable, constants, objtable
+from pypy.lang.smalltalk import utility
 
 w_Object = classtable.classtable['w_Object']
 w_Metaclass  = classtable.classtable['w_Metaclass']
@@ -13,14 +14,14 @@
     for i in range(size):
         w_array.store(i, objtable.w_nil)
         w_methoddict.store(constants.METHODDICT_NAMES_INDEX+i, objtable.w_nil)
-    w_tally = objtable.wrap_int(len(methods))
+    w_tally = utility.wrap_int(len(methods))
     w_methoddict.store(constants.METHODDICT_TALLY_INDEX, w_tally)
     w_methoddict.store(constants.METHODDICT_VALUES_INDEX, w_array)
     positions = range(size)
     random.shuffle(positions)
     for selector, w_compiledmethod in methods.items():
         pos = positions.pop()
-        w_selector = objtable.wrap_string(selector)
+        w_selector = utility.wrap_string(selector)
         w_methoddict.store(constants.METHODDICT_NAMES_INDEX+pos, w_selector)
         w_array.store(pos, w_compiledmethod)
     #print w_methoddict._vars
@@ -37,9 +38,9 @@
     w_class = model.W_PointersObject(w_classofclass, size)
     w_class.store(constants.CLASS_SUPERCLASS_INDEX, w_superclass)
     w_class.store(constants.CLASS_METHODDICT_INDEX, w_methoddict)
-    w_class.store(constants.CLASS_FORMAT_INDEX, objtable.wrap_int(format))
+    w_class.store(constants.CLASS_FORMAT_INDEX, utility.wrap_int(format))
     if name is not None:
-        w_class.store(constants.CLASS_NAME_INDEX, objtable.wrap_string(name))
+        w_class.store(constants.CLASS_NAME_INDEX, utility.wrap_string(name))
     return w_class
 
 def basicshape(name, format, kind, varsized, instsize):

Added: pypy/dist/pypy/lang/smalltalk/utility.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/lang/smalltalk/utility.py	Mon Oct 29 16:43:04 2007
@@ -0,0 +1,68 @@
+from pypy.lang.smalltalk.error import UnwrappingError, WrappingError
+from pypy.lang.smalltalk import model
+
+
+# ____________________________________________________________ 
+# unwrapping utilities
+
+def unwrap_int(w_value):
+    if isinstance(w_value, model.W_SmallInteger):
+        return w_value.value
+    raise UnwrappingError("expected a W_SmallInteger, got %s" % (w_value,))
+
+def unwrap_char(w_char):
+    from pypy.lang.smalltalk import classtable, objtable, constants
+    w_class = w_char.getclass()
+    if w_class is not classtable.w_Character:
+        raise UnwrappingError("expected character, got %s" % (w_class, ))
+    w_ord = w_char.fetch(constants.CHARACTER_VALUE_INDEX)
+    w_class = w_ord.getclass()
+    if w_class is not classtable.w_SmallInteger:
+        raise UnwrappingError("expected smallint from character, got %s" % (w_class, ))
+
+    assert isinstance(w_ord, model.W_SmallInteger)
+    return chr(w_ord.value)
+
+# ____________________________________________________________ 
+# wrapping utilities
+
+def wrap_int(i):
+    from pypy.lang.smalltalk import constants
+    if i <= constants.TAGGED_MAXINT and i >= constants.TAGGED_MININT:
+        return model.W_SmallInteger(i)
+    raise WrappingError("integer too large to fit into a tagged pointer")
+
+def wrap_float(i):
+    return model.W_Float(i)
+
+def wrap_string(string):
+    from pypy.lang.smalltalk import classtable
+    w_inst = classtable.w_String.as_class_get_shadow().new(len(string))
+    for i in range(len(string)):
+        w_inst.setchar(i, string[i])
+    return w_inst
+
+def wrap_char(c):
+    from pypy.lang.smalltalk.objtable import CharacterTable
+    return CharacterTable[ord(c)]
+
+def wrap_bool(bool):
+    from pypy.lang.smalltalk import objtable
+    if bool:
+        return objtable.w_true
+    else:
+        return objtable.w_false
+
+def wrap_list(lst_w_obj):
+    from pypy.lang.smalltalk import classtable
+    """
+    Converts a Python list of wrapper objects into
+    a wrapped smalltalk array
+    """
+    lstlen = len(lit)
+    res = classtable.w_Array.as_class_get_shadow().new(lstlen)
+    for i in range(lstlen):
+        res.storevarpointer(i, fakeliteral(lit[i]))
+    return res
+
+

Modified: pypy/dist/pypy/translator/goal/targetfibsmalltalk.py
==============================================================================
--- pypy/dist/pypy/translator/goal/targetfibsmalltalk.py	(original)
+++ pypy/dist/pypy/translator/goal/targetfibsmalltalk.py	Mon Oct 29 16:43:04 2007
@@ -1,6 +1,6 @@
 from pypy.lang.smalltalk import model, interpreter, primitives, shadow
 from pypy.lang.smalltalk import objtable
-from pypy.lang.smalltalk.objtable import wrap_int
+from pypy.lang.smalltalk.utility import wrap_int, unwrap_int
 from pypy.lang.smalltalk import classtable
 from pypy.lang.smalltalk.test.test_interpreter import *
 
@@ -30,7 +30,7 @@
     interp.w_active_context.push(w_object)
     interp.w_active_context.push(wrap_int(8))
     result = interp.interpret()
-    assert primitives.unwrap_int(result) == 34
+    assert unwrap_int(result) == 34
     print "check_me() ok"
 check_me()
 
@@ -45,7 +45,7 @@
     interp.w_active_context.push(w_object)
     interp.w_active_context.push(wrap_int(n))
     result = interp.interpret()
-    print primitives.unwrap_int(result)
+    print unwrap_int(result)
     return 0
 
 # _____ Define and setup target ___

Modified: pypy/dist/pypy/translator/goal/targetimageloadingmalltalk.py
==============================================================================
--- pypy/dist/pypy/translator/goal/targetimageloadingmalltalk.py	(original)
+++ pypy/dist/pypy/translator/goal/targetimageloadingmalltalk.py	Mon Oct 29 16:43:04 2007
@@ -3,7 +3,6 @@
 import os
 from pypy.lang.smalltalk import model, interpreter, primitives, shadow
 from pypy.lang.smalltalk import objtable
-from pypy.lang.smalltalk.objtable import wrap_int
 from pypy.lang.smalltalk import classtable
 # from pypy.lang.smalltalk.test.test_interpreter import *
 from pypy.lang.smalltalk import squeakimage
@@ -69,8 +68,8 @@
     reader.initialize()
     image = squeakimage.SqueakImage()
     image.from_reader(reader)
-    interp = tinyBenchmarks(image)
-    run_benchmarks(interp)
+    #interp = tinyBenchmarks(image)
+    #run_benchmarks(interp)
     return 0
 
 # _____ Define and setup target ___



More information about the Pypy-commit mailing list