Author: Amaury Forgeot d'Arc <amaur...@gmail.com> Branch: py3k Changeset: r48023:689baa45b402 Date: 2011-10-13 22:38 +0200 http://bitbucket.org/pypy/pypy/changeset/689baa45b402/
Log: Add "raise ex2 from ex1" syntax (the from clause is not really used yet) - Replace old "raise type, message" syntax - various fixes around string conversions diff --git a/lib_pypy/_collections.py b/lib_pypy/_collections.py --- a/lib_pypy/_collections.py +++ b/lib_pypy/_collections.py @@ -94,7 +94,7 @@ def pop(self): if self.left is self.right and self.leftndx > self.rightndx: - raise IndexError, "pop from an empty deque" + raise IndexError("pop from an empty deque") x = self.right[self.rightndx] self.right[self.rightndx] = None self.length -= 1 @@ -115,7 +115,7 @@ def popleft(self): if self.left is self.right and self.leftndx > self.rightndx: - raise IndexError, "pop from an empty deque" + raise IndexError("pop from an empty deque") x = self.left[self.leftndx] self.left[self.leftndx] = None self.length -= 1 @@ -313,7 +313,7 @@ return type(self), (list(self), self.maxlen) def __hash__(self): - raise TypeError, "deque objects are unhashable" + raise TypeError("deque objects are unhashable") def __copy__(self): return self.__class__(self, self.maxlen) @@ -365,7 +365,7 @@ self.counter = len(deq) def giveup(): self.counter = 0 - raise RuntimeError, "deque mutated during iteration" + raise RuntimeError("deque mutated during iteration") self._gen = itergen(deq.state, giveup) def next(self): diff --git a/lib_pypy/itertools.py b/lib_pypy/itertools.py --- a/lib_pypy/itertools.py +++ b/lib_pypy/itertools.py @@ -377,7 +377,7 @@ self.step = 1 if self.start<0 or (self.stop is not None and self.stop<0 ) or self.step<=0: - raise ValueError, "indices for islice() must be positive" + raise ValueError("indices for islice() must be positive") self.it = iter(iterable) self.donext = None self.cnt = 0 diff --git a/lib_pypy/struct.py b/lib_pypy/struct.py --- a/lib_pypy/struct.py +++ b/lib_pypy/struct.py @@ -81,18 +81,18 @@ def pack_signed_int(number,size,le): if not isinstance(number, (int,long)): - raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" + raise StructError("argument for i,I,l,L,q,Q,h,H must be integer") if number > 2**(8*size-1)-1 or number < -1*2**(8*size-1): - raise OverflowError,"Number:%i too large to convert" % number + raise OverflowError("Number:%i too large to convert" % number) return pack_int(number,size,le) def pack_unsigned_int(number,size,le): if not isinstance(number, (int,long)): - raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer" + raise StructError("argument for i,I,l,L,q,Q,h,H must be integer") if number < 0: - raise TypeError,"can't convert negative long to unsigned" + raise TypeError("can't convert negative long to unsigned") if number > 2**(8*size)-1: - raise OverflowError,"Number:%i too large to convert" % number + raise OverflowError("Number:%i too large to convert" % number) return pack_int(number,size,le) def pack_char(char,size,le): @@ -296,7 +296,7 @@ try: format = formatdef[cur] except KeyError: - raise StructError,"%s is not a valid format"%cur + raise StructError("%s is not a valid format" % cur) if num != None : result += num*format['size'] else: @@ -319,7 +319,7 @@ try: format = formatdef[cur] except KeyError: - raise StructError,"%s is not a valid format"%cur + raise StructError("%s is not a valid format" % cur) if num == None : num_s = 0 num = 1 @@ -334,7 +334,7 @@ result += [args[0][:num] + '\0'*padding] args.pop(0) else: - raise StructError,"arg for string format not a string" + raise StructError("arg for string format not a string") elif cur == 'p': if isinstance(args[0], str): padding = num - len(args[0]) - 1 @@ -348,18 +348,18 @@ result += [chr(255) + args[0][:num-1]] args.pop(0) else: - raise StructError,"arg for string format not a string" + raise StructError("arg for string format not a string") else: if len(args) < num: - raise StructError,"insufficient arguments to pack" + raise StructError("insufficient arguments to pack") for var in args[:num]: result += [format['pack'](var,format['size'],endianness)] args=args[num:] num = None i += 1 if len(args) != 0: - raise StructError,"too many arguments for pack format" + raise StructError("too many arguments for pack format") return ''.join(result) def unpack(fmt,data): @@ -373,7 +373,7 @@ result = [] length= calcsize(fmt) if length != len (data): - raise StructError,"unpack str size does not match format" + raise StructError("unpack str size does not match format") while i<len(fmt): num,i=getNum(fmt,i) cur = fmt[i] @@ -381,7 +381,7 @@ try: format = formatdef[cur] except KeyError: - raise StructError,"%s is not a valid format"%cur + raise StructError("%s is not a valid format" % cur) if not num : num = 1 diff --git a/pypy/interpreter/astcompiler/ast.py b/pypy/interpreter/astcompiler/ast.py --- a/pypy/interpreter/astcompiler/ast.py +++ b/pypy/interpreter/astcompiler/ast.py @@ -723,44 +723,37 @@ class Raise(stmt): - _lineno_mask = 8 - _col_offset_mask = 16 - - def __init__(self, type, inst, tback, lineno, col_offset): - self.type = type - self.inst = inst - self.tback = tback + _lineno_mask = 4 + _col_offset_mask = 8 + + def __init__(self, exc, cause, lineno, col_offset): + self.exc = exc + self.cause = cause stmt.__init__(self, lineno, col_offset) - self.initialization_state = 31 + self.initialization_state = 15 def walkabout(self, visitor): visitor.visit_Raise(self) def mutate_over(self, visitor): - if self.type: - self.type = self.type.mutate_over(visitor) - if self.inst: - self.inst = self.inst.mutate_over(visitor) - if self.tback: - self.tback = self.tback.mutate_over(visitor) + if self.exc: + self.exc = self.exc.mutate_over(visitor) + if self.cause: + self.cause = self.cause.mutate_over(visitor) return visitor.visit_Raise(self) def sync_app_attrs(self, space): - if (self.initialization_state & ~7) ^ 24: - missing_field(space, self.initialization_state, [None, None, None, 'lineno', 'col_offset'], 'Raise') + if (self.initialization_state & ~3) ^ 12: + missing_field(space, self.initialization_state, [None, None, 'lineno', 'col_offset'], 'Raise') else: if not self.initialization_state & 1: - self.type = None + self.exc = None if not self.initialization_state & 2: - self.inst = None - if not self.initialization_state & 4: - self.tback = None - if self.type: - self.type.sync_app_attrs(space) - if self.inst: - self.inst.sync_app_attrs(space) - if self.tback: - self.tback.sync_app_attrs(space) + self.cause = None + if self.exc: + self.exc.sync_app_attrs(space) + if self.cause: + self.cause.sync_app_attrs(space) class TryExcept(stmt): @@ -2686,12 +2679,10 @@ self.visit_sequence(node.body) def visit_Raise(self, node): - if node.type: - node.type.walkabout(self) - if node.inst: - node.inst.walkabout(self) - if node.tback: - node.tback.walkabout(self) + if node.exc: + node.exc.walkabout(self) + if node.cause: + node.cause.walkabout(self) def visit_TryExcept(self, node): self.visit_sequence(node.body) @@ -3991,79 +3982,57 @@ __init__=interp2app(With_init), ) -def Raise_get_type(space, w_self): +def Raise_get_exc(space, w_self): if w_self.w_dict is not None: - w_obj = w_self.getdictvalue(space, 'type') + w_obj = w_self.getdictvalue(space, 'exc') if w_obj is not None: return w_obj if not w_self.initialization_state & 1: typename = space.type(w_self).getname(space) - w_err = space.wrap("'%s' object has no attribute 'type'" % typename) + w_err = space.wrap("'%s' object has no attribute 'exc'" % typename) raise OperationError(space.w_AttributeError, w_err) - return space.wrap(w_self.type) - -def Raise_set_type(space, w_self, w_new_value): + return space.wrap(w_self.exc) + +def Raise_set_exc(space, w_self, w_new_value): try: - w_self.type = space.interp_w(expr, w_new_value, True) + w_self.exc = space.interp_w(expr, w_new_value, True) except OperationError, e: if not e.match(space, space.w_TypeError): raise - w_self.setdictvalue(space, 'type', w_new_value) + w_self.setdictvalue(space, 'exc', w_new_value) return - w_self.deldictvalue(space, 'type') + w_self.deldictvalue(space, 'exc') w_self.initialization_state |= 1 -def Raise_get_inst(space, w_self): +def Raise_get_cause(space, w_self): if w_self.w_dict is not None: - w_obj = w_self.getdictvalue(space, 'inst') + w_obj = w_self.getdictvalue(space, 'cause') if w_obj is not None: return w_obj if not w_self.initialization_state & 2: typename = space.type(w_self).getname(space) - w_err = space.wrap("'%s' object has no attribute 'inst'" % typename) + w_err = space.wrap("'%s' object has no attribute 'cause'" % typename) raise OperationError(space.w_AttributeError, w_err) - return space.wrap(w_self.inst) - -def Raise_set_inst(space, w_self, w_new_value): + return space.wrap(w_self.cause) + +def Raise_set_cause(space, w_self, w_new_value): try: - w_self.inst = space.interp_w(expr, w_new_value, True) + w_self.cause = space.interp_w(expr, w_new_value, True) except OperationError, e: if not e.match(space, space.w_TypeError): raise - w_self.setdictvalue(space, 'inst', w_new_value) + w_self.setdictvalue(space, 'cause', w_new_value) return - w_self.deldictvalue(space, 'inst') + w_self.deldictvalue(space, 'cause') w_self.initialization_state |= 2 -def Raise_get_tback(space, w_self): - if w_self.w_dict is not None: - w_obj = w_self.getdictvalue(space, 'tback') - if w_obj is not None: - return w_obj - if not w_self.initialization_state & 4: - typename = space.type(w_self).getname(space) - w_err = space.wrap("'%s' object has no attribute 'tback'" % typename) - raise OperationError(space.w_AttributeError, w_err) - return space.wrap(w_self.tback) - -def Raise_set_tback(space, w_self, w_new_value): - try: - w_self.tback = space.interp_w(expr, w_new_value, True) - except OperationError, e: - if not e.match(space, space.w_TypeError): - raise - w_self.setdictvalue(space, 'tback', w_new_value) - return - w_self.deldictvalue(space, 'tback') - w_self.initialization_state |= 4 - -_Raise_field_unroller = unrolling_iterable(['type', 'inst', 'tback']) +_Raise_field_unroller = unrolling_iterable(['exc', 'cause']) def Raise_init(space, w_self, __args__): w_self = space.descr_self_interp_w(Raise, w_self) args_w, kwargs_w = __args__.unpack() if args_w: - if len(args_w) != 3: - w_err = space.wrap("Raise constructor takes either 0 or 3 positional arguments") + if len(args_w) != 2: + w_err = space.wrap("Raise constructor takes either 0 or 2 positional arguments") raise OperationError(space.w_TypeError, w_err) i = 0 for field in _Raise_field_unroller: @@ -4075,10 +4044,9 @@ Raise.typedef = typedef.TypeDef("Raise", stmt.typedef, __module__='_ast', - _fields=_FieldsWrapper(['type', 'inst', 'tback']), - type=typedef.GetSetProperty(Raise_get_type, Raise_set_type, cls=Raise), - inst=typedef.GetSetProperty(Raise_get_inst, Raise_set_inst, cls=Raise), - tback=typedef.GetSetProperty(Raise_get_tback, Raise_set_tback, cls=Raise), + _fields=_FieldsWrapper(['exc', 'cause']), + exc=typedef.GetSetProperty(Raise_get_exc, Raise_set_exc, cls=Raise), + cause=typedef.GetSetProperty(Raise_get_cause, Raise_set_cause, cls=Raise), __new__=interp2app(get_AST_new(Raise)), __init__=interp2app(Raise_init), ) 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 @@ -149,17 +149,13 @@ return ast.Return(values, flow_node.lineno, flow_node.column) elif first_child_type == syms.raise_stmt: exc = None - value = None - traceback = None + cause = None child_count = len(first_child.children) if child_count >= 2: exc = self.handle_expr(first_child.children[1]) if child_count >= 4: - value = self.handle_expr(first_child.children[3]) - if child_count == 6: - traceback = self.handle_expr(first_child.children[5]) - return ast.Raise(exc, value, traceback, flow_node.lineno, - flow_node.column) + cause = self.handle_expr(first_child.children[3]) + return ast.Raise(exc, cause, flow_node.lineno, flow_node.column) else: raise AssertionError("unknown flow statement") 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 @@ -746,15 +746,12 @@ def visit_Raise(self, rais): self.update_position(rais.lineno, True) arg = 0 - if rais.type: - rais.type.walkabout(self) + if rais.exc: + rais.exc.walkabout(self) arg += 1 - if rais.inst: - rais.inst.walkabout(self) + if rais.cause: + rais.cause.walkabout(self) arg += 1 - if rais.tback: - rais.tback.walkabout(self) - arg += 1 self.emit_op_arg(ops.RAISE_VARARGS, arg) def visit_Global(self, glob): diff --git a/pypy/interpreter/astcompiler/test/test_compiler.py b/pypy/interpreter/astcompiler/test/test_compiler.py --- a/pypy/interpreter/astcompiler/test/test_compiler.py +++ b/pypy/interpreter/astcompiler/test/test_compiler.py @@ -797,6 +797,17 @@ return y""" yield self.st, test, "f()", 4 + def test_raise_from(self): + test = """if 1: + def f(): + try: + raise TypeError() from ValueError() + except TypeError: + return 42 + """ + yield self.st, test, "f()", 42 + # This line is needed for py.code to find the source. + class AppTestCompiler: diff --git a/pypy/interpreter/astcompiler/tools/Python.asdl b/pypy/interpreter/astcompiler/tools/Python.asdl --- a/pypy/interpreter/astcompiler/tools/Python.asdl +++ b/pypy/interpreter/astcompiler/tools/Python.asdl @@ -30,8 +30,7 @@ | If(expr test, stmt* body, stmt* orelse) | With(expr context_expr, expr? optional_vars, stmt* body) - -- 'type' is a bad name - | Raise(expr? type, expr? inst, expr? tback) + | Raise(expr? exc, expr? cause) | TryExcept(stmt* body, excepthandler* handlers, stmt* orelse) | TryFinally(stmt* body, stmt* finalbody) | Assert(expr test, expr? msg) diff --git a/pypy/interpreter/baseobjspace.py b/pypy/interpreter/baseobjspace.py --- a/pypy/interpreter/baseobjspace.py +++ b/pypy/interpreter/baseobjspace.py @@ -1219,7 +1219,7 @@ # unclear if there is any use at all for getting the bytes in # the unicode buffer.) try: - return self.str_w(w_obj) + return self.bytes_w(w_obj) except OperationError, e: if not e.match(self, self.w_TypeError): raise @@ -1254,6 +1254,10 @@ return self.str_w(w_obj) def unicode_w(self, w_obj): + if not we_are_translated(): + if self.isinstance_w(w_obj, self.w_bytes): + import pdb; pdb.set_trace() + assert False, "unicode_w was called with a bytes string" return w_obj.unicode_w(self) def realunicode_w(self, w_obj): diff --git a/pypy/interpreter/pyopcode.py b/pypy/interpreter/pyopcode.py --- a/pypy/interpreter/pyopcode.py +++ b/pypy/interpreter/pyopcode.py @@ -489,15 +489,14 @@ self.last_exception = operror raise Reraise - w_value = w_traceback = space.w_None - if nbargs >= 3: - w_traceback = self.popvalue() + w_value = w_cause = space.w_None if nbargs >= 2: + w_cause = self.popvalue() # XXX cause? + if 1: w_value = self.popvalue() - if 1: - w_type = self.popvalue() - operror = OperationError(w_type, w_value) + operror = OperationError(space.type(w_value), w_value) operror.normalize_exception(space) + w_traceback = space.w_None # XXX with_traceback? if not space.full_exceptions or space.is_w(w_traceback, space.w_None): # common case raise operror diff --git a/pypy/interpreter/pyparser/data/Grammar3.2 b/pypy/interpreter/pyparser/data/Grammar3.2 --- a/pypy/interpreter/pyparser/data/Grammar3.2 +++ b/pypy/interpreter/pyparser/data/Grammar3.2 @@ -49,7 +49,7 @@ continue_stmt: 'continue' return_stmt: 'return' [testlist] yield_stmt: yield_expr -raise_stmt: 'raise' [test [',' test [',' test]]] +raise_stmt: 'raise' [test ['from' test]] import_stmt: import_name | import_from import_name: 'import' dotted_as_names import_from: ('from' ('.'* dotted_name | '.'+) 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 @@ -135,7 +135,7 @@ if e.match(space, space.w_UnicodeDecodeError): e.normalize_exception(space) w_message = space.str(e.get_w_value(space)) - raise error.SyntaxError(space.text_w(w_message)) + raise error.SyntaxError(space.str_w(w_message)) raise f_flags, future_info = future.get_futures(self.future_flags, textsrc) diff --git a/pypy/module/__builtin__/app_inspect.py b/pypy/module/__builtin__/app_inspect.py --- a/pypy/module/__builtin__/app_inspect.py +++ b/pypy/module/__builtin__/app_inspect.py @@ -19,12 +19,12 @@ if len(obj) == 0: return _caller_locals() elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." + raise TypeError("vars() takes at most 1 argument.") else: try: return obj[0].__dict__ except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" + raise TypeError("vars() argument must have __dict__ attribute") # Replaced by the interp-level helper space.callable(): ##def callable(ob): diff --git a/pypy/module/exceptions/interp_exceptions.py b/pypy/module/exceptions/interp_exceptions.py --- a/pypy/module/exceptions/interp_exceptions.py +++ b/pypy/module/exceptions/interp_exceptions.py @@ -631,11 +631,11 @@ def descr_init(self, space, w_encoding, w_object, w_start, w_end, w_reason): # typechecking - space.text_w(w_encoding) - space.str_w(w_object) + space.str_w(w_encoding) + space.bytes_w(w_object) space.int_w(w_start) space.int_w(w_end) - space.text_w(w_reason) + space.str_w(w_reason) # assign attributes self.w_encoding = w_encoding self.w_object = w_object @@ -650,7 +650,7 @@ if self.end == self.start + 1: return "'%s' codec can't decode byte 0x%02x in position %d: %s"%( self.encoding, - ord(self.object[self.start]), self.start, self.reason) + self.object[self.start], self.start, self.reason) return "'%s' codec can't decode bytes in position %d-%d: %s" % ( self.encoding, self.start, self.end - 1, self.reason) """) diff --git a/pypy/module/imp/importing.py b/pypy/module/imp/importing.py --- a/pypy/module/imp/importing.py +++ b/pypy/module/imp/importing.py @@ -964,7 +964,7 @@ """ Read a code object from a file and check it for validity """ w_marshal = space.getbuiltinmodule('marshal') - w_code = space.call_method(w_marshal, 'loads', space.wrap(strbuf)) + w_code = space.call_method(w_marshal, 'loads', space.wrapbytes(strbuf)) pycode = space.interpclass_w(w_code) if pycode is None or not isinstance(pycode, Code): raise operationerrfmt(space.w_ImportError, @@ -1008,9 +1008,9 @@ """ w_marshal = space.getbuiltinmodule('marshal') try: - w_str = space.call_method(w_marshal, 'dumps', space.wrap(co), - space.wrap(MARSHAL_VERSION_FOR_PYC)) - strbuf = space.str_w(w_str) + w_bytes = space.call_method(w_marshal, 'dumps', space.wrap(co), + space.wrap(MARSHAL_VERSION_FOR_PYC)) + strbuf = space.bytes_w(w_bytes) except OperationError, e: if e.async(space): raise diff --git a/pypy/module/operator/app_operator.py b/pypy/module/operator/app_operator.py --- a/pypy/module/operator/app_operator.py +++ b/pypy/module/operator/app_operator.py @@ -21,7 +21,7 @@ if x == b: return index index += 1 - raise ValueError, 'sequence.index(x): x not in sequence' + raise ValueError('sequence.index(x): x not in sequence') # XXX the following is approximative def isMappingType(obj,): @@ -40,9 +40,9 @@ def repeat(obj, num): 'repeat(a, b) -- Return a * b, where a is a sequence, and b is an integer.' if not isinstance(num, (int, long)): - raise TypeError, 'an integer is required' + raise TypeError('an integer is required') if not isSequenceType(obj): - raise TypeError, "non-sequence object can't be repeated" + raise TypeError("non-sequence object can't be repeated") return obj * num diff --git a/pypy/module/posix/app_posix.py b/pypy/module/posix/app_posix.py --- a/pypy/module/posix/app_posix.py +++ b/pypy/module/posix/app_posix.py @@ -191,7 +191,7 @@ except Exception, e: try_close(write_end) try_close(read_end) - raise Exception, e # bare 'raise' does not work here :-( + raise Exception() from e def wait(): """ wait() -> (pid, status) diff --git a/pypy/module/sys/app.py b/pypy/module/sys/app.py --- a/pypy/module/sys/app.py +++ b/pypy/module/sys/app.py @@ -54,7 +54,7 @@ # note that we cannot use SystemExit(exitcode) here. # The comma version leads to an extra de-tupelizing # in normalize_exception, which is exactly like CPython's. - raise SystemExit, exitcode + raise SystemExit(exitcode) #import __builtin__ 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 @@ -249,7 +249,7 @@ marshal_w__Rope = marshal_w__String def unmarshal_String(space, u, tc): - return space.wrap(u.get_str()) + return space.wrapbytes(u.get_str()) register(TYPE_STRING, unmarshal_String) def unmarshal_stringref(space, u, tc): @@ -336,7 +336,7 @@ def unmarshal_str(u): w_obj = u.get_w_obj() try: - return u.space.str_w(w_obj) + return u.space.bytes_w(w_obj) except OperationError, e: if e.match(u.space, u.space.w_TypeError): u.raise_exc('invalid marshal data for code object') diff --git a/pypy/objspace/std/unicodeobject.py b/pypy/objspace/std/unicodeobject.py --- a/pypy/objspace/std/unicodeobject.py +++ b/pypy/objspace/std/unicodeobject.py @@ -75,8 +75,7 @@ return ''.join(result) def str__Unicode(space, w_uni): - from pypy.objspace.std.unicodetype import encode_object - return encode_object(space, w_uni, None, None) + return w_uni def eq__Unicode_Unicode(space, w_left, w_right): return space.newbool(w_left._value == w_right._value) _______________________________________________ pypy-commit mailing list pypy-commit@python.org http://mail.python.org/mailman/listinfo/pypy-commit