drop py paramater for protcol definitions

This commit is contained in:
Nikolay Kim 2017-06-22 12:32:01 -07:00
parent cb969161c6
commit 00bd5615ed
23 changed files with 431 additions and 530 deletions

View File

@ -62,7 +62,6 @@ pub fn impl_method_proto(cls: &Box<syn::Ty>,
-> <#cls as #p<'p>>::Result {}}.as_str()).unwrap());
sig.decl.output = tmp.output.clone();
modify_self_ty(sig);
modify_py_ty(sig);
if pyres {
quote! {
@ -80,13 +79,13 @@ pub fn impl_method_proto(cls: &Box<syn::Ty>,
}
},
MethodProto::Binary{name: n, arg, pyres, proto} => {
if sig.decl.inputs.len() <= 2 {
if sig.decl.inputs.len() <= 1 {
println!("Not enough arguments for {}", n);
return Tokens::new();
}
let p = syn::Ident::from(proto);
let arg_name = syn::Ident::from(arg);
let arg_ty = get_arg_ty(sig, 2);
let arg_ty = get_arg_ty(sig, 1);
let (ty, succ) = get_res_success(ty);
let tmp = extract_decl(syn::parse_item(
@ -99,9 +98,8 @@ pub fn impl_method_proto(cls: &Box<syn::Ty>,
&self,
arg: Option<<#cls as #p<'p>>::#arg_name>)
-> <#cls as #p<'p>>::Result {}}.as_str()).unwrap());
modify_arg_ty(sig, 2, &tmp, &tmp2);
modify_arg_ty(sig, 1, &tmp, &tmp2);
modify_self_ty(sig);
modify_py_ty(sig);
if pyres {
quote! {
@ -121,15 +119,15 @@ pub fn impl_method_proto(cls: &Box<syn::Ty>,
}
},
MethodProto::Ternary{name: n, arg1, arg2, pyres, proto} => {
if sig.decl.inputs.len() <= 3 {
if sig.decl.inputs.len() <= 2 {
print_err(format!("Not enough arguments {}", n), quote!(sig));
return Tokens::new();
}
let p = syn::Ident::from(proto);
let arg1_name = syn::Ident::from(arg1);
let arg1_ty = get_arg_ty(sig, 2);
let arg1_ty = get_arg_ty(sig, 1);
let arg2_name = syn::Ident::from(arg2);
let arg2_ty = get_arg_ty(sig, 3);
let arg2_ty = get_arg_ty(sig, 2);
let (ty, succ) = get_res_success(ty);
// rewrite ty
@ -145,10 +143,9 @@ pub fn impl_method_proto(cls: &Box<syn::Ty>,
arg1: Option<<#cls as #p<'p>>::#arg1_name>,
arg2: Option<<#cls as #p<'p>>::#arg2_name>)
-> <#cls as #p<'p>>::Result {}}.as_str()).unwrap());
modify_arg_ty(sig, 1, &tmp, &tmp2);
modify_arg_ty(sig, 2, &tmp, &tmp2);
modify_arg_ty(sig, 3, &tmp, &tmp2);
modify_self_ty(sig);
modify_py_ty(sig);
if pyres {
quote! {
@ -170,17 +167,17 @@ pub fn impl_method_proto(cls: &Box<syn::Ty>,
}
},
MethodProto::Quaternary{name: n, arg1, arg2, arg3, proto} => {
if sig.decl.inputs.len() <= 4 {
if sig.decl.inputs.len() <= 3 {
print_err(format!("Not enough arguments {}", n), quote!(sig));
return Tokens::new();
}
let p = syn::Ident::from(proto);
let arg1_name = syn::Ident::from(arg1);
let arg1_ty = get_arg_ty(sig, 2);
let arg1_ty = get_arg_ty(sig, 1);
let arg2_name = syn::Ident::from(arg2);
let arg2_ty = get_arg_ty(sig, 3);
let arg2_ty = get_arg_ty(sig, 2);
let arg3_name = syn::Ident::from(arg3);
let arg3_ty = get_arg_ty(sig, 4);
let arg3_ty = get_arg_ty(sig, 3);
let (ty, succ) = get_res_success(ty);
// rewrite ty
@ -198,11 +195,10 @@ pub fn impl_method_proto(cls: &Box<syn::Ty>,
arg2: Option<<#cls as #p<'p>>::#arg2_name>,
arg3: Option<<#cls as #p<'p>>::#arg3_name>)
-> <#cls as #p<'p>>::Result {}}.as_str()).unwrap());
modify_arg_ty(sig, 1, &tmp, &tmp2);
modify_arg_ty(sig, 2, &tmp, &tmp2);
modify_arg_ty(sig, 3, &tmp, &tmp2);
modify_arg_ty(sig, 4, &tmp, &tmp2);
modify_self_ty(sig);
modify_py_ty(sig);
quote! {
impl<'p> #p<'p> for #cls {
@ -338,13 +334,13 @@ fn modify_arg_ty(sig: &mut syn::MethodSig, idx: usize,
&syn::Ty::Path(_, ref path) => {
let seg = path.segments.last().unwrap().clone();
if seg.ident.as_ref() == "Option" {
sig.decl.inputs[idx] = fix_name(pat, &decl2.inputs[idx-1]);
sig.decl.inputs[idx] = fix_name(pat, &decl2.inputs[idx]);
} else {
sig.decl.inputs[idx] = fix_name(pat, &decl1.inputs[idx-1]);
sig.decl.inputs[idx] = fix_name(pat, &decl1.inputs[idx]);
}
},
_ => {
sig.decl.inputs[idx] = fix_name(pat, &decl1.inputs[idx-1]);
sig.decl.inputs[idx] = fix_name(pat, &decl1.inputs[idx]);
}
}
},
@ -364,41 +360,6 @@ fn modify_self_ty(sig: &mut syn::MethodSig)
}
}
// modify Python signature
fn modify_py_ty(sig: &mut syn::MethodSig)
{
if sig.decl.inputs.len() <= 1 {
return
}
match sig.decl.inputs[1] {
syn::FnArg::Captured(_, ref mut arg_ty) => {
match arg_ty {
&mut syn::Ty::Path(_, ref mut path) => {
let last = path.segments.len()-1;
let seg = path.segments[last].clone();
if seg.ident.as_ref() == "Python" {
if let syn::PathParameters::AngleBracketed(ref data) = seg.parameters {
path.segments[last] = syn::PathSegment{
ident: seg.ident.clone(),
parameters: syn::PathParameters::AngleBracketed(
syn::AngleBracketedParameterData{
lifetimes: vec![syn::Lifetime {
ident: syn::Ident::from("'p")}],
types: data.types.clone(),
bindings: data.bindings.clone(),
})
}
}
}
},
_ => (),
}
},
_ => panic!("not supported"),
}
}
fn fix_name(pat: &syn::Pat, arg: &syn::FnArg) -> syn::FnArg {
match arg {
&syn::FnArg::Captured(_, ref arg_ty) =>

View File

@ -13,6 +13,7 @@ pub struct FnArg<'a> {
pub mode: &'a syn::BindingMode,
pub ty: &'a syn::Ty,
pub optional: Option<&'a syn::Ty>,
pub py: bool,
}
#[derive(Clone, PartialEq, Debug)]
@ -42,7 +43,6 @@ impl<'a> FnSpec<'a> {
let (fn_type, fn_attrs) = parse_attributes(meth_attrs);
let mut has_self = false;
let mut py = false;
let mut arguments = Vec::new();
for input in sig.decl.inputs.iter() {
@ -67,21 +67,26 @@ impl<'a> FnSpec<'a> {
panic!("unsupported argument: {:?}", pat),
};
if !py {
match ty {
&syn::Ty::Path(_, ref path) =>
if let Some(segment) = path.segments.last() {
if segment.ident.as_ref() == "Python" {
py = true;
continue;
}
},
_ => (),
}
}
let py = match ty {
&syn::Ty::Path(_, ref path) =>
if let Some(segment) = path.segments.last() {
segment.ident.as_ref() == "Python"
} else {
false
},
_ => false
};
let opt = check_arg_ty_and_optional(name, ty);
arguments.push(FnArg{name: ident, mode: mode, ty: ty, optional: opt});
arguments.push(
FnArg {
name: ident,
mode: mode,
ty: ty,
optional: opt,
py: py,
}
);
}
&syn::FnArg::Ignored(_) =>
panic!("ignored argument: {:?}", name),

View File

@ -200,7 +200,6 @@ fn wrap_fn(item: &mut syn::Item) -> Option<Box<syn::Block>> {
match item.node {
syn::ItemKind::Fn(ref decl, _, _, _, _, _) => {
let mut py = false;
let mut arguments = Vec::new();
for input in decl.inputs.iter() {
@ -214,24 +213,22 @@ fn wrap_fn(item: &mut syn::Item) -> Option<Box<syn::Block>> {
panic!("unsupported argument: {:?}", pat),
};
if !py {
match ty {
&syn::Ty::Path(_, ref path) =>
if let Some(segment) = path.segments.last() {
if segment.ident.as_ref() == "Python" {
py = true;
continue;
}
},
_ => (),
}
}
let py = match ty {
&syn::Ty::Path(_, ref path) =>
if let Some(segment) = path.segments.last() {
segment.ident.as_ref() == "Python"
} else {
false
},
_ => false
};
let opt = method::check_arg_ty_and_optional(&name, ty);
arguments.push(method::FnArg {name: ident,
mode: mode,
ty: ty,
optional: opt});
optional: opt,
py: py});
}
&syn::FnArg::Ignored(_) =>
panic!("ignored argument: {:?}", name),
@ -302,9 +299,10 @@ fn wrap_fn(item: &mut syn::Item) -> Option<Box<syn::Block>> {
/// Generate static method wrapper (PyCFunction, PyCFunctionWithKeywords)
pub fn impl_wrap(name: &syn::Ident, spec: &method::FnSpec) -> Tokens {
let names: Vec<&syn::Ident> = spec.args.iter().map(|item| item.name).collect();
let names: Vec<syn::Ident> = spec.args.iter().map(
|item| if item.py {syn::Ident::from("py")} else {item.name.clone()}).collect();
let cb = quote! {{
#name(py, #(#names),*)
#name(#(#names),*)
}};
let body = py_method::impl_arg_params(spec, cb);

View File

@ -188,13 +188,12 @@ fn impl_class(cls: &syn::Ident, base: &syn::Ident,
if (ty.tp_flags & _pyo3::ffi::Py_TPFLAGS_READY) == 0 {
// automatically initialize the class on-demand
let to = _pyo3::typeob::initialize_type::<#cls>(
_pyo3::typeob::initialize_type::<#cls>(
py, None, <#cls as _pyo3::typeob::PyTypeInfo>::type_name(),
<#cls as _pyo3::typeob::PyTypeInfo>::type_description(), ty).expect(
format!("An error occurred while initializing class {}",
<#cls as _pyo3::typeob::PyTypeInfo>::type_name())
.as_ref());
py.release(to);
}
});
}

View File

@ -55,7 +55,7 @@ fn impl_methods(ty: &Box<syn::Ty>, impls: &mut Vec<syn::ImplItem>) -> Tokens {
quote! {
#[feature(specialization)]
#[allow(non_upper_case_globals, unused_attributes,
unused_qualifications, unused_variables)]
unused_qualifications, unused_variables, unused_imports)]
const #dummy_const: () = {
extern crate pyo3 as _pyo3;

View File

@ -120,9 +120,10 @@ pub fn impl_proto_wrap(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) ->
/// Generate class method wrapper (PyCFunction, PyCFunctionWithKeywords)
pub fn impl_wrap_type(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tokens {
let names: Vec<&syn::Ident> = spec.args.iter().map(|item| item.name).collect();
let names: Vec<syn::Ident> = spec.args.iter().map(
|item| if item.py {syn::Ident::from("py")} else {item.name.clone()}).collect();
let cb = quote! {{
#cls::#name(&cls, py, #(#names),*)
#cls::#name(&cls, #(#names),*)
}};
let body = impl_arg_params(spec, cb);
@ -153,9 +154,10 @@ pub fn impl_wrap_type(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> T
/// Generate class method wrapper (PyCFunction, PyCFunctionWithKeywords)
pub fn impl_wrap_class(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tokens {
let names: Vec<&syn::Ident> = spec.args.iter().map(|item| item.name).collect();
let names: Vec<syn::Ident> = spec.args.iter().map(
|item| if item.py {syn::Ident::from("py")} else {item.name.clone()}).collect();
let cb = quote! {{
#cls::#name(&cls, py, #(#names),*)
#cls::#name(&cls, #(#names),*)
}};
let body = impl_arg_params(spec, cb);
let output = &spec.output;
@ -185,9 +187,10 @@ pub fn impl_wrap_class(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) ->
/// Generate static method wrapper (PyCFunction, PyCFunctionWithKeywords)
pub fn impl_wrap_static(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tokens {
let names: Vec<&syn::Ident> = spec.args.iter().map(|item| item.name).collect();
let names: Vec<syn::Ident> = spec.args.iter().map(
|item| if item.py {syn::Ident::from("py")} else {item.name.clone()}).collect();
let cb = quote! {{
#cls::#name(py, #(#names),*)
#cls::#name(#(#names),*)
}};
let body = impl_arg_params(spec, cb);
@ -226,8 +229,8 @@ fn impl_wrap_getter(cls: &Box<syn::Ty>, name: &syn::Ident, _spec: &FnSpec) -> To
stringify!(#cls), ".getter_", stringify!(#name), "()");
_pyo3::callback::cb_unary::<#cls, _, _, _>(
LOCATION, slf, _pyo3::callback::PyObjectCallbackConverter, |py, slf| {
slf.#name(py)
})
slf.#name()
})
}
}
}
@ -252,7 +255,7 @@ fn impl_wrap_setter(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tok
let value = py.cast_from_borrowed_ptr(value);
let result = match <#val_ty as _pyo3::FromPyObject>::extract(value) {
Ok(val) => slf.#name(py, val),
Ok(val) => slf.#name(val),
Err(e) => Err(e)
};
match result {
@ -269,20 +272,26 @@ fn impl_wrap_setter(cls: &Box<syn::Ty>, name: &syn::Ident, spec: &FnSpec) -> Tok
fn impl_call(_cls: &Box<syn::Ty>, fname: &syn::Ident, spec: &FnSpec) -> Tokens {
let names: Vec<&syn::Ident> = spec.args.iter().map(|item| item.name).collect();
let names: Vec<syn::Ident> = spec.args.iter().map(
|item| if item.py {syn::Ident::from("py")} else {item.name.clone()}).collect();
quote! {{
slf.#fname(py, #(#names),*)
slf.#fname(#(#names),*)
}}
}
pub fn impl_arg_params(spec: &FnSpec, body: Tokens) -> Tokens {
if spec.args.is_empty() {
let args: Vec<FnArg> = spec.args.iter()
.filter(|item| !item.py).map(|item| item.clone()).collect();
if args.is_empty() {
return body
}
let mut params = Vec::new();
for arg in spec.args.iter() {
if arg.py {
continue
}
if ! (spec.is_args(&arg.name) || spec.is_kwargs(&arg.name)) {
let name = arg.name.as_ref();
let kwonly = if spec.is_kw_only(&arg.name) {
@ -330,7 +339,7 @@ pub fn impl_arg_params(spec: &FnSpec, body: Tokens) -> Tokens {
];
let mut output = [#(#placeholders),*];
let result = match _pyo3::argparse::parse_args(
match _pyo3::argparse::parse_args(
py, Some(LOCATION), PARAMS, &args,
kwargs, #accept_args, #accept_kwargs, &mut output)
{
@ -340,18 +349,14 @@ pub fn impl_arg_params(spec: &FnSpec, body: Tokens) -> Tokens {
#body
},
Err(err) => Err(err)
};
for p in output.iter_mut() {
if let Some(ob) = p.take() {
py.release(ob);
}
}
result
}
}
fn impl_arg_param(arg: &FnArg, spec: &FnSpec, body: &Tokens) -> Tokens {
if arg.py {
return body.clone()
}
let ty = arg.ty;
let name = arg.name;

View File

@ -16,7 +16,7 @@ pub struct ParamDescription<'a> {
/// Whether the parameter is optional.
pub is_optional: bool,
/// Whether the parameter is optional.
pub kw_only: bool
pub kw_only: bool,
}
/// Parse argument list
@ -33,7 +33,7 @@ pub fn parse_args<'p>(py: Python<'p>,
accept_args: bool, accept_kwargs: bool,
output: &mut[Option<&'p PyObject>]) -> PyResult<()>
{
assert!(params.len() == output.len());
let nargs = args.len();
let nkeywords = kwargs.map_or(0, |d| d.len());

View File

@ -10,7 +10,7 @@
use ffi;
use err::PyResult;
use python::Python;
use python::PyDowncastFrom;
use callback::PyObjectCallbackConverter;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
@ -20,21 +20,21 @@ use class::methods::PyMethodDef;
///
/// Each method in this trait corresponds to Python async/await implementation.
#[allow(unused_variables)]
pub trait PyAsyncProtocol<'p>: PyTypeInfo + Sized + 'static {
pub trait PyAsyncProtocol<'p>: PyTypeInfo + PyDowncastFrom {
fn __await__(&'p self, py: Python<'p>)
fn __await__(&'p self)
-> Self::Result where Self: PyAsyncAwaitProtocol<'p> { unimplemented!() }
fn __aiter__(&'p self, py: Python<'p>)
fn __aiter__(&'p self)
-> Self::Result where Self: PyAsyncAiterProtocol<'p> { unimplemented!() }
fn __anext__(&'p mut self, py: Python<'p>)
fn __anext__(&'p mut self)
-> Self::Result where Self: PyAsyncAnextProtocol<'p> { unimplemented!() }
fn __aenter__(&'p mut self, py: Python<'p>)
fn __aenter__(&'p mut self)
-> Self::Result where Self: PyAsyncAenterProtocol<'p> { unimplemented!() }
fn __aexit__(&'p mut self, py: Python<'p>,
fn __aexit__(&'p mut self,
exc_type: Option<Self::ExcType>,
exc_value: Option<Self::ExcValue>,
traceback: Option<Self::Traceback>)

View File

@ -13,12 +13,11 @@ use ::CompareOp;
use ffi;
use callback;
use err::{PyErr, PyResult};
use python::{Python, IntoPyPointer};
use pointer::PyObjectPtr;
use objects::exc;
use instance::{Py, AsPyRef};
use python::{Python, IntoPyPointer, PyDowncastFrom};
use objects::{exc, PyObject};
use typeob::PyTypeInfo;
use conversion::{FromPyObject, IntoPyObject};
use objectprotocol::ObjectProtocol;
use callback::{PyObjectCallbackConverter, HashConverter, BoolCallbackConverter};
use class::methods::PyMethodDef;
@ -28,40 +27,40 @@ use class::methods::PyMethodDef;
/// Basic python class customization
#[allow(unused_variables)]
pub trait PyObjectProtocol<'p>: PyTypeInfo + Sized + 'static {
pub trait PyObjectProtocol<'p>: PyTypeInfo + PyDowncastFrom + Sized + 'static {
fn __getattr__(&'p self, py: Python<'p>, name: Self::Name)
fn __getattr__(&'p self, name: Self::Name)
-> Self::Result where Self: PyObjectGetAttrProtocol<'p> {unimplemented!()}
fn __setattr__(&'p mut self, py: Python<'p>, name: Self::Name, value: Self::Value)
fn __setattr__(&'p mut self, name: Self::Name, value: Self::Value)
-> Self::Result where Self: PyObjectSetAttrProtocol<'p> {unimplemented!()}
fn __delattr__(&'p mut self, py: Python<'p>, name: Self::Name)
fn __delattr__(&'p mut self, name: Self::Name)
-> Self::Result where Self: PyObjectDelAttrProtocol<'p> {unimplemented!()}
fn __str__(&'p self, py: Python<'p>)
fn __str__(&'p self)
-> Self::Result where Self: PyObjectStrProtocol<'p> {unimplemented!()}
fn __repr__(&'p self, py: Python<'p>)
fn __repr__(&'p self)
-> Self::Result where Self: PyObjectReprProtocol<'p> {unimplemented!()}
fn __format__(&'p self, py: Python<'p>, format_spec: Self::Format)
fn __format__(&'p self, format_spec: Self::Format)
-> Self::Result where Self: PyObjectFormatProtocol<'p> {unimplemented!()}
fn __hash__(&'p self, py: Python<'p>)
fn __hash__(&'p self)
-> Self::Result where Self: PyObjectHashProtocol<'p> {unimplemented!()}
fn __bool__(&'p self, py: Python<'p>)
fn __bool__(&'p self)
-> Self::Result where Self: PyObjectBoolProtocol<'p> {unimplemented!()}
fn __bytes__(&'p self, py: Python<'p>)
fn __bytes__(&'p self)
-> Self::Result where Self: PyObjectBytesProtocol<'p> {unimplemented!()}
/// This method is used by Python2 only.
fn __unicode__(&'p self, py: Python<'p>)
fn __unicode__(&'p self)
-> Self::Result where Self: PyObjectUnicodeProtocol<'p> {unimplemented!()}
fn __richcmp__(&'p self, py: Python<'p>, other: Self::Other, op: CompareOp)
fn __richcmp__(&'p self, other: Self::Other, op: CompareOp)
-> Self::Result where Self: PyObjectRichcmpProtocol<'p> {unimplemented!()}
}
@ -356,27 +355,27 @@ impl<'p, T> PyObjectRichcmpProtocolImpl for T where T: PyObjectProtocol<'p>
}
}
impl<T> PyObjectRichcmpProtocolImpl for T
where T: for<'p> PyObjectRichcmpProtocol<'p>
where T: for<'p> PyObjectRichcmpProtocol<'p> + PyDowncastFrom
{
#[inline]
fn tp_richcompare() -> Option<ffi::richcmpfunc> {
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: *mut ffi::PyObject,
op: c_int) -> *mut ffi::PyObject
where T: for<'p> PyObjectRichcmpProtocol<'p>
where T: for<'p> PyObjectRichcmpProtocol<'p> + PyDowncastFrom
{
const LOCATION: &'static str = concat!(stringify!(T), ".__richcmp__()");
callback::cb_meth(LOCATION, |py| {
let slf = Py::<T>::from_borrowed_ptr(slf);
let arg = PyObjectPtr::from_borrowed_ptr(py, arg);
let slf = py.cast_from_borrowed_ptr::<T>(slf);
let arg = py.cast_from_borrowed_ptr::<PyObject>(arg);
let result = {
let res = match extract_op(py, op) {
Ok(op) => {
match arg.extract(py) {
match arg.extract() {
Ok(arg) => {
slf.as_ref(py).__richcmp__(py, arg, op).into()
slf.__richcmp__(arg, op).into()
}
Err(e) => Err(e.into()),
}
@ -393,8 +392,6 @@ impl<T> PyObjectRichcmpProtocolImpl for T
}
}
};
py.release(arg);
py.release(slf);
result
})
}

View File

@ -9,7 +9,6 @@ use std::os::raw::c_int;
use ffi;
use err::PyResult;
use python::Python;
use typeob::PyTypeInfo;
use callback::UnitCallbackConverter;
@ -18,11 +17,11 @@ use callback::UnitCallbackConverter;
#[allow(unused_variables)]
pub trait PyBufferProtocol<'p> : PyTypeInfo + Sized + 'static
{
fn bf_getbuffer(&'p self, py: Python<'p>,
fn bf_getbuffer(&'p self,
view: *mut ffi::Py_buffer, flags: c_int) -> Self::Result
where Self: PyBufferGetBufferProtocol<'p> { unimplemented!() }
fn bf_releasebuffer(&'p self, py: Python<'p>, view: *mut ffi::Py_buffer) -> Self::Result
fn bf_releasebuffer(&'p self, view: *mut ffi::Py_buffer) -> Self::Result
where Self: PyBufferReleaseBufferProtocol<'p> { unimplemented!() }
}
@ -79,8 +78,8 @@ impl<T> PyBufferGetBufferProtocolImpl for T
where T: for<'p> PyBufferGetBufferProtocol<'p>
{
const LOCATION: &'static str = concat!(stringify!(T), ".buffer_get::<PyBufferProtocol>()");
::callback::cb_unary::<T, _, _, _>(LOCATION, slf, UnitCallbackConverter, |py, slf| {
slf.bf_getbuffer(py, arg1, arg2).into()
::callback::cb_unary::<T, _, _, _>(LOCATION, slf, UnitCallbackConverter, |_, slf| {
slf.bf_getbuffer(arg1, arg2).into()
})
}
Some(wrap::<T>)

View File

@ -5,7 +5,6 @@
//!
use err::PyResult;
use python::Python;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
@ -14,10 +13,10 @@ use class::methods::PyMethodDef;
#[allow(unused_variables)]
pub trait PyContextProtocol<'p>: PyTypeInfo {
fn __enter__(&'p mut self, py: Python<'p>)
fn __enter__(&'p mut self)
-> Self::Result where Self: PyContextEnterProtocol<'p> {unimplemented!()}
fn __exit__(&'p mut self, py: Python<'p>,
fn __exit__(&'p mut self,
exc_type: Option<Self::ExcType>,
exc_value: Option<Self::ExcValue>,
traceback: Option<Self::Traceback>)

View File

@ -9,7 +9,7 @@ use std::os::raw::c_int;
use ffi;
use err::PyResult;
use python::Python;
use python::PyDowncastFrom;
use objects::{PyType, PyObject};
use callback::{PyObjectCallbackConverter, UnitCallbackConverter};
use typeob::PyTypeInfo;
@ -19,18 +19,18 @@ use conversion::{IntoPyObject, FromPyObject};
/// Descriptor interface
#[allow(unused_variables)]
pub trait PyDescrProtocol<'p>: PyTypeInfo {
pub trait PyDescrProtocol<'p>: PyTypeInfo + PyDowncastFrom {
fn __get__(&'p self, py: Python<'p>, instance: &'p PyObject, owner: Option<&'p PyType>)
fn __get__(&'p self, instance: &'p PyObject, owner: Option<&'p PyType>)
-> Self::Result where Self: PyDescrGetProtocol<'p> { unimplemented!() }
fn __set__(&'p self, py: Python<'p>, instance: &'p PyObject, value: &'p PyObject)
fn __set__(&'p self, instance: &'p PyObject, value: &'p PyObject)
-> Self::Result where Self: PyDescrSetProtocol<'p> { unimplemented!() }
fn __delete__(&'p self, py: Python<'p>, instance: &'p PyObject)
fn __delete__(&'p self, instance: &'p PyObject)
-> Self::Result where Self: PyDescrDeleteProtocol<'p> { unimplemented!() }
fn __set_name__(&'p self, py: Python<'p>, instance: &'p PyObject)
fn __set_name__(&'p self, instance: &'p PyObject)
-> Self::Result where Self: PyDescrSetNameProtocol<'p> { unimplemented!() }
}

View File

@ -16,10 +16,10 @@ pub struct PyTraverseError(c_int);
#[allow(unused_variables)]
pub trait PyGCProtocol<'p> : PyTypeInfo {
fn __traverse__(&'p self, py: Python<'p>, visit: PyVisit)
fn __traverse__(&'p self, visit: PyVisit)
-> Result<(), PyTraverseError> { unimplemented!() }
fn __clear__(&'p mut self, py: Python<'p>) { unimplemented!() }
fn __clear__(&'p mut self) { unimplemented!() }
}
@ -28,11 +28,10 @@ pub trait PyGCClearProtocol<'p>: PyGCProtocol<'p> {}
impl<'p, T> PyGCProtocol<'p> for T where T: PyTypeInfo {
default fn __traverse__(&'p self, _py: Python<'p>, _: PyVisit)
-> Result<(), PyTraverseError> {
default fn __traverse__(&'p self, _: PyVisit) -> Result<(), PyTraverseError> {
Ok(())
}
default fn __clear__(&'p mut self, _py: Python<'p>) {}
default fn __clear__(&'p mut self) {}
}
#[doc(hidden)]
@ -97,7 +96,7 @@ impl<T> PyGCTraverseProtocolImpl for T where T: for<'p> PyGCTraverseProtocol<'p>
callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
let visit = PyVisit { visit: visit, arg: arg, _py: py };
match slf.__traverse__(py, visit) {
match slf.__traverse__(visit) {
Ok(()) => 0,
Err(PyTraverseError(code)) => code
}
@ -130,8 +129,8 @@ impl<T> PyGCClearProtocolImpl for T where T: for<'p> PyGCClearProtocol<'p>
{
const LOCATION: &'static str = concat!(stringify!(T), ".__clear__()");
callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
slf.__clear__(py);
callback::cb_unary_unit::<T, _>(LOCATION, slf, |_, slf| {
slf.__clear__();
0
})
}

View File

@ -8,18 +8,18 @@
use ffi;
use err::PyResult;
use python::Python;
use python::PyDowncastFrom;
use typeob::PyTypeInfo;
use callback::{PyObjectCallbackConverter, IterNextResultConverter};
/// Iterator protocol
#[allow(unused_variables)]
pub trait PyIterProtocol<'p> : PyTypeInfo {
fn __iter__(&'p mut self, py: Python<'p>)
pub trait PyIterProtocol<'p> : PyTypeInfo + PyDowncastFrom {
fn __iter__(&'p mut self)
-> Self::Result where Self: PyIterIterProtocol<'p> { unimplemented!() }
fn __next__(&'p mut self, py: Python<'p>)
fn __next__(&'p mut self)
-> Self::Result where Self: PyIterNextProtocol<'p> { unimplemented!() }
}

View File

@ -8,19 +8,14 @@ macro_rules! py_unary_func {
};
($trait:ident, $class:ident :: $f:ident, $res_type:ty, $conv:expr, $ret_type:ty) => {{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject) -> $ret_type
where T: for<'p> $trait<'p>
where T: for<'p> $trait<'p> + $crate::PyDowncastFrom
{
use $crate::instance::AsPyRef;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = $crate::Py::<T>::from_borrowed_ptr(slf);
let result = {
let res = slf.as_mut(py).$f(py).into();
$crate::callback::cb_convert($conv, py, res)
};
py.release(slf);
result
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let res = slf.$f().into();
$crate::callback::cb_convert($conv, py, res)
})
}
Some(wrap::<$class>)
@ -33,19 +28,15 @@ macro_rules! py_unary_func {
($trait:ident, $class:ident :: $f:ident, $res_type:ty, $conv:ty) => {{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject)
-> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p>
where T: for<'p> $trait<'p> + $crate::PyDowncastFrom
{
use instance::AsPyRef;
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = $crate::Py::<T>::from_borrowed_ptr(slf);
let result = {
let res = slf.as_mut(py).$f(py).into();
$crate::callback::cb_convert($conv, py, res)
};
py.release(slf);
result
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let res = slf.$f().into();
$crate::callback::cb_convert($conv, py, res)
})
}
Some(wrap::<$class>)
@ -59,11 +50,11 @@ macro_rules! py_len_func {
($trait:ident, $class:ident :: $f:ident, $conv:expr) => {{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject)
-> $crate::ffi::Py_ssize_t
where T: for<'p> $trait<'p>
where T: for<'p> $trait<'p> + $crate::PyDowncastFrom
{
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_unary::<T, _, _, _>(LOCATION, slf, $conv, |py, slf| {
slf.$f(py).into()
$crate::callback::cb_unary::<T, _, _, _>(LOCATION, slf, $conv, |_, slf| {
slf.$f().into()
})
}
Some(wrap::<$class>)
@ -80,27 +71,20 @@ macro_rules! py_binary_func{
#[allow(unused_mut)]
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: *mut ffi::PyObject) -> $return
where T: for<'p> $trait<'p>
where T: for<'p> $trait<'p> + $crate::PyDowncastFrom
{
use instance::AsPyRef;
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = $crate::Py::<T>::from_borrowed_ptr(slf);
let arg = $crate::PyObjectPtr::from_borrowed_ptr(py, arg);
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg);
let result = {
let result = match arg.extract(py) {
Ok(arg) => {
slf.as_mut(py).$f(py, arg).into()
}
Err(e) => Err(e.into()),
};
$crate::callback::cb_convert($conv, py, result)
let result = match arg.extract() {
Ok(arg) => slf.$f(arg).into(),
Err(e) => Err(e.into()),
};
py.release(arg);
py.release(slf);
result
$crate::callback::cb_convert($conv, py, result)
})
}
Some(wrap::<$class>)
@ -114,37 +98,29 @@ macro_rules! py_binary_self_func{
#[allow(unused_mut)]
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: *mut ffi::PyObject) -> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p>
where T: for<'p> $trait<'p> + $crate::PyDowncastFrom
{
use instance::AsPyRef;
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_meth(LOCATION, |py| {
let slf1 = $crate::Py::<T>::from_borrowed_ptr(slf);
let arg = $crate::PyObjectPtr::from_borrowed_ptr(py, arg);
let slf1 = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg);
let result = {
let result = match arg.extract(py) {
Ok(arg) => {
slf1.as_mut(py).$f(py, arg).into()
}
Err(e) => Err(e.into()),
};
match result {
Ok(_) => {
ffi::Py_INCREF(slf);
slf
}
Err(e) => {
e.restore(py);
$crate::std::ptr::null_mut()
}
}
let result = match arg.extract() {
Ok(arg) => slf1.$f(arg).into(),
Err(e) => Err(e.into()),
};
py.release(arg);
py.release(slf1);
result
match result {
Ok(_) => {
ffi::Py_INCREF(slf);
slf
}
Err(e) => {
e.restore(py);
$crate::std::ptr::null_mut()
}
}
})
}
Some(wrap::<$class>)
@ -159,19 +135,14 @@ macro_rules! py_ssizearg_func {
#[allow(unused_mut)]
unsafe extern "C" fn wrap<T>(slf: *mut ffi::PyObject,
arg: $crate::Py_ssize_t) -> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p>
where T: for<'p> $trait<'p> + $crate::PyDowncastFrom
{
use instance::AsPyRef;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_meth(LOCATION, |py| {
let slf = $crate::Py::<T>::from_borrowed_ptr(slf);
let result = {
let result = slf.as_mut(py).$f(py, arg as isize).into();
$crate::callback::cb_convert($conv, py, result)
};
py.release(slf);
result
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let result = slf.$f(arg as isize).into();
$crate::callback::cb_convert($conv, py, result)
})
}
Some(wrap::<$class>)
@ -188,30 +159,24 @@ macro_rules! py_ternary_func{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject,
arg1: *mut $crate::ffi::PyObject,
arg2: *mut $crate::ffi::PyObject) -> $return_type
where T: for<'p> $trait<'p>
where T: for<'p> $trait<'p> + $crate::PyDowncastFrom
{
use instance::AsPyRef;
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, $res_type>(LOCATION, $conv, |py| {
let slf = $crate::Py::<T>::from_borrowed_ptr(slf);
let arg1 = $crate::PyObjectPtr::from_borrowed_ptr(py, arg1);
let arg2 = $crate::PyObjectPtr::from_borrowed_ptr(py, arg2);
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg1 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg1);
let arg2 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg2);
let result = {
let result = match arg1.extract(py) {
Ok(arg1) => match arg2.extract(py) {
Ok(arg2) => slf.as_mut(py).$f(py, arg1, arg2).into(),
Err(e) => Err(e.into())
},
Err(e) => Err(e.into()),
};
$crate::callback::cb_convert($conv, py, result)
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
Ok(arg2) => slf.$f(arg1, arg2).into(),
Err(e) => Err(e.into())
},
Err(e) => Err(e.into()),
};
py.release(arg2);
py.release(arg1);
py.release(slf);
result
$crate::callback::cb_convert($conv, py, result)
})
}
@ -229,35 +194,29 @@ macro_rules! py_ternary_self_func{
-> *mut $crate::ffi::PyObject
where T: for<'p> $trait<'p>
{
use instance::AsPyRef;
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_meth(LOCATION, |py| {
let slf1 = $crate::Py::<T>::from_borrowed_ptr(slf);
let arg1 = $crate::PyObjectPtr::from_borrowed_ptr(py, arg1);
let arg2 = $crate::PyObjectPtr::from_borrowed_ptr(py, arg2);
let slf1 = py.mut_cast_from_borrowed_ptr::<T>(slf);
let arg1 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg1);
let arg2 = py.cast_from_borrowed_ptr::<$crate::PyObject>(arg2);
let result = {
let result = match arg1.extract(py) {
Ok(arg1) => match arg2.extract(py) {
Ok(arg2) => slf1.as_mut(py).$f(py, arg1, arg2).into(),
Err(e) => Err(e.into())
},
Err(e) => Err(e.into()),
};
match result {
Ok(_) => slf,
Err(e) => {
e.restore(py);
$crate::std::ptr::null_mut()
}
}
let result = match arg1.extract() {
Ok(arg1) => match arg2.extract() {
Ok(arg2) => slf1.$f(arg1, arg2).into(),
Err(e) => Err(e.into())
},
Err(e) => Err(e.into()),
};
py.release(arg2);
py.release(arg1);
py.release(slf1);
result
match result {
Ok(_) => slf,
Err(e) => {
e.restore(py);
$crate::std::ptr::null_mut()
}
}
})
}
Some(wrap::<T>)
@ -274,6 +233,7 @@ macro_rules! py_func_set{
value: *mut $crate::ffi::PyObject) -> $crate::c_int
where T: for<'p> $trait<'p>
{
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
if value.is_null() {
@ -282,20 +242,16 @@ macro_rules! py_func_set{
e.restore(py);
-1
} else {
let name = $crate::PyObjectPtr::from_borrowed_ptr(py, name);
let value = $crate::PyObjectPtr::from_borrowed_ptr(py, value);
let result = match name.extract(py) {
Ok(name) => match value.extract(py) {
Ok(value) => {
slf.$f(py, name, value).into()
},
let name = py.mut_cast_from_borrowed_ptr::<$crate::PyObject>(name);
let value = py.cast_from_borrowed_ptr::<$crate::PyObject>(value);
let result = match name.extract() {
Ok(name) => match value.extract() {
Ok(value) =>
slf.$f(name, value).into(),
Err(e) => Err(e.into()),
},
Err(e) => Err(e.into()),
};
py.release(value);
py.release(name);
match result {
Ok(_) =>
0,
@ -323,40 +279,33 @@ macro_rules! py_func_del{
value: *mut $crate::ffi::PyObject) -> $crate::c_int
where T: for<'p> $trait<'p>
{
use instance::AsPyRef;
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, ()>(
LOCATION, $crate::callback::UnitCallbackConverter, |py|
{
if value.is_null() {
let slf = $crate::Py::<T>::from_borrowed_ptr(slf);
let name = $crate::PyObjectPtr::from_borrowed_ptr(py, name);
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let name = py.cast_from_borrowed_ptr::<$crate::PyObject>(name);
let result = {
let result = match name.extract(py) {
Ok(name) =>
slf.as_mut(py).$f(py, name).into(),
Err(e) => Err(e.into()),
};
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py);
-1
}
}
let result = match name.extract() {
Ok(name) => slf.$f(name).into(),
Err(e) => Err(e.into()),
};
py.release(name);
py.release(slf);
result
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py);
-1
}
}
} else {
let e = PyErr::new::<exc::NotImplementedError, _>(
py, format!("Subscript assignment not supported by {:?}",
stringify!(T)));
e.restore(py);
-1
}
})
}
@ -373,59 +322,48 @@ macro_rules! py_func_set_del{
unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject,
name: *mut $crate::ffi::PyObject,
value: *mut $crate::ffi::PyObject) -> $crate::c_int
where T: for<'p> $trait<'p> + for<'p> $trait2<'p>
where T: for<'p> $trait<'p> + for<'p> $trait2<'p> + $crate::PyDowncastFrom
{
use instance::AsPyRef;
use $crate::ObjectProtocol;
const LOCATION: &'static str = concat!(stringify!($class), ".", stringify!($f), "()");
$crate::callback::cb_pyfunc::<_, _, ()>(
LOCATION, $crate::callback::UnitCallbackConverter, |py|
{
let slf = $crate::Py::<T>::from_borrowed_ptr(slf);
let name = $crate::PyObjectPtr::from_borrowed_ptr(py, name);
let slf = py.mut_cast_from_borrowed_ptr::<T>(slf);
let name = py.cast_from_borrowed_ptr::<$crate::PyObject>(name);
let result = {
if value.is_null() {
let result = match name.extract(py) {
Ok(name) =>
slf.as_mut(py).$f2(py, name).into(),
Err(e) => Err(e.into()),
};
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py);
-1
}
if value.is_null() {
let result = match name.extract() {
Ok(name) => slf.$f2(name).into(),
Err(e) => Err(e.into()),
};
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py);
-1
}
} else {
let value = ::PyObjectPtr::from_borrowed_ptr(py, value);
let result = {
let result = match name.extract(py) {
Ok(name) => match value.extract(py) {
Ok(value) => {
slf.as_mut(py).$f(py, name, value).into()
},
Err(e) => Err(e.into()),
},
Err(e) => Err(e.into()),
};
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py);
-1
}
}
};
py.release(value);
result
}
};
py.release(name);
py.release(slf);
result
} else {
let value = py.cast_from_borrowed_ptr::<$crate::PyObject>(value);
let result = match name.extract() {
Ok(name) => match value.extract() {
Ok(value) => {
slf.$f(name, value).into()
},
Err(e) => Err(e.into()),
},
Err(e) => Err(e.into()),
};
match result {
Ok(_) => 0,
Err(e) => {
e.restore(py);
-1
}
}
}
})
}
Some(wrap::<T>)

View File

@ -5,7 +5,7 @@
use ffi;
use err::{PyErr, PyResult};
use python::Python;
use python::{Python, PyDowncastFrom};
use objects::exc;
use callback::{PyObjectCallbackConverter, LenResultConverter};
use conversion::{IntoPyObject, FromPyObject};
@ -15,27 +15,27 @@ use class::methods::PyMethodDef;
/// Mapping interface
#[allow(unused_variables)]
pub trait PyMappingProtocol<'p>: PyTypeInfo + Sized + 'static {
pub trait PyMappingProtocol<'p>: PyTypeInfo + PyDowncastFrom + Sized + 'static {
fn __len__(&'p self, py: Python<'p>)
fn __len__(&'p self)
-> Self::Result where Self: PyMappingLenProtocol<'p> {unimplemented!()}
fn __getitem__(&'p self, py: Python<'p>, key: Self::Key)
fn __getitem__(&'p self, key: Self::Key)
-> Self::Result where Self: PyMappingGetItemProtocol<'p> {unimplemented!()}
fn __setitem__(&'p mut self, py: Python<'p>, key: Self::Key, value: Self::Value)
fn __setitem__(&'p mut self, key: Self::Key, value: Self::Value)
-> Self::Result where Self: PyMappingSetItemProtocol<'p> {unimplemented!()}
fn __delitem__(&'p mut self, py: Python<'p>, key: Self::Key)
fn __delitem__(&'p mut self, key: Self::Key)
-> Self::Result where Self: PyMappingDelItemProtocol<'p> {unimplemented!()}
fn __iter__(&'p self, py: Python<'p>)
-> Self::Result where Self: PyMappingIterProtocol<'p> {unimplemented!()}
fn __contains__(&'p self, py: Python<'p>, value: Self::Value)
fn __contains__(&'p self, value: Self::Value)
-> Self::Result where Self: PyMappingContainsProtocol<'p> {unimplemented!()}
fn __reversed__(&'p self, py: Python<'p>)
fn __reversed__(&'p self)
-> Self::Result where Self: PyMappingReversedProtocol<'p> {unimplemented!()}
}

View File

@ -5,120 +5,119 @@
use ffi;
use err::PyResult;
use python::Python;
use callback::PyObjectCallbackConverter;
use typeob::PyTypeInfo;
use class::methods::PyMethodDef;
use class::basic::PyObjectProtocolImpl;
use ::{IntoPyObject, FromPyObject};
use {IntoPyObject, FromPyObject, PyDowncastFrom};
/// Number interface
#[allow(unused_variables)]
pub trait PyNumberProtocol<'p>: PyTypeInfo {
pub trait PyNumberProtocol<'p>: PyTypeInfo + PyDowncastFrom {
fn __add__(&'p self, py: Python<'p>, other: Self::Other)
fn __add__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberAddProtocol<'p> { unimplemented!() }
fn __sub__(&'p self, py: Python<'p>, other: Self::Other)
fn __sub__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberSubProtocol<'p> { unimplemented!() }
fn __mul__(&'p self, py: Python<'p>, other: Self::Other)
fn __mul__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberMulProtocol<'p> { unimplemented!() }
fn __matmul__(&'p self, py: Python<'p>, other: Self::Other)
fn __matmul__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberMatmulProtocol<'p> { unimplemented!() }
fn __truediv__(&'p self, py: Python<'p>, other: Self::Other)
fn __truediv__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberTruedivProtocol<'p> { unimplemented!() }
fn __floordiv__(&'p self, py: Python<'p>, other: Self::Other)
fn __floordiv__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberFloordivProtocol<'p> { unimplemented!() }
fn __mod__(&'p self, py: Python<'p>, other: Self::Other)
fn __mod__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberModProtocol<'p> { unimplemented!() }
fn __divmod__(&'p self, py: Python<'p>, other: Self::Other)
fn __divmod__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberDivmodProtocol<'p> { unimplemented!() }
fn __pow__(&'p self, py: Python<'p>, other: Self::Other, modulo: Self::Modulo)
fn __pow__(&'p self, other: Self::Other, modulo: Self::Modulo)
-> Self::Result where Self: PyNumberPowProtocol<'p> { unimplemented!() }
fn __lshift__(&'p self, py: Python<'p>, other: Self::Other)
fn __lshift__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberLShiftProtocol<'p> { unimplemented!() }
fn __rshift__(&'p self, py: Python<'p>, other: Self::Other)
fn __rshift__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRShiftProtocol<'p> { unimplemented!() }
fn __and__(&'p self, py: Python<'p>, other: Self::Other)
fn __and__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberAndProtocol<'p> { unimplemented!() }
fn __xor__(&'p self, py: Python<'p>, other: Self::Other)
fn __xor__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberXorProtocol<'p> { unimplemented!() }
fn __or__(&'p self, py: Python<'p>, other: Self::Other)
fn __or__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberOrProtocol<'p> { unimplemented!() }
fn __radd__(&'p self, py: Python<'p>, other: Self::Other)
fn __radd__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRAddProtocol<'p> { unimplemented!() }
fn __rsub__(&'p self, py: Python<'p>, other: Self::Other)
fn __rsub__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRSubProtocol<'p> { unimplemented!() }
fn __rmul__(&'p self, py: Python<'p>, other: Self::Other)
fn __rmul__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRMulProtocol<'p> { unimplemented!() }
fn __rmatmul__(&'p self, py: Python<'p>, other: Self::Other)
fn __rmatmul__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRMatmulProtocol<'p> { unimplemented!() }
fn __rtruediv__(&'p self, py: Python<'p>, other: Self::Other)
fn __rtruediv__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRTruedivProtocol<'p> { unimplemented!() }
fn __rfloordiv__(&'p self, py: Python<'p>, other: Self::Other)
fn __rfloordiv__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRFloordivProtocol<'p> { unimplemented!() }
fn __rmod__(&'p self, py: Python<'p>, other: Self::Other)
fn __rmod__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRModProtocol<'p> { unimplemented!() }
fn __rdivmod__(&'p self, py: Python<'p>, other: Self::Other)
fn __rdivmod__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRDivmodProtocol<'p> { unimplemented!() }
fn __rpow__(&'p self, py: Python<'p>, other: Self::Other)
fn __rpow__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRPowProtocol<'p> { unimplemented!() }
fn __rlshift__(&'p self, py: Python<'p>, other: Self::Other)
fn __rlshift__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRLShiftProtocol<'p> { unimplemented!() }
fn __rrshift__(&'p self, py: Python<'p>, other: Self::Other)
fn __rrshift__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRRShiftProtocol<'p> { unimplemented!() }
fn __rand__(&'p self, py: Python<'p>, other: Self::Other)
fn __rand__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRAndProtocol<'p> { unimplemented!() }
fn __rxor__(&'p self, py: Python<'p>, other: Self::Other)
fn __rxor__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberRXorProtocol<'p> { unimplemented!() }
fn __ror__(&'p self, py: Python<'p>, other: Self::Other)
fn __ror__(&'p self, other: Self::Other)
-> Self::Result where Self: PyNumberROrProtocol<'p> { unimplemented!() }
fn __iadd__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __iadd__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIAddProtocol<'p> { unimplemented!() }
fn __isub__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __isub__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberISubProtocol<'p> { unimplemented!() }
fn __imul__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __imul__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIMulProtocol<'p> { unimplemented!() }
fn __imatmul__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __imatmul__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIMatmulProtocol<'p> { unimplemented!() }
fn __itruediv__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __itruediv__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberITruedivProtocol<'p> {unimplemented!()}
fn __ifloordiv__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __ifloordiv__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIFloordivProtocol<'p> {unimplemented!() }
fn __imod__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __imod__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIModProtocol<'p> { unimplemented!() }
fn __ipow__(&'p mut self, py: Python<'p>, other: Self::Other, modulo: Self::Modulo)
fn __ipow__(&'p mut self, other: Self::Other, modulo: Self::Modulo)
-> Self::Result where Self: PyNumberIPowProtocol<'p> { unimplemented!() }
fn __ilshift__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __ilshift__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberILShiftProtocol<'p> { unimplemented!() }
fn __irshift__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __irshift__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIRShiftProtocol<'p> { unimplemented!() }
fn __iand__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __iand__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIAndProtocol<'p> { unimplemented!() }
fn __ixor__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __ixor__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIXorProtocol<'p> { unimplemented!() }
fn __ior__(&'p mut self, py: Python<'p>, other: Self::Other)
fn __ior__(&'p mut self, other: Self::Other)
-> Self::Result where Self: PyNumberIOrProtocol<'p> { unimplemented!() }
// Unary arithmetic
fn __neg__(&'p self, py: Python<'p>)
fn __neg__(&'p self)
-> Self::Result where Self: PyNumberNegProtocol<'p> { unimplemented!() }
fn __pos__(&'p self, py: Python<'p>)
fn __pos__(&'p self)
-> Self::Result where Self: PyNumberPosProtocol<'p> { unimplemented!() }
fn __abs__(&'p self, py: Python<'p>)
fn __abs__(&'p self)
-> Self::Result where Self: PyNumberAbsProtocol<'p> { unimplemented!() }
fn __invert__(&'p self, py: Python<'p>)
fn __invert__(&'p self)
-> Self::Result where Self: PyNumberInvertProtocol<'p> { unimplemented!() }
fn __complex__(&'p self, py: Python<'p>)
fn __complex__(&'p self)
-> Self::Result where Self: PyNumberComplexProtocol<'p> { unimplemented!() }
fn __int__(&'p self, py: Python<'p>)
fn __int__(&'p self)
-> Self::Result where Self: PyNumberIntProtocol<'p> { unimplemented!() }
fn __float__(&'p self, py: Python<'p>)
fn __float__(&'p self)
-> Self::Result where Self: PyNumberFloatProtocol<'p> { unimplemented!() }
fn __round__(&'p self, py: Python<'p>)
fn __round__(&'p self)
-> Self::Result where Self: PyNumberRoundProtocol<'p> { unimplemented!() }
fn __index__(&'p self, py: Python<'p>)
fn __index__(&'p self)
-> Self::Result where Self: PyNumberIndexProtocol<'p> { unimplemented!() }
}

View File

@ -6,10 +6,10 @@
use std::os::raw::c_int;
use ffi;
use python::Python;
use python::PyDowncastFrom;
use err::{PyErr, PyResult};
use objects::exc;
use pointer::PyObjectPtr;
use objects::{exc, PyObject};
use objectprotocol::ObjectProtocol;
use callback::{PyObjectCallbackConverter, LenResultConverter, BoolCallbackConverter};
use typeob::PyTypeInfo;
use conversion::{IntoPyObject, FromPyObject};
@ -17,32 +17,33 @@ use conversion::{IntoPyObject, FromPyObject};
/// Sequece interface
#[allow(unused_variables)]
pub trait PySequenceProtocol<'p>: PyTypeInfo + Sized + 'static {
fn __len__(&'p self, py: Python<'p>) -> Self::Result
pub trait PySequenceProtocol<'p>: PyTypeInfo + PyDowncastFrom
{
fn __len__(&'p self) -> Self::Result
where Self: PySequenceLenProtocol<'p> { unimplemented!() }
fn __getitem__(&'p self, py: Python<'p>, key: isize) -> Self::Result
fn __getitem__(&'p self, key: isize) -> Self::Result
where Self: PySequenceGetItemProtocol<'p> { unimplemented!() }
fn __setitem__(&'p mut self, py: Python<'p>, key: isize, value: Self::Value) -> Self::Result
fn __setitem__(&'p mut self, key: isize, value: Self::Value) -> Self::Result
where Self: PySequenceSetItemProtocol<'p> { unimplemented!() }
fn __delitem__(&'p mut self, py: Python<'p>, key: isize) -> Self::Result
fn __delitem__(&'p mut self, key: isize) -> Self::Result
where Self: PySequenceDelItemProtocol<'p> { unimplemented!() }
fn __contains__(&'p self, py: Python<'p>, item: Self::Item) -> Self::Result
fn __contains__(&'p self, item: Self::Item) -> Self::Result
where Self: PySequenceContainsProtocol<'p> { unimplemented!() }
fn __concat__(&'p self, py: Python<'p>, other: Self::Other) -> Self::Result
fn __concat__(&'p self, other: Self::Other) -> Self::Result
where Self: PySequenceConcatProtocol<'p> { unimplemented!() }
fn __repeat__(&'p self, py: Python<'p>, count: isize) -> Self::Result
fn __repeat__(&'p self, count: isize) -> Self::Result
where Self: PySequenceRepeatProtocol<'p> { unimplemented!() }
fn __inplace_concat__(&'p mut self, py: Python<'p>, other: Self::Other) -> Self::Result
fn __inplace_concat__(&'p mut self, other: Self::Other) -> Self::Result
where Self: PySequenceInplaceConcatProtocol<'p> { unimplemented!() }
fn __inplace_repeat__(&'p mut self, py: Python<'p>, count: isize) -> Self::Result
fn __inplace_repeat__(&'p mut self, count: isize) -> Self::Result
where Self: PySequenceInplaceRepeatProtocol<'p> { unimplemented!() }
}
@ -224,10 +225,10 @@ impl<T> PySequenceSetItemProtocolImpl for T
e.restore(py);
-1
} else {
let value = PyObjectPtr::from_borrowed_ptr(py, value);
let result = match value.extract(py) {
let value = py.cast_from_borrowed_ptr::<PyObject>(value);
let result = match value.extract() {
Ok(value) => {
slf.__setitem__(py, key as isize, value).into()
slf.__setitem__(key as isize, value).into()
},
Err(e) => Err(e.into()),
};
@ -269,7 +270,7 @@ impl<T> PySequenceDelItemProtocolImpl for T
const LOCATION: &'static str = "T.__detitem__()";
::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
if value.is_null() {
let result = slf.__delitem__(py, key as isize).into();
let result = slf.__delitem__(key as isize).into();
match result {
Ok(_) => 0,
Err(e) => {
@ -304,7 +305,7 @@ impl<T> PySequenceDelItemProtocolImpl for T
const LOCATION: &'static str = "T.__set/del_item__()";
::callback::cb_unary_unit::<T, _>(LOCATION, slf, |py, slf| {
if value.is_null() {
let result = slf.__delitem__(py, key as isize).into();
let result = slf.__delitem__(key as isize).into();
match result {
Ok(_) => 0,
Err(e) => {
@ -313,10 +314,10 @@ impl<T> PySequenceDelItemProtocolImpl for T
}
}
} else {
let value = ::PyObjectPtr::from_borrowed_ptr(py, value);
let result = match value.extract(py) {
let value = py.cast_from_borrowed_ptr::<PyObject>(value);
let result = match value.extract() {
Ok(value) => {
slf.__setitem__(py, key as isize, value).into()
slf.__setitem__(key as isize, value).into()
},
Err(e) => Err(e.into()),
};

View File

@ -116,7 +116,8 @@ impl PyBytes {
#[cfg(test)]
mod test {
use python::Python;
use conversion::{ToPyObject}; //, RefFromPyObject};
use instance::AsPyRef;
use conversion::{ToPyObject, RefFromPyObject};
#[test]
fn test_non_bmp() {

View File

@ -104,15 +104,16 @@ pub struct Pool {
}
impl Pool {
#[inline]
pub unsafe fn new() -> Pool {
let pool: &'static mut Vec<PyObject> = mem::transmute(POOL);
Pool{ pos: pool.len(), no_send: marker::PhantomData }
}
/// Retrieves the marker type that proves that the GIL was acquired.
#[inline]
pub fn python<'p>(&'p self) -> Python<'p> {
unsafe { Python::assume_gil_acquired() }
}
// /// Retrieves the marker type that proves that the GIL was acquired.
// #[inline]
// pub fn python<'p>(&'p self) -> Python<'p> {
// unsafe { Python::assume_gil_acquired() }
//}
}
impl Drop for Pool {

View File

@ -18,9 +18,9 @@ struct TestClass {
#[py::proto]
impl class::PyBufferProtocol for TestClass {
fn bf_getbuffer(&self, py: Python, view: *mut ffi::Py_buffer, flags: c_int) -> PyResult<()> {
fn bf_getbuffer(&self, view: *mut ffi::Py_buffer, flags: c_int) -> PyResult<()> {
if view == ptr::null_mut() {
return Err(PyErr::new::<exc::BufferError, _>(py, "View is null"))
return Err(PyErr::new::<exc::BufferError, _>(self.token(), "View is null"))
}
unsafe {
@ -28,7 +28,7 @@ impl class::PyBufferProtocol for TestClass {
}
if (flags & ffi::PyBUF_WRITABLE) == ffi::PyBUF_WRITABLE {
return Err(PyErr::new::<exc::BufferError, _>(py, "Object is not writable"))
return Err(PyErr::new::<exc::BufferError, _>(self.token(), "Object is not writable"))
}
let bytes = &self.vec;

View File

@ -105,8 +105,8 @@ struct EmptyClassWithNew {
#[py::methods]
impl EmptyClassWithNew {
#[__new__]
fn __new__(cls: &PyType, py: Python) -> PyResult<Py<EmptyClassWithNew>> {
Py::new(py, |t| EmptyClassWithNew{token: t})
fn __new__(cls: &PyType) -> PyResult<Py<EmptyClassWithNew>> {
Py::new(cls.token(), |t| EmptyClassWithNew{token: t})
}
}
@ -127,8 +127,8 @@ struct NewWithOneArg {
#[py::methods]
impl NewWithOneArg {
#[new]
fn __new__(_cls: &PyType, py: Python, arg: i32) -> PyResult<Py<NewWithOneArg>> {
Py::new(py, |t| NewWithOneArg{_data: arg, token: t})
fn __new__(cls: &PyType, arg: i32) -> PyResult<Py<NewWithOneArg>> {
Py::new(cls.token(), |t| NewWithOneArg{_data: arg, token: t})
}
}
@ -153,9 +153,9 @@ struct NewWithTwoArgs {
#[py::methods]
impl NewWithTwoArgs {
#[new]
fn __new__(_cls: &PyType, py: Python, arg1: i32, arg2: i32) -> PyResult<Py<NewWithTwoArgs>>
fn __new__(cls: &PyType, arg1: i32, arg2: i32) -> PyResult<Py<NewWithTwoArgs>>
{
Py::new(py, |t| NewWithTwoArgs{_data1: arg1, _data2: arg2, token: t})
Py::new(cls.token(), |t| NewWithTwoArgs{_data1: arg1, _data2: arg2, token: t})
}
}
@ -232,7 +232,7 @@ struct InstanceMethod {
#[py::methods]
impl InstanceMethod {
/// Test method
fn method(&self, py: Python) -> PyResult<i32> {
fn method(&self) -> PyResult<i32> {
Ok(self.member)
}
}
@ -243,7 +243,7 @@ fn instance_method() {
let py = gil.python();
let obj = Py::new(py, |t| InstanceMethod{member: 42, token: t}).unwrap();
assert!(obj.as_ref(py).method(py).unwrap() == 42);
assert!(obj.as_ref(py).method().unwrap() == 42);
let d = PyDict::new(py);
d.set_item("obj", obj).unwrap();
py.run("assert obj.method() == 42", None, Some(d)).unwrap();
@ -258,7 +258,7 @@ struct InstanceMethodWithArgs {
#[py::methods]
impl InstanceMethodWithArgs {
fn method(&self, py: Python, multiplier: i32) -> PyResult<i32> {
fn method(&self, multiplier: i32) -> PyResult<i32> {
Ok(self.member * multiplier)
}
}
@ -269,7 +269,7 @@ fn instance_method_with_args() {
let py = gil.python();
let obj = Py::new(py, |t| InstanceMethodWithArgs{member: 7, token: t}).unwrap();
assert!(obj.as_ref(py).method(py, 6).unwrap() == 42);
assert!(obj.as_ref(py).method(6).unwrap() == 42);
let d = PyDict::new(py);
d.set_item("obj", obj).unwrap();
py.run("assert obj.method(3) == 21", None, Some(d)).unwrap();
@ -283,12 +283,12 @@ struct ClassMethod {token: PyToken}
#[py::methods]
impl ClassMethod {
#[new]
fn __new__(cls: &PyType, py: Python) -> PyResult<Py<ClassMethod>> {
Py::new(py, |t| ClassMethod{token: t})
fn __new__(cls: &PyType) -> PyResult<Py<ClassMethod>> {
Py::new(cls.token(), |t| ClassMethod{token: t})
}
#[classmethod]
fn method(cls: &PyType, py: Python) -> PyResult<String> {
fn method(cls: &PyType) -> PyResult<String> {
Ok(format!("{}.method()!", cls.name()))
}
}
@ -311,7 +311,7 @@ struct ClassMethodWithArgs{token: PyToken}
#[py::methods]
impl ClassMethodWithArgs {
#[classmethod]
fn method(cls: &PyType, py: Python, input: &PyString) -> PyResult<String> {
fn method(cls: &PyType, input: &PyString) -> PyResult<String> {
Ok(format!("{}.method({})", cls.name(), input))
}
}
@ -334,8 +334,8 @@ struct StaticMethod {
#[py::methods]
impl StaticMethod {
#[new]
fn __new__(cls: &PyType, py: Python) -> PyResult<Py<StaticMethod>> {
Py::new(py, |t| StaticMethod{token: t})
fn __new__(cls: &PyType) -> PyResult<Py<StaticMethod>> {
Py::new(cls.token(), |t| StaticMethod{token: t})
}
#[staticmethod]
@ -389,12 +389,12 @@ struct GCIntegration {
#[py::proto]
impl PyGCProtocol for GCIntegration {
fn __traverse__(&self, py: Python, visit: PyVisit) -> Result<(), PyTraverseError> {
fn __traverse__(&self, visit: PyVisit) -> Result<(), PyTraverseError> {
visit.call(&*self.self_ref.borrow())
}
fn __clear__(&mut self, py: Python) {
*self.self_ref.borrow_mut() = py.None();
fn __clear__(&mut self) {
*self.self_ref.borrow_mut() = self.token().None();
}
}
@ -424,7 +424,7 @@ pub struct Len {
#[py::proto]
impl PyMappingProtocol for Len {
fn __len__(&self, py: Python) -> PyResult<usize> {
fn __len__(&self) -> PyResult<usize> {
Ok(self.l)
}
}
@ -453,11 +453,11 @@ struct Iterator{
#[py::proto]
impl PyIterProtocol for Iterator {
fn __iter__(&mut self, py: Python) -> PyResult<Py<Iterator>> {
fn __iter__(&mut self) -> PyResult<Py<Iterator>> {
Ok(self.into())
}
fn __next__(&mut self, py: Python) -> PyResult<Option<i32>> {
fn __next__(&mut self) -> PyResult<Option<i32>> {
Ok(self.iter.next())
}
}
@ -477,24 +477,24 @@ struct StringMethods {token: PyToken}
#[py::proto]
impl<'p> PyObjectProtocol<'p> for StringMethods {
fn __str__(&self, py: Python) -> PyResult<&'static str> {
fn __str__(&self) -> PyResult<&'static str> {
Ok("str")
}
fn __repr__(&self, py: Python) -> PyResult<&'static str> {
fn __repr__(&self) -> PyResult<&'static str> {
Ok("repr")
}
fn __format__(&self, py: Python, format_spec: String) -> PyResult<String> {
fn __format__(&self, format_spec: String) -> PyResult<String> {
Ok(format!("format({})", format_spec))
}
fn __unicode__(&self, py: Python) -> PyResult<PyObjectPtr> {
Ok(PyString::new(py, "unicode").into())
fn __unicode__(&self) -> PyResult<PyObjectPtr> {
Ok(PyString::new(self.token(), "unicode").into())
}
fn __bytes__(&self, py: Python) -> PyResult<PyObjectPtr> {
Ok(PyBytes::new(py, b"bytes").into())
fn __bytes__(&self) -> PyResult<PyObjectPtr> {
Ok(PyBytes::new(self.token(), b"bytes").into())
}
}
@ -533,10 +533,10 @@ struct Comparisons {
#[py::proto]
impl PyObjectProtocol for Comparisons {
fn __hash__(&self, py: Python) -> PyResult<usize> {
fn __hash__(&self) -> PyResult<usize> {
Ok(self.val as usize)
}
fn __bool__(&self, py: Python) -> PyResult<bool> {
fn __bool__(&self) -> PyResult<bool> {
Ok(self.val != 0)
}
}
@ -567,13 +567,13 @@ struct Sequence {
#[py::proto]
impl PySequenceProtocol for Sequence {
fn __len__(&self, py: Python) -> PyResult<usize> {
fn __len__(&self) -> PyResult<usize> {
Ok(5)
}
fn __getitem__(&self, py: Python, key: isize) -> PyResult<isize> {
fn __getitem__(&self, key: isize) -> PyResult<isize> {
if key == 5 {
return Err(PyErr::new::<exc::IndexError, NoArgs>(py, NoArgs));
return Err(PyErr::new::<exc::IndexError, NoArgs>(self.token(), NoArgs));
}
Ok(key)
}
@ -597,7 +597,7 @@ struct Callable {token: PyToken}
impl Callable {
#[__call__]
fn __call__(&self, py: Python, arg: i32) -> PyResult<i32> {
fn __call__(&self, arg: i32) -> PyResult<i32> {
Ok(arg * 6)
}
}
@ -624,7 +624,7 @@ struct SetItem {
#[py::proto]
impl PyMappingProtocol<'a> for SetItem {
fn __setitem__(&mut self, py: Python, key: i32, val: i32) -> PyResult<()> {
fn __setitem__(&mut self, key: i32, val: i32) -> PyResult<()> {
self.key = key;
self.val = val;
Ok(())
@ -651,7 +651,7 @@ struct DelItem {
#[py::proto]
impl PyMappingProtocol<'a> for DelItem {
fn __delitem__(&mut self, py: Python, key: i32) -> PyResult<()> {
fn __delitem__(&mut self, key: i32) -> PyResult<()> {
self.key = key;
Ok(())
}
@ -676,12 +676,12 @@ struct SetDelItem {
#[py::proto]
impl PyMappingProtocol for SetDelItem {
fn __setitem__(&mut self, py: Python, key: i32, val: i32) -> PyResult<()> {
fn __setitem__(&mut self, key: i32, val: i32) -> PyResult<()> {
self.val = Some(val);
Ok(())
}
fn __delitem__(&mut self, py: Python, key: i32) -> PyResult<()> {
fn __delitem__(&mut self, key: i32) -> PyResult<()> {
self.val = None;
Ok(())
}
@ -704,7 +704,7 @@ struct Reversed {token: PyToken}
#[py::proto]
impl PyMappingProtocol for Reversed{
fn __reversed__(&self, py: Python) -> PyResult<&'static str> {
fn __reversed__(&self) -> PyResult<&'static str> {
Ok("I am reversed")
}
}
@ -723,7 +723,7 @@ struct Contains {token: PyToken}
#[py::proto]
impl PySequenceProtocol for Contains {
fn __contains__(&self, py: Python, item: i32) -> PyResult<bool> {
fn __contains__(&self, item: i32) -> PyResult<bool> {
Ok(item >= 0)
}
}
@ -747,19 +747,19 @@ struct UnaryArithmetic {token: PyToken}
#[py::proto]
impl PyNumberProtocol for UnaryArithmetic {
fn __neg__(&self, py: Python) -> PyResult<&'static str> {
fn __neg__(&self) -> PyResult<&'static str> {
Ok("neg")
}
fn __pos__(&self, py: Python) -> PyResult<&'static str> {
fn __pos__(&self) -> PyResult<&'static str> {
Ok("pos")
}
fn __abs__(&self, py: Python) -> PyResult<&'static str> {
fn __abs__(&self) -> PyResult<&'static str> {
Ok("abs")
}
fn __invert__(&self, py: Python) -> PyResult<&'static str> {
fn __invert__(&self) -> PyResult<&'static str> {
Ok("invert")
}
}
@ -784,42 +784,42 @@ struct BinaryArithmetic {
#[py::proto]
impl PyObjectProtocol for BinaryArithmetic {
fn __repr__(&self, py: Python) -> PyResult<&'static str> {
fn __repr__(&self) -> PyResult<&'static str> {
Ok("BA")
}
}
#[py::proto]
impl PyNumberProtocol for BinaryArithmetic {
fn __add__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __add__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} + {:?}", self, rhs))
}
fn __sub__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __sub__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} - {:?}", self, rhs))
}
fn __mul__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __mul__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} * {:?}", self, rhs))
}
fn __lshift__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __lshift__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} << {:?}", self, rhs))
}
fn __rshift__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __rshift__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} >> {:?}", self, rhs))
}
fn __and__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __and__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} & {:?}", self, rhs))
}
fn __xor__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __xor__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} ^ {:?}", self, rhs))
}
fn __or__(&self, py: Python, rhs: &PyObject) -> PyResult<String> {
fn __or__(&self, rhs: &PyObject) -> PyResult<String> {
Ok(format!("{:?} | {:?}", self, rhs))
}
}
@ -858,18 +858,18 @@ struct RichComparisons {
#[py::proto]
impl PyObjectProtocol for RichComparisons {
fn __repr__(&self, py: Python) -> PyResult<&'static str> {
fn __repr__(&self) -> PyResult<&'static str> {
Ok("RC")
}
fn __richcmp__(&self, py: Python, other: &PyObject, op: CompareOp) -> PyResult<String> {
fn __richcmp__(&self, other: &PyObject, op: CompareOp) -> PyResult<String> {
match op {
CompareOp::Lt => Ok(format!("{} < {:?}", self.__repr__(py).unwrap(), other)),
CompareOp::Le => Ok(format!("{} <= {:?}", self.__repr__(py).unwrap(), other)),
CompareOp::Eq => Ok(format!("{} == {:?}", self.__repr__(py).unwrap(), other)),
CompareOp::Ne => Ok(format!("{} != {:?}", self.__repr__(py).unwrap(), other)),
CompareOp::Gt => Ok(format!("{} > {:?}", self.__repr__(py).unwrap(), other)),
CompareOp::Ge => Ok(format!("{} >= {:?}", self.__repr__(py).unwrap(), other))
CompareOp::Lt => Ok(format!("{} < {:?}", self.__repr__().unwrap(), other)),
CompareOp::Le => Ok(format!("{} <= {:?}", self.__repr__().unwrap(), other)),
CompareOp::Eq => Ok(format!("{} == {:?}", self.__repr__().unwrap(), other)),
CompareOp::Ne => Ok(format!("{} != {:?}", self.__repr__().unwrap(), other)),
CompareOp::Gt => Ok(format!("{} > {:?}", self.__repr__().unwrap(), other)),
CompareOp::Ge => Ok(format!("{} >= {:?}", self.__repr__().unwrap(), other))
}
}
}
@ -881,16 +881,15 @@ struct RichComparisons2 {
#[py::proto]
impl PyObjectProtocol for RichComparisons2 {
fn __repr__(&self, py: Python) -> PyResult<&'static str> {
fn __repr__(&self) -> PyResult<&'static str> {
Ok("RC2")
}
fn __richcmp__(&self, py: Python,
other: &'p PyObject, op: CompareOp) -> PyResult<PyObjectPtr> {
fn __richcmp__(&self, other: &'p PyObject, op: CompareOp) -> PyResult<PyObjectPtr> {
match op {
CompareOp::Eq => Ok(true.to_object(py)),
CompareOp::Ne => Ok(false.to_object(py)),
_ => Ok(py.NotImplemented())
CompareOp::Eq => Ok(true.to_object(self.token())),
CompareOp::Ne => Ok(false.to_object(self.token())),
_ => Ok(self.token().NotImplemented())
}
}
}
@ -956,49 +955,49 @@ struct InPlaceOperations {
#[py::proto]
impl PyObjectProtocol for InPlaceOperations {
fn __repr__(&self, py: Python) -> PyResult<String> {
fn __repr__(&self) -> PyResult<String> {
Ok(format!("IPO({:?})", self.value))
}
}
#[py::proto]
impl PyNumberProtocol for InPlaceOperations {
fn __iadd__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __iadd__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value + other;
Ok(())
}
fn __isub__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __isub__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value - other;
Ok(())
}
fn __imul__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __imul__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value * other;
Ok(())
}
fn __ilshift__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __ilshift__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value << other;
Ok(())
}
fn __irshift__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __irshift__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value >> other;
Ok(())
}
fn __iand__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __iand__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value & other;
Ok(())
}
fn __ixor__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __ixor__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value ^ other;
Ok(())
}
fn __ior__(&mut self, py: Python, other: u32) -> PyResult<()> {
fn __ior__(&mut self, other: u32) -> PyResult<()> {
self.value = self.value | other;
Ok(())
}
@ -1043,16 +1042,16 @@ struct ContextManager {
#[py::proto]
impl<'p> PyContextProtocol<'p> for ContextManager {
fn __enter__(&mut self, py: Python) -> PyResult<i32> {
fn __enter__(&mut self) -> PyResult<i32> {
Ok(42)
}
fn __exit__(&mut self, py: Python,
fn __exit__(&mut self,
ty: Option<&'p PyType>,
value: Option<&'p PyObject>,
traceback: Option<&'p PyObject>) -> PyResult<bool> {
self.exit_called = true;
if ty == Some(py.get_type::<exc::ValueError>()) {
if ty == Some(self.token().get_type::<exc::ValueError>()) {
Ok(true)
} else {
Ok(false)
@ -1089,16 +1088,16 @@ struct ClassWithProperties {
#[py::methods]
impl ClassWithProperties {
fn get_num(&self, py: Python) -> PyResult<i32> {
fn get_num(&self) -> PyResult<i32> {
Ok(self.num)
}
#[getter(DATA)]
fn get_data(&self, py: Python) -> PyResult<i32> {
fn get_data(&self) -> PyResult<i32> {
Ok(self.num)
}
#[setter(DATA)]
fn set_data(&mut self, py: Python, value: i32) -> PyResult<()> {
fn set_data(&mut self, value: i32) -> PyResult<()> {
self.num = value;
Ok(())
}

View File

@ -28,19 +28,19 @@ struct Test {
#[py::proto]
impl<'p> PyMappingProtocol<'p> for Test
{
fn __getitem__(&self, py: Python, idx: &PyObject) -> PyResult<PyObjectPtr> {
fn __getitem__(&self, idx: &PyObject) -> PyResult<PyObjectPtr> {
if let Ok(slice) = idx.cast_as::<PySlice>() {
let indices = slice.indices(1000)?;
if indices.start == 100 && indices.stop == 200 && indices.step == 1 {
return Ok("slice".into_object(py))
return Ok("slice".into_object(self.token()))
}
}
else if let Ok(idx) = idx.extract::<isize>() {
if idx == 1 {
return Ok("int".into_object(py))
return Ok("int".into_object(self.token()))
}
}
Err(PyErr::new::<exc::ValueError, _>(py, "error"))
Err(PyErr::new::<exc::ValueError, _>(self.token(), "error"))
}
}