From 22be5435b70b38c474a9c16164713e437f135111 Mon Sep 17 00:00:00 2001 From: lynskylate Date: Mon, 12 Aug 2019 02:01:08 +0800 Subject: [PATCH] Use pyimpl for implement PyStaticMethod --- vm/src/obj/objstaticmethod.rs | 16 ++++++++-------- vm/src/pyobject.rs | 15 ++++++++++++++- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/vm/src/obj/objstaticmethod.rs b/vm/src/obj/objstaticmethod.rs index a33acf176d..7d72008889 100644 --- a/vm/src/obj/objstaticmethod.rs +++ b/vm/src/obj/objstaticmethod.rs @@ -1,7 +1,8 @@ use super::objtype::PyClassRef; -use crate::pyobject::{PyContext, PyObjectRef, PyRef, PyResult, PyValue}; +use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue}; use crate::vm::VirtualMachine; +#[pyclass] #[derive(Clone, Debug)] pub struct PyStaticMethod { pub callable: PyObjectRef, @@ -14,7 +15,9 @@ impl PyValue for PyStaticMethod { } } -impl PyStaticMethodRef { +#[pyimpl] +impl PyStaticMethod { + #[pymethod(name = "__new__")] fn new( cls: PyClassRef, callable: PyObjectRef, @@ -26,15 +29,12 @@ impl PyStaticMethodRef { .into_ref_with_type(vm, cls) } - fn get(self, _inst: PyObjectRef, _owner: PyObjectRef, _vm: &VirtualMachine) -> PyResult { + #[pymethod(name = "__get__")] + fn get(&self, _inst: PyObjectRef, _owner: PyObjectRef, _vm: &VirtualMachine) -> PyResult { Ok(self.callable.clone()) } } pub fn init(context: &PyContext) { - let staticmethod_type = &context.staticmethod_type; - extend_class!(context, staticmethod_type, { - "__get__" => context.new_rustfunc(PyStaticMethodRef::get), - "__new__" => context.new_rustfunc(PyStaticMethodRef::new), - }); + PyStaticMethod::extend_class(context, &context.staticmethod_type); } diff --git a/vm/src/pyobject.rs b/vm/src/pyobject.rs index ba40d54735..71d47e4cfe 100644 --- a/vm/src/pyobject.rs +++ b/vm/src/pyobject.rs @@ -47,7 +47,7 @@ use crate::obj::objproperty::PropertyBuilder; use crate::obj::objrange; use crate::obj::objset::{self, PySet}; use crate::obj::objslice; -use crate::obj::objstaticmethod; +use crate::obj::objstaticmethod::{self, PyStaticMethod}; use crate::obj::objstr; use crate::obj::objsuper; use crate::obj::objtuple::{self, PyTuple, PyTupleRef}; @@ -716,6 +716,19 @@ impl PyContext { ) } + pub fn new_staticmethod(&self, f: F) -> PyObjectRef + where + F: IntoPyNativeFunc, + { + PyObject::new( + PyStaticMethod { + callable: self.new_rustfunc(f), + }, + self.staticmethod_type(), + None, + ) + } + pub fn new_classmethod(&self, f: F) -> PyObjectRef where F: IntoPyNativeFunc,