[pypy-commit] pypy space-newtext: more wraps removed

cfbolz pypy.commits at gmail.com
Fri Oct 21 07:48:50 EDT 2016


Author: Carl Friedrich Bolz <cfbolz at gmx.de>
Branch: space-newtext
Changeset: r87909:c945ce239b8c
Date: 2016-10-21 12:17 +0200
http://bitbucket.org/pypy/pypy/changeset/c945ce239b8c/

Log:	more wraps removed

diff --git a/pypy/interpreter/astcompiler/assemble.py b/pypy/interpreter/astcompiler/assemble.py
--- a/pypy/interpreter/astcompiler/assemble.py
+++ b/pypy/interpreter/astcompiler/assemble.py
@@ -266,8 +266,8 @@
             else:
                 w_key = space.newtuple([obj, space.w_float])
         elif space.is_w(w_type, space.w_complex):
-            w_real = space.getattr(obj, space.wrap("real"))
-            w_imag = space.getattr(obj, space.wrap("imag"))
+            w_real = space.getattr(obj, space.newtext("real"))
+            w_imag = space.getattr(obj, space.newtext("imag"))
             real = space.float_w(w_real)
             imag = space.float_w(w_imag)
             real_negzero = (real == 0.0 and
@@ -366,7 +366,7 @@
         space = self.space
         consts_w = [space.w_None] * space.len_w(w_consts)
         w_iter = space.iter(w_consts)
-        first = space.wrap(0)
+        first = space.newint(0)
         while True:
             try:
                 w_key = space.next(w_iter)
diff --git a/pypy/interpreter/astcompiler/astbuilder.py b/pypy/interpreter/astcompiler/astbuilder.py
--- a/pypy/interpreter/astcompiler/astbuilder.py
+++ b/pypy/interpreter/astcompiler/astbuilder.py
@@ -1070,8 +1070,8 @@
                 raw = "0" + raw
         if negative:
             raw = "-" + raw
-        w_num_str = self.space.wrap(raw)
-        w_base = self.space.wrap(base)
+        w_num_str = self.space.newtext(raw)
+        w_base = self.space.newint(base)
         if raw[-1] in "lL":
             tp = self.space.w_long
             return self.space.call_function(tp, w_num_str, w_base)
@@ -1109,7 +1109,7 @@
             # This implements implicit string concatenation.
             if len(sub_strings_w) > 1:
                 w_sub_strings = space.newlist(sub_strings_w)
-                w_join = space.getattr(space.wrap(""), space.wrap("join"))
+                w_join = space.getattr(space.newtext(""), space.newtext("join"))
                 final_string = space.call_function(w_join, w_sub_strings)
             else:
                 final_string = sub_strings_w[0]
diff --git a/pypy/interpreter/astcompiler/codegen.py b/pypy/interpreter/astcompiler/codegen.py
--- a/pypy/interpreter/astcompiler/codegen.py
+++ b/pypy/interpreter/astcompiler/codegen.py
@@ -321,7 +321,7 @@
     def visit_ClassDef(self, cls):
         self.update_position(cls.lineno, True)
         self.visit_sequence(cls.decorator_list)
-        self.load_const(self.space.wrap(cls.name))
+        self.load_const(self.space.newtext(cls.name))
         self.visit_sequence(cls.bases)
         bases_count = len(cls.bases) if cls.bases is not None else 0
         self.emit_op_arg(ops.BUILD_TUPLE, bases_count)
@@ -610,7 +610,7 @@
                 level = 0
             else:
                 level = -1
-            self.load_const(self.space.wrap(level))
+            self.load_const(self.space.newint(level))
             self.load_const(self.space.w_None)
             self.emit_op_name(ops.IMPORT_NAME, self.names, alias.name)
             # If there's no asname then we store the root module.  If there is
@@ -653,12 +653,12 @@
             level = -1
         else:
             level = imp.level
-        self.load_const(space.wrap(level))
+        self.load_const(space.newint(level))
         names_w = [None]*len(imp.names)
         for i in range(len(imp.names)):
             alias = imp.names[i]
             assert isinstance(alias, ast.alias)
-            names_w[i] = space.wrap(alias.name)
+            names_w[i] = space.newtext(alias.name)
         self.load_const(space.newtuple(names_w))
         if imp.module:
             mod_name = imp.module
@@ -943,7 +943,7 @@
         self.name_op(name.id, name.ctx)
 
     def visit_keyword(self, keyword):
-        self.load_const(self.space.wrap(keyword.arg))
+        self.load_const(self.space.newtext(keyword.arg))
         keyword.value.walkabout(self)
 
     def visit_Call(self, call):
diff --git a/pypy/interpreter/astcompiler/optimize.py b/pypy/interpreter/astcompiler/optimize.py
--- a/pypy/interpreter/astcompiler/optimize.py
+++ b/pypy/interpreter/astcompiler/optimize.py
@@ -119,7 +119,7 @@
     return space.pow(w_left, w_right, space.w_None)
 
 def _fold_not(space, operand):
-    return space.wrap(not space.is_true(operand))
+    return space.newbool(not space.is_true(operand))
 
 
 binary_folders = {
@@ -214,7 +214,7 @@
                         break
                 else:
                     raise AssertionError("unknown unary operation")
-                w_minint = self.space.wrap(-sys.maxint - 1)
+                w_minint = self.space.newint(-sys.maxint - 1)
                 # This makes sure the result is an integer.
                 if self.space.eq_w(w_minint, w_const):
                     w_const = w_minint
diff --git a/pypy/interpreter/baseobjspace.py b/pypy/interpreter/baseobjspace.py
--- a/pypy/interpreter/baseobjspace.py
+++ b/pypy/interpreter/baseobjspace.py
@@ -1577,7 +1577,8 @@
     def str_w(self, w_obj):
         return w_obj.str_w(self)
 
-    bytes_w = str_w  # Python2
+    bytes_w = str_w  # the same on Python3
+    text_w = str_w # equivalent to identifier_w on Python3
 
     def str0_w(self, w_obj):
         "Like str_w, but rejects strings with NUL bytes."
diff --git a/pypy/interpreter/error.py b/pypy/interpreter/error.py
--- a/pypy/interpreter/error.py
+++ b/pypy/interpreter/error.py
@@ -244,10 +244,10 @@
             if with_traceback:
                 w_t = self.w_type
                 w_v = self.get_w_value(space)
-                w_tb = space.wrap(self.get_traceback())
-                space.appexec([space.wrap(where),
-                               space.wrap(objrepr),
-                               space.wrap(extra_line),
+                w_tb = self.get_traceback()
+                space.appexec([space.newtext(where),
+                               space.newtext(objrepr),
+                               space.newtext(extra_line),
                                w_t, w_v, w_tb],
                 """(where, objrepr, extra_line, t, v, tb):
                     import sys, traceback
@@ -261,7 +261,7 @@
                 msg = 'Exception %s in %s%s ignored\n' % (
                     self.errorstr(space, use_repr=True), where, objrepr)
                 space.call_method(space.sys.get('stderr'), 'write',
-                                  space.wrap(msg))
+                                  space.newtext(msg))
         except OperationError:
             pass   # ignored
 
@@ -269,7 +269,7 @@
         w_value = self._w_value
         if w_value is None:
             value = self._compute_value(space)
-            self._w_value = w_value = space.wrap(value)
+            self._w_value = w_value = space.newtext(value)
         return w_value
 
     def _compute_value(self, space):
@@ -387,7 +387,7 @@
 
 @specialize.arg(1)
 def oefmt(w_type, valuefmt, *args):
-    """Equivalent to OperationError(w_type, space.wrap(valuefmt % args)).
+    """Equivalent to OperationError(w_type, space.newtext(valuefmt % args)).
     More efficient in the (common) case where the value is not actually
     needed.
 
@@ -429,11 +429,11 @@
             msg = 'Windows Error %d' % winerror
         exc = space.w_WindowsError
         if w_filename is not None:
-            w_error = space.call_function(exc, space.wrap(winerror),
-                                          space.wrap(msg), w_filename)
+            w_error = space.call_function(exc, space.newint(winerror),
+                                          space.newtext(msg), w_filename)
         else:
-            w_error = space.call_function(exc, space.wrap(winerror),
-                                          space.wrap(msg))
+            w_error = space.call_function(exc, space.newint(winerror),
+                                          space.newtext(msg))
         return OperationError(exc, w_error)
 
 def wrap_oserror2(space, e, w_filename=None, exception_name='w_OSError',
@@ -457,18 +457,18 @@
     else:
         exc = w_exception_class
     if w_filename is not None:
-        w_error = space.call_function(exc, space.wrap(errno),
-                                      space.wrap(msg), w_filename)
+        w_error = space.call_function(exc, space.newint(errno),
+                                      space.newtext(msg), w_filename)
     else:
-        w_error = space.call_function(exc, space.wrap(errno),
-                                      space.wrap(msg))
+        w_error = space.call_function(exc, space.newint(errno),
+                                      space.newtext(msg))
     return OperationError(exc, w_error)
 wrap_oserror2._annspecialcase_ = 'specialize:arg(3)'
 
 def wrap_oserror(space, e, filename=None, exception_name='w_OSError',
                  w_exception_class=None):
     if filename is not None:
-        return wrap_oserror2(space, e, space.wrap(filename),
+        return wrap_oserror2(space, e, space.newtext(filename),
                              exception_name=exception_name,
                              w_exception_class=w_exception_class)
     else:
@@ -482,7 +482,7 @@
 
     errno = get_saved_errno()
     msg = os.strerror(errno)
-    w_error = space.call_function(w_type, space.wrap(errno), space.wrap(msg))
+    w_error = space.call_function(w_type, space.newint(errno), space.newtext(msg))
     return OperationError(w_type, w_error)
 
 def new_exception_class(space, name, w_bases=None, w_dict=None):
@@ -503,7 +503,7 @@
     if w_dict is None:
         w_dict = space.newdict()
     w_exc = space.call_function(
-        space.w_type, space.wrap(name), w_bases, w_dict)
+        space.w_type, space.newtext(name), w_bases, w_dict)
     if module:
-        space.setattr(w_exc, space.wrap("__module__"), space.wrap(module))
+        space.setattr(w_exc, space.newtext("__module__"), space.newtext(module))
     return w_exc
diff --git a/pypy/interpreter/generator.py b/pypy/interpreter/generator.py
--- a/pypy/interpreter/generator.py
+++ b/pypy/interpreter/generator.py
@@ -23,15 +23,14 @@
         else:
             code_name = self.pycode.co_name
         addrstring = self.getaddrstring(space)
-        return space.wrap("<generator object %s at 0x%s>" %
-                          (code_name, addrstring))
+        return space.newtext("<generator object %s at 0x%s>" %
+                             (code_name, addrstring))
 
     def descr__reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
         w_mod    = space.getbuiltinmodule('_pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('generator_new')
-        w        = space.wrap
         if self.frame:
             w_frame = self.frame._reduce_state(space)
         else:
@@ -39,7 +38,7 @@
 
         tup = [
             w_frame,
-            w(self.running),
+            space.newbool(self.running),
             ]
 
         return space.newtuple([new_inst, space.newtuple([]),
@@ -61,7 +60,7 @@
 
     def descr__iter__(self):
         """x.__iter__() <==> iter(x)"""
-        return self.space.wrap(self)
+        return self
 
     def descr_send(self, w_arg):
         """send(arg) -> send 'arg' into generator,
@@ -170,7 +169,7 @@
             code_name = '<finished>'
         else:
             code_name = self.pycode.co_name
-        return space.wrap(code_name)
+        return space.newtext(code_name)
 
     # Results can be either an RPython list of W_Root, or it can be an
     # app-level W_ListObject, which also has an append() method, that's why we
diff --git a/pypy/interpreter/mixedmodule.py b/pypy/interpreter/mixedmodule.py
--- a/pypy/interpreter/mixedmodule.py
+++ b/pypy/interpreter/mixedmodule.py
@@ -110,7 +110,7 @@
                     bltin.w_module = self.w_name
                     func._builtinversion_ = bltin
                     bltin.name = name
-                w_value = space.wrap(bltin)
+                w_value = bltin
             space.setitem(self.w_dict, w_name, w_value)
             return w_value
 
@@ -158,7 +158,7 @@
 
     @classmethod
     def get__doc__(cls, space):
-        return space.wrap(cls.__doc__)
+        return space.newtext_or_none(cls.__doc__)
 
 
 def getinterpevalloader(pkgroot, spec):
@@ -186,7 +186,7 @@
             else:
                 #print spec, "->", value
                 if hasattr(value, 'func_code'):  # semi-evil
-                    return space.wrap(gateway.interp2app(value))
+                    return gateway.interp2app(value).get_function(space)
 
                 try:
                     is_type = issubclass(value, W_Root)  # pseudo-evil
diff --git a/pypy/interpreter/module.py b/pypy/interpreter/module.py
--- a/pypy/interpreter/module.py
+++ b/pypy/interpreter/module.py
@@ -78,7 +78,7 @@
     def descr_module__new__(space, w_subtype, __args__):
         module = space.allocate_instance(Module, w_subtype)
         Module.__init__(module, space, None, add_package=False)
-        return space.wrap(module)
+        return module
 
     def descr_module__init__(self, w_name, w_doc=None):
         space = self.space
@@ -89,7 +89,7 @@
         space.setitem(self.w_dict, space.new_interned_str('__doc__'), w_doc)
 
     def descr__reduce__(self, space):
-        w_name = space.finditem(self.w_dict, space.wrap('__name__'))
+        w_name = space.finditem(self.w_dict, space.newtext('__name__'))
         if (w_name is None or
             not space.isinstance_w(w_name, space.w_str)):
             # maybe raise exception here (XXX this path is untested)
@@ -113,7 +113,7 @@
                 w_name,
                 space.w_None,
                 space.w_None,
-                space.newtuple([space.wrap('')])
+                space.newtuple([space.newtext('')])
             ])
         ]
 
@@ -126,10 +126,10 @@
         else:
             name = "'?'"
         if isinstance(self, MixedModule):
-            return space.wrap("<module %s (built-in)>" % name)
+            return space.newtext("<module %s (built-in)>" % name)
         try:
-            w___file__ = space.getattr(self, space.wrap('__file__'))
+            w___file__ = space.getattr(self, space.newtext('__file__'))
             __file__ = space.str_w(space.repr(w___file__))
         except OperationError:
             __file__ = '?'
-        return space.wrap("<module %s from %s>" % (name, __file__))
+        return space.newtext("<module %s from %s>" % (name, __file__))
diff --git a/pypy/interpreter/pyopcode.py b/pypy/interpreter/pyopcode.py
--- a/pypy/interpreter/pyopcode.py
+++ b/pypy/interpreter/pyopcode.py
@@ -778,11 +778,11 @@
         w_prog = self.popvalue()
         ec = self.space.getexecutioncontext()
         flags = ec.compiler.getcodeflags(self.pycode)
-        w_compile_flags = self.space.wrap(flags)
-        w_resulttuple = prepare_exec(self.space, self.space.wrap(self), w_prog,
+        w_compile_flags = self.space.newint(flags)
+        w_resulttuple = prepare_exec(self.space, self, w_prog,
                                      w_globals, w_locals,
                                      w_compile_flags,
-                                     self.space.wrap(self.get_builtin()),
+                                     self.get_builtin(),
                                      self.space.gettypeobject(PyCode.typedef))
         w_prog, w_globals, w_locals = self.space.fixedview(w_resulttuple, 3)
 
@@ -829,7 +829,7 @@
         w_name = self.popvalue()
         w_metaclass = find_metaclass(self.space, w_bases,
                                      w_methodsdict, self.get_w_globals(),
-                                     self.space.wrap(self.get_builtin()))
+                                     self.get_builtin())
         w_newclass = self.space.call_function(w_metaclass, w_name,
                                               w_bases, w_methodsdict)
         self.pushvalue(w_newclass)
@@ -1414,9 +1414,8 @@
 
     # internal pickling interface, not using the standard protocol
     def _get_state_(self, space):
-        w = space.wrap
-        return space.newtuple([w(self._opname), w(self.handlerposition),
-                               w(self.valuestackdepth)])
+        return space.newtuple([space.newtext(self._opname), space.newint(self.handlerposition),
+                               space.newint(self.valuestackdepth)])
 
     def handle(self, frame, unroller):
         """ Purely abstract method
diff --git a/pypy/interpreter/pyparser/parsestring.py b/pypy/interpreter/pyparser/parsestring.py
--- a/pypy/interpreter/pyparser/parsestring.py
+++ b/pypy/interpreter/pyparser/parsestring.py
@@ -62,7 +62,7 @@
             v = unicodehelper.decode_raw_unicode_escape(space, substr)
         else:
             v = unicodehelper.decode_unicode_escape(space, substr)
-        return space.wrap(v)
+        return space.newunicode(v)
 
     need_encoding = (encoding is not None and
                      encoding != "utf-8" and encoding != "utf8" and
@@ -71,11 +71,11 @@
     substr = s[ps : q]
     if rawmode or '\\' not in s[ps:]:
         if need_encoding:
-            w_u = space.wrap(unicodehelper.decode_utf8(space, substr))
+            w_u = space.newunicode(unicodehelper.decode_utf8(space, substr))
             w_v = unicodehelper.encode(space, w_u, encoding)
             return w_v
         else:
-            return space.wrap(substr)
+            return space.newbytes(substr)
 
     enc = None
     if need_encoding:
@@ -226,9 +226,9 @@
 
 def decode_utf8_recode(space, s, ps, end, recode_encoding):
     u, ps = decode_utf8(space, s, ps, end)
-    w_v = unicodehelper.encode(space, space.wrap(u), recode_encoding)
+    w_v = unicodehelper.encode(space, space.newunicode(u), recode_encoding)
     v = space.str_w(w_v)
     return v, ps
 
 def raise_app_valueerror(space, msg):
-    raise OperationError(space.w_ValueError, space.wrap(msg))
+    raise OperationError(space.w_ValueError, space.newtext(msg))
diff --git a/pypy/interpreter/pyparser/pyparse.py b/pypy/interpreter/pyparser/pyparse.py
--- a/pypy/interpreter/pyparser/pyparse.py
+++ b/pypy/interpreter/pyparser/pyparse.py
@@ -3,11 +3,11 @@
 from pypy.interpreter.astcompiler import consts
 
 def recode_to_utf8(space, bytes, encoding):
-    w_text = space.call_method(space.wrap(bytes), "decode",
-                               space.wrap(encoding))
+    w_text = space.call_method(space.newbytes(bytes), "decode",
+                               space.newtext(encoding))
     if not space.isinstance_w(w_text, space.w_unicode):
         raise error.SyntaxError("codec did not return a unicode object")
-    w_recoded = space.call_method(w_text, "encode", space.wrap("utf-8"))
+    w_recoded = space.call_method(w_text, "encode", space.newtext("utf-8"))
     return space.str_w(w_recoded)
 
 def _normalize_encoding(encoding):
diff --git a/pypy/interpreter/test/test_error.py b/pypy/interpreter/test/test_error.py
--- a/pypy/interpreter/test/test_error.py
+++ b/pypy/interpreter/test/test_error.py
@@ -89,6 +89,7 @@
         w_EnvironmentError = [EnvironmentError]
         def wrap(self, obj):
             return [obj]
+        newint = newtext = wrap
         def call_function(self, exc, w_errno, w_msg, w_filename=None):
             return (exc, w_errno, w_msg, w_filename)
     space = FakeSpace()
diff --git a/pypy/interpreter/typedef.py b/pypy/interpreter/typedef.py
--- a/pypy/interpreter/typedef.py
+++ b/pypy/interpreter/typedef.py
@@ -92,7 +92,7 @@
 def default_identity_hash(space, w_obj):
     w_unique_id = w_obj.immutable_unique_id(space)
     if w_unique_id is None:     # common case
-        return space.wrap(compute_identity_hash(w_obj))
+        return space.newint(compute_identity_hash(w_obj))
     else:
         return space.hash(w_unique_id)
 
@@ -280,7 +280,7 @@
         if (space.is_w(w_obj, space.w_None)
             and not space.is_w(w_cls, space.type(space.w_None))):
             #print self, w_obj, w_cls
-            return space.wrap(self)
+            return self
         else:
             try:
                 return self.fget(self, space, w_obj)
@@ -288,7 +288,7 @@
                 return w_obj.descr_call_mismatch(
                     space, '__getattribute__',
                     self.reqcls, Arguments(space, [w_obj,
-                                                   space.wrap(self.name)]))
+                                                   space.newtext(self.name)]))
 
     def descr_property_set(self, space, w_obj, w_value):
         """property.__set__(obj, value)
@@ -302,7 +302,7 @@
             w_obj.descr_call_mismatch(
                 space, '__setattr__',
                 self.reqcls, Arguments(space, [w_obj,
-                                               space.wrap(self.name),
+                                               space.newtext(self.name),
                                                w_value]))
 
     def descr_property_del(self, space, w_obj):
@@ -317,13 +317,14 @@
             w_obj.descr_call_mismatch(
                 space, '__delattr__',
                 self.reqcls, Arguments(space, [w_obj,
-                                               space.wrap(self.name)]))
+                                               space.newtext(self.name)]))
 
     def descr_get_objclass(space, property):
         return property.objclass_getter(space)
 
 def interp_attrproperty(name, cls, doc=None):
     "NOT_RPYTHON: initialization-time only"
+    # YYY needs some refactoring to get rid of the wrap
     def fget(space, obj):
         return space.wrap(getattr(obj, name))
     return GetSetProperty(fget, cls=cls, doc=doc)
@@ -370,13 +371,13 @@
         """member.__get__(obj[, type]) -> value
         Read the slot 'member' of the given 'obj'."""
         if space.is_w(w_obj, space.w_None):
-            return space.wrap(self)
+            return self
         else:
             self.typecheck(space, w_obj)
             w_result = w_obj.getslotvalue(self.index)
             if w_result is None:
                 raise OperationError(space.w_AttributeError,
-                                     space.wrap(self.name)) # XXX better message
+                                     space.newtext(self.name)) # XXX better message
             return w_result
 
     def descr_member_set(self, space, w_obj, w_value):
@@ -392,7 +393,7 @@
         success = w_obj.delslotvalue(self.index)
         if not success:
             raise OperationError(space.w_AttributeError,
-                                 space.wrap(self.name)) # XXX better message
+                                 space.newtext(self.name)) # XXX better message
 
 Member.typedef = TypeDef(
     "member_descriptor",
@@ -423,7 +424,7 @@
     def descr_new(space, w_subtype, __args__):
         self = space.allocate_instance(W_Type, w_subtype)
         W_Type.__init__(self, space)
-        return space.wrap(self)
+        return self
     descr_new = func_with_new_name(descr_new, 'descr_new_%s' % W_Type.__name__)
     return interp2app(descr_new)
 
@@ -478,10 +479,10 @@
 
 # co_xxx interface emulation for built-in code objects
 def fget_co_varnames(space, code): # unwrapping through unwrap_spec
-    return space.newtuple([space.wrap(name) for name in code.getvarnames()])
+    return space.newtuple([space.newtext(name) for name in code.getvarnames()])
 
 def fget_co_argcount(space, code): # unwrapping through unwrap_spec
-    return space.wrap(code.signature().num_argnames())
+    return space.newint(code.signature().num_argnames())
 
 def fget_co_flags(space, code): # unwrapping through unwrap_spec
     sig = code.signature()
@@ -490,7 +491,7 @@
         flags |= CO_VARARGS
     if sig.has_kwarg():
         flags |= CO_VARKEYWORDS
-    return space.wrap(flags)
+    return space.newint(flags)
 
 def fget_co_consts(space, code): # unwrapping through unwrap_spec
     w_docstring = code.getdocstring(space)
diff --git a/pypy/interpreter/unicodehelper.py b/pypy/interpreter/unicodehelper.py
--- a/pypy/interpreter/unicodehelper.py
+++ b/pypy/interpreter/unicodehelper.py
@@ -9,11 +9,11 @@
     def raise_unicode_exception_decode(errors, encoding, msg, s,
                                        startingpos, endingpos):
         raise OperationError(space.w_UnicodeDecodeError,
-                             space.newtuple([space.wrap(encoding),
-                                             space.wrap(s),
-                                             space.wrap(startingpos),
-                                             space.wrap(endingpos),
-                                             space.wrap(msg)]))
+                             space.newtuple([space.newtext(encoding),
+                                             space.newbytes(s),
+                                             space.newint(startingpos),
+                                             space.newint(endingpos),
+                                             space.newtext(msg)]))
     return raise_unicode_exception_decode
 
 class RUnicodeEncodeError(Exception):
diff --git a/pypy/objspace/std/bufferobject.py b/pypy/objspace/std/bufferobject.py
--- a/pypy/objspace/std/bufferobject.py
+++ b/pypy/objspace/std/bufferobject.py
@@ -57,10 +57,9 @@
         start, stop, step, size = space.decode_index4(w_index,
                                                       self.buf.getlength())
         if step == 0:  # index only
-            import pdb; pdb.set_trace()
-            return space.wrap(self.buf.getitem(start))
+            return space.newbytes(self.buf.getitem(start))
         res = self.buf.getslice(start, stop, step, size)
-        return space.wrap(res)
+        return space.newbytes(res)
 
     def descr_setitem(self, space, w_index, w_obj):
         if self.buf.readonly:
@@ -84,11 +83,11 @@
                     self.buf.setitem(start + i * step, value.getitem(i))
 
     def descr_str(self, space):
-        return space.wrap(self.buf.as_str())
+        return space.newbytes(self.buf.as_str())
 
     @unwrap_spec(other='bufferstr')
     def descr_add(self, space, other):
-        return space.wrap(self.buf.as_str() + other)
+        return space.newbytes(self.buf.as_str() + other)
 
     def _make_descr__cmp(name):
         def descr__cmp(self, space, w_other):
@@ -97,7 +96,7 @@
             # xxx not the most efficient implementation
             str1 = self.buf.as_str()
             str2 = w_other.buf.as_str()
-            return space.wrap(getattr(operator, name)(str1, str2))
+            return space.newbool(getattr(operator, name)(str1, str2))
         descr__cmp.func_name = name
         return descr__cmp
 
@@ -109,11 +108,11 @@
     descr_ge = _make_descr__cmp('ge')
 
     def descr_hash(self, space):
-        return space.wrap(compute_hash(self.buf.as_str()))
+        return space.newint(compute_hash(self.buf.as_str()))
 
     def descr_mul(self, space, w_times):
         # xxx not the most efficient implementation
-        w_string = space.wrap(self.buf.as_str())
+        w_string = space.newbytes(self.buf.as_str())
         # use the __mul__ method instead of space.mul() so that we
         # return NotImplemented instead of raising a TypeError
         return space.call_method(w_string, '__mul__', w_times)
@@ -125,8 +124,8 @@
             info = 'read-write buffer'
         addrstring = self.getaddrstring(space)
 
-        return space.wrap("<%s for 0x%s, size %d>" %
-                          (info, addrstring, self.buf.getlength()))
+        return space.newtext("<%s for 0x%s, size %d>" %
+                             (info, addrstring, self.buf.getlength()))
 
     def descr_pypy_raw_address(self, space):
         from rpython.rtyper.lltypesystem import lltype, rffi
@@ -136,8 +135,8 @@
             # report the error using the RPython-level internal repr of self.buf
             msg = ("cannot find the underlying address of buffer that "
                    "is internally %r" % (self.buf,))
-            raise OperationError(space.w_ValueError, space.wrap(msg))
-        return space.wrap(rffi.cast(lltype.Signed, ptr))
+            raise OperationError(space.w_ValueError, space.newtext(msg))
+        return space.newint(rffi.cast(lltype.Signed, ptr))
 
 W_Buffer.typedef = TypeDef(
     "buffer", None, None, "read-write",
diff --git a/pypy/objspace/std/formatting.py b/pypy/objspace/std/formatting.py
--- a/pypy/objspace/std/formatting.py
+++ b/pypy/objspace/std/formatting.py
@@ -200,7 +200,10 @@
             space = self.space
             if self.w_valuedict is None:
                 raise oefmt(space.w_TypeError, "format requires a mapping")
-            w_key = space.wrap(key)
+            if do_unicode:
+                w_key = space.newunicode(key)
+            else:
+                w_key = space.newbytes(key)
             return space.getitem(self.w_valuedict, w_key)
 
         def parse_fmt(self):
@@ -334,10 +337,10 @@
             if do_unicode:
                 w_defaultencoding = space.call_function(
                     space.sys.get('getdefaultencoding'))
-                w_s = space.call_method(space.wrap(c),
+                w_s = space.call_method(space.newunicode(c),
                                         "encode",
                                         w_defaultencoding,
-                                        space.wrap('replace'))
+                                        space.newtext('replace'))
                 s = space.str_w(w_s)
             else:
                 s = c
@@ -350,7 +353,7 @@
             length = len(r)
             if do_unicode and isinstance(r, str):
                 # convert string to unicode using the default encoding
-                r = self.space.unicode_w(self.space.wrap(r))
+                r = self.space.unicode_w(self.space.newbytes(r))
             prec = self.prec
             if prec == -1 and self.width == 0:
                 # fast path
@@ -454,7 +457,7 @@
             self.std_wp(s)
 
         def fmt_r(self, w_value):
-            self.std_wp(self.space.str_w(self.space.repr(w_value)))
+            self.std_wp(self.space.text_w(self.space.repr(w_value)))
 
         def fmt_c(self, w_value):
             self.prec = -1     # just because
@@ -516,11 +519,11 @@
             # fall through to the unicode case
             pass
         else:
-            return space.wrap(result)
+            return space.newbytes(result)
     fmt = space.unicode_w(w_fmt)
     formatter = UnicodeFormatter(space, fmt, values_w, w_valuedict)
     result = formatter.format()
-    return space.wrap(result)
+    return space.newunicode(result)
 
 def mod_format(space, w_format, w_values, do_unicode=False):
     if space.isinstance_w(w_values, space.w_tuple):
diff --git a/pypy/objspace/std/marshal_impl.py b/pypy/objspace/std/marshal_impl.py
--- a/pypy/objspace/std/marshal_impl.py
+++ b/pypy/objspace/std/marshal_impl.py
@@ -152,7 +152,7 @@
         x = (hi << 32) | (lo & (2**32-1))    # result fits in an int
     else:
         x = (r_longlong(hi) << 32) | r_longlong(r_uint(lo))  # get a r_longlong
-    return space.wrap(x)
+    return space.newint(x)
 
 
 @marshaller(W_AbstractLongObject)
@@ -210,7 +210,7 @@
 @unmarshaller(TYPE_FLOAT)
 def unmarshal_float(space, u, tc):
     return space.call_function(space.builtin.get('float'),
-                               space.wrap(u.get_pascal()))
+                               space.newtext(u.get_pascal()))
 
 @unmarshaller(TYPE_BINARY_FLOAT)
 def unmarshal_float_bin(space, u, tc):
@@ -224,9 +224,8 @@
         m.put(pack_float(w_complex.realval))
         m.put(pack_float(w_complex.imagval))
     else:
-        # XXX a bit too wrap-happy
-        w_real = space.wrap(w_complex.realval)
-        w_imag = space.wrap(w_complex.imagval)
+        w_real = space.newfloat(w_complex.realval)
+        w_imag = space.newfloat(w_complex.imagval)
         m.start(TYPE_COMPLEX)
         m.put_pascal(space.str_w(space.repr(w_real)))
         m.put_pascal(space.str_w(space.repr(w_imag)))
@@ -234,9 +233,9 @@
 @unmarshaller(TYPE_COMPLEX)
 def unmarshal_complex(space, u, tc):
     w_real = space.call_function(space.builtin.get('float'),
-                                 space.wrap(u.get_pascal()))
+                                 space.newtext(u.get_pascal()))
     w_imag = space.call_function(space.builtin.get('float'),
-                                 space.wrap(u.get_pascal()))
+                                 space.newtext(u.get_pascal()))
     w_t = space.builtin.get('complex')
     return space.call_function(w_t, w_real, w_imag)
 
@@ -265,7 +264,7 @@
 
 @unmarshaller(TYPE_STRING)
 def unmarshal_bytes(space, u, tc):
-    return space.wrap(u.get_str())
+    return space.newbytes(u.get_str())
 
 @unmarshaller(TYPE_INTERNED)
 def unmarshal_interned(space, u, tc):
@@ -404,7 +403,7 @@
 
 @unmarshaller(TYPE_UNICODE)
 def unmarshal_unicode(space, u, tc):
-    return space.wrap(unicodehelper.decode_utf8(space, u.get_str()))
+    return space.newunicode(unicodehelper.decode_utf8(space, u.get_str()))
 
 
 @marshaller(W_SetObject)
diff --git a/pypy/objspace/std/newformat.py b/pypy/objspace/std/newformat.py
--- a/pypy/objspace/std/newformat.py
+++ b/pypy/objspace/std/newformat.py
@@ -48,6 +48,13 @@
     class TemplateFormatter(object):
         is_unicode = for_unicode
 
+        if for_unicode:
+            def wrap(self, u):
+                return self.space.newunicode(u)
+        else:
+            def wrap(self, s):
+                return self.space.newbytes(s)
+
         parser_list_w = None
 
         def __init__(self, space, template):
@@ -113,7 +120,7 @@
                             assert end_literal > last_literal
                             literal = self.template[last_literal:end_literal]
                             w_entry = space.newtuple([
-                                space.wrap(literal),
+                                self.wrap(literal),
                                 space.w_None, space.w_None, space.w_None])
                             self.parser_list_w.append(w_entry)
                             self.last_end = i
@@ -211,13 +218,13 @@
             if index == -1:
                 kwarg = name[:i]
                 if self.is_unicode:
-                    w_arg = space.getitem(self.w_kwargs, space.wrap(kwarg))
+                    w_arg = space.getitem(self.w_kwargs, self.wrap(kwarg))
                 else:
                     try:
                         w_arg = self.kwargs[kwarg]
                     except KeyError:
                         raise OperationError(space.w_KeyError,
-                                             space.wrap(kwarg))
+                                             space.newtext(kwarg))
             else:
                 try:
                     w_arg = self.args[index]
@@ -243,7 +250,7 @@
                     if start == i:
                         raise oefmt(space.w_ValueError,
                                     "Empty attribute in format string")
-                    w_attr = space.wrap(name[start:i])
+                    w_attr = self.wrap(name[start:i])
                     if w_obj is not None:
                         w_obj = space.getattr(w_obj, w_attr)
                     else:
@@ -263,9 +270,9 @@
                         raise oefmt(space.w_ValueError, "Missing ']'")
                     index, reached = _parse_int(self.space, name, start, i)
                     if index != -1 and reached == i:
-                        w_item = space.wrap(index)
+                        w_item = space.newint(index)
                     else:
-                        w_item = space.wrap(name[start:i])
+                        w_item = self.wrap(name[start:i])
                     i += 1 # Skip "]"
                     if w_obj is not None:
                         w_obj = space.getitem(w_obj, w_item)
@@ -294,9 +301,9 @@
                 if stop != i:
                     index = -1
             if index >= 0:
-                w_first = space.wrap(index)
+                w_first = space.newint(index)
             else:
-                w_first = space.wrap(name[:i])
+                w_first = self.wrap(name[:i])
             #
             self.parser_list_w = []
             self._resolve_lookups(None, name, i, end)
@@ -326,11 +333,15 @@
                     space = self.space
                     startm1 = start - 1
                     assert startm1 >= self.last_end
+                    if conversion is None:
+                        w_conversion = space.w_None
+                    else:
+                        w_conversion = self.wrap(conversion)
                     w_entry = space.newtuple([
-                        space.wrap(self.template[self.last_end:startm1]),
-                        space.wrap(name),
-                        space.wrap(spec),
-                        space.wrap(conversion)])
+                        self.wrap(self.template[self.last_end:startm1]),
+                        self.wrap(name),
+                        self.wrap(spec),
+                        w_conversion])
                     self.parser_list_w.append(w_entry)
                     self.last_end = end + 1
                 return self.empty
@@ -340,7 +351,7 @@
                 w_obj = self._convert(w_obj, conversion)
             if recursive:
                 spec = self._build_string(spec_start, end, level)
-            w_rendered = self.space.format(w_obj, self.space.wrap(spec))
+            w_rendered = self.space.format(w_obj, self.wrap(spec))
             unwrapper = "unicode_w" if self.is_unicode else "str_w"
             to_interp = getattr(self.space, unwrapper)
             return to_interp(w_rendered)
@@ -353,7 +364,7 @@
             space = self.space
             if self.last_end < len(self.template):
                 w_lastentry = space.newtuple([
-                    space.wrap(self.template[self.last_end:]),
+                    self.wrap(self.template[self.last_end:]),
                     space.w_None,
                     space.w_None,
                     space.w_None])
@@ -369,10 +380,10 @@
     if is_unicode:
         template = unicode_template_formatter(space,
                                               space.unicode_w(w_string))
-        return space.wrap(template.build(args))
+        return space.newunicode(template.build(args))
     else:
         template = str_template_formatter(space, space.str_w(w_string))
-        return space.wrap(template.build(args))
+        return space.newbytes(template.build(args))
 
 
 class NumberSpec(object):
@@ -403,6 +414,13 @@
     class Formatter(BaseFormatter):
         """__format__ implementation for builtin types."""
 
+        if for_unicode:
+            def wrap(self, u):
+                return self.space.newunicode(u)
+        else:
+            def wrap(self, s):
+                return self.space.newbytes(s)
+
         is_unicode = for_unicode
         _grouped_digits = None
 
@@ -545,7 +563,7 @@
         def format_string(self, string):
             space = self.space
             if self._parse_spec("s", "<"):
-                return space.wrap(string)
+                return self.wrap(string)
             if self._type != "s":
                 self._unknown_presentation("string")
             if self._sign != "\0":
@@ -566,7 +584,7 @@
                 length = precision
                 string = string[:precision]
             self._calc_padding(string, length)
-            return space.wrap(self._pad(string))
+            return self.wrap(self._pad(string))
 
         def _get_locale(self, tp):
             if tp == "n":
@@ -814,8 +832,8 @@
                                         n_remainder, False, result)
             fill = self._fill_char
             upper = self._type == "X"
-            return self.space.wrap(self._fill_number(spec, result, to_numeric,
-                                     to_prefix, fill, to_remainder, upper))
+            return self.wrap(self._fill_number(spec, result, to_numeric,
+                             to_prefix, fill, to_remainder, upper))
 
         def _long_to_base(self, base, value):
             prefix = ""
@@ -963,8 +981,8 @@
             spec = self._calc_num_width(0, sign, to_number, n_digits,
                                         n_remainder, have_dec_point, digits)
             fill = self._fill_char
-            return self.space.wrap(self._fill_number(spec, digits, to_number, 0,
-                                      fill, to_remainder, False))
+            return self.wrap(self._fill_number(spec, digits, to_number, 0,
+                             fill, to_remainder, False))
 
         def format_float(self, w_float):
             space = self.space
@@ -1125,7 +1143,7 @@
             #add right padding
             out.append_multiple_char(fill, self._right_pad)
 
-            return self.space.wrap(out.build())
+            return self.wrap(out.build())
 
 
         def format_complex(self, w_complex):
diff --git a/pypy/objspace/std/objspace.py b/pypy/objspace/std/objspace.py
--- a/pypy/objspace/std/objspace.py
+++ b/pypy/objspace/std/objspace.py
@@ -158,18 +158,7 @@
             #print 'wrapping', x, '->', w_result
             return w_result
         if isinstance(x, base_int):
-            if self.config.objspace.std.withsmalllong:
-                from pypy.objspace.std.smalllongobject import W_SmallLongObject
-                from rpython.rlib.rarithmetic import r_longlong, r_ulonglong
-                from rpython.rlib.rarithmetic import longlongmax
-                if (not isinstance(x, r_ulonglong)
-                    or x <= r_ulonglong(longlongmax)):
-                    return W_SmallLongObject(r_longlong(x))
-            x = widen(x)
-            if isinstance(x, int):
-                return self.newint(x)
-            else:
-                return W_LongObject.fromrarith_int(x)
+            return self.newint(x)
         return self._wrap_not_rpython(x)
 
     def _wrap_not_rpython(self, x):
@@ -251,7 +240,18 @@
             return w_obj.unwrap(self)
         raise TypeError("cannot unwrap: %r" % w_obj)
 
+    @specialize.argtype(1)
     def newint(self, intval):
+        if self.config.objspace.std.withsmalllong:
+            from pypy.objspace.std.smalllongobject import W_SmallLongObject
+            from rpython.rlib.rarithmetic import r_longlong, r_ulonglong
+            from rpython.rlib.rarithmetic import longlongmax
+            if (not isinstance(intval, r_ulonglong)
+                or intval <= r_ulonglong(longlongmax)):
+                return W_SmallLongObject(r_longlong(intval))
+        intval = widen(intval)
+        if not isinstance(intval, int):
+            return W_LongObject.fromrarith_int(intval)
         return wrapint(self, intval)
 
     def newfloat(self, floatval):
@@ -332,6 +332,11 @@
         assert isinstance(s, str)
         return W_BytesObject(s) # Python3 this is unicode
 
+    def newtext_or_none(self, s):
+        if s is None:
+            return self.w_None
+        return self.newtext(s)
+
     def newunicode(self, uni):
         assert isinstance(uni, unicode)
         return W_UnicodeObject(uni)
diff --git a/pypy/objspace/std/typeobject.py b/pypy/objspace/std/typeobject.py
--- a/pypy/objspace/std/typeobject.py
+++ b/pypy/objspace/std/typeobject.py
@@ -1109,21 +1109,19 @@
         slot_name = space.str_w(space.new_interned_str(slot_name))
         # in cpython it is ignored less, but we probably don't care
         member = Member(index_next_extra_slot, slot_name, w_self)
-        w_self.dict_w[slot_name] = space.wrap(member)
+        w_self.dict_w[slot_name] = member
         return True
     else:
         return False
 
 def create_dict_slot(w_self):
     if not w_self.hasdict:
-        w_self.dict_w.setdefault('__dict__',
-                                 w_self.space.wrap(dict_descr))
+        w_self.dict_w.setdefault('__dict__', dict_descr)
         w_self.hasdict = True
 
 def create_weakref_slot(w_self):
     if not w_self.weakrefable:
-        w_self.dict_w.setdefault('__weakref__',
-                                 w_self.space.wrap(weakref_descr))
+        w_self.dict_w.setdefault('__weakref__', weakref_descr)
         w_self.weakrefable = True
 
 def valid_slot_name(slot_name):
@@ -1157,7 +1155,11 @@
 def setup_builtin_type(w_self, instancetypedef):
     w_self.hasdict = instancetypedef.hasdict
     w_self.weakrefable = instancetypedef.weakrefable
-    w_self.w_doc = w_self.space.wrap(instancetypedef.doc)
+    if isinstance(instancetypedef.doc, W_Root):
+        w_doc = instancetypedef.doc
+    else:
+        w_doc = w_self.space.newtext_or_none(instancetypedef.doc)
+    w_self.w_doc = w_doc
     ensure_common_attributes(w_self)
     w_self.flag_heaptype = instancetypedef.heaptype
     #
@@ -1335,7 +1337,7 @@
         w_type = W_TypeObject(space, typedef.name, bases_w, dict_w,
                               overridetypedef=overridetypedef)
         if typedef is not overridetypedef:
-            w_type.w_doc = space.wrap(typedef.doc)
+            w_type.w_doc = space.newtext_or_none(typedef.doc)
         if hasattr(typedef, 'flag_sequence_bug_compat'):
             w_type.flag_sequence_bug_compat = typedef.flag_sequence_bug_compat
         w_type.lazyloaders = lazyloaders


More information about the pypy-commit mailing list