1use crate::PyObject;
2use crate::object::PyTypeObject;
3use crate::object::define_py_check;
4use crate::pystate::with_vm;
5use crate::util::{CStrExt, FfiPtrExt};
6use core::ffi::{c_char, c_int};
7use rustpython_vm::function::{FuncArgs, HeapMethodDef, ItemDoc, PosArgs, PyMethodFlags};
8use rustpython_vm::{AsObject, PyObjectRef, PyRef, PyResult, VirtualMachine};
9
10define_py_check!(fn PyCFunction_Check, types.builtin_function_or_method_type);
11define_py_check!(exact fn PyCFunction_CheckExact, types.builtin_function_or_method_type);
12
13#[repr(C)]
14pub struct PyMethodDef {
15 pub ml_name: *const c_char,
16 pub ml_meth: PyMethodPointer,
17 pub ml_flags: c_int,
18 pub ml_doc: *const c_char,
19}
20
21#[repr(C)]
22#[derive(Copy, Clone)]
23#[allow(non_snake_case)]
24pub union PyMethodPointer {
25 pub PyCFunction: unsafe extern "C" fn(slf: *mut PyObject, args: *mut PyObject) -> *mut PyObject,
26 pub PyCFunctionWithKeywords: unsafe extern "C" fn(
27 slf: *mut PyObject,
28 args: *mut PyObject,
29 kwargs: *mut PyObject,
30 ) -> *mut PyObject,
31 pub PyCFunctionFast: unsafe extern "C" fn(
32 slf: *mut PyObject,
33 args: *const *mut PyObject,
34 nargs: isize,
35 ) -> *mut PyObject,
36 pub PyCFunctionFastWithKeywords: unsafe extern "C" fn(
37 slf: *mut PyObject,
38 args: *const *mut PyObject,
39 nargs: isize,
40 kwnames: *mut PyObject,
41 ) -> *mut PyObject,
42}
43
44pub(crate) fn build_method_def(
45 vm: &VirtualMachine,
46 ml: &PyMethodDef,
47 has_self: bool,
48) -> PyResult<PyRef<HeapMethodDef>> {
49 let name = unsafe { ml.ml_name.try_as_str(vm) }?;
50
51 let doc = unsafe { ml.ml_doc.try_as_str_opt(vm) }?;
52 let doc = doc
53 .filter(|doc| !doc.is_empty())
54 .map_or(ItemDoc::NONE, |doc| {
55 let text: &'static str = Box::leak(doc.to_owned().into_boxed_str());
56 ItemDoc::static_text(text)
57 });
58
59 let flags = PyMethodFlags::from_bits(ml.ml_flags as u32)
60 .ok_or_else(|| vm.new_system_error("PyMethodDef contains unknown flags"))?;
61 let has_self = has_self && !flags.contains(PyMethodFlags::STATIC);
62
63 let method = ml.ml_meth;
64
65 if flags.contains(PyMethodFlags::METHOD) {
66 return Err(vm.new_system_error("METH_METHOD is not supported on abi3"));
67 }
68
69 let call_flags = flags
70 & (PyMethodFlags::VARARGS
71 | PyMethodFlags::KEYWORDS
72 | PyMethodFlags::NOARGS
73 | PyMethodFlags::O
74 | PyMethodFlags::FASTCALL);
75
76 bitflags::bitflags_match!(call_flags, {
77 PyMethodFlags::NOARGS => {
78 if has_self {
79 let callable = move |zelf: PyObjectRef, vm: &VirtualMachine| unsafe {
80 let f = method.PyCFunction;
81 f(zelf.as_raw().cast_mut(), core::ptr::null_mut()).assume_owned_or_err(vm)
82 };
83 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
84 } else {
85 let callable = move |vm: &VirtualMachine| unsafe {
86 let f = method.PyCFunction;
87 f(core::ptr::null_mut(), core::ptr::null_mut()).assume_owned_or_err(vm)
88 };
89 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
90 }
91 },
92 PyMethodFlags::VARARGS => {
93 let callable = move |args: PosArgs, vm: &VirtualMachine| unsafe {
94 call_function(vm, method, flags, Some(args))
95 };
96 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
97 },
98 PyMethodFlags::VARARGS | PyMethodFlags::KEYWORDS => {
99 let callable = move | args: FuncArgs, vm: &VirtualMachine| unsafe {
100 call_function_with_keywords(vm, method, flags, args)
101 };
102 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
103 },
104 PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS => {
105 let callable = move |args: FuncArgs, vm: &VirtualMachine| unsafe {
106 call_fast_function_with_keywords(vm, method, flags, args)
107 };
108 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
109 },
110 PyMethodFlags::FASTCALL => {
111 let callable = move |args: PosArgs, vm: &VirtualMachine| unsafe {
112 call_fast_function(vm, method, flags, args)
113 };
114 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
115 },
116 PyMethodFlags::O => {
117 let f = unsafe { method.PyCFunction };
118 if has_self {
119 let callable = move |zelf: PyObjectRef, arg: PyObjectRef, vm: &VirtualMachine| -> PyResult {
120 unsafe { f(zelf.as_raw().cast_mut(), arg.as_raw().cast_mut()).assume_owned_or_err(vm) }
121 };
122 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
123 } else {
124 let callable = move |arg: PyObjectRef, vm: &VirtualMachine| -> PyResult {
125 unsafe { f(core::ptr::null_mut(), arg.as_raw().cast_mut()).assume_owned_or_err(vm) }
126 };
127 Ok(vm.ctx.new_method_def(name, callable, flags, doc))
128 }
129 },
130 _ => {
131 Err(vm.new_system_error(format!(
132 "function {name} has unsupported or invalid calling-convention flags: {flags:?}"
133 )))
134 },
135 })
136}
137
138unsafe fn call_function<A: Into<FuncArgs>>(
139 vm: &VirtualMachine,
140 method: PyMethodPointer,
141 flags: PyMethodFlags,
142 args: Option<A>,
143) -> PyResult {
144 let f = unsafe { method.PyCFunction };
145 let (slf, arg_tuple) = if let Some(mut args) = args.map(Into::into) {
146 let slf = take_self_arg(&mut args, flags);
147 let arg_tuple = vm.ctx.new_tuple(args.args);
148 (slf, Some(arg_tuple))
149 } else {
150 (None, None)
151 };
152
153 let slf_ptr = slf
154 .as_ref()
155 .map(|obj| obj.as_object().as_raw().cast_mut())
156 .unwrap_or_default();
157
158 let arg_ptr = arg_tuple
159 .as_ref()
160 .map(|tuple| tuple.as_object().as_raw().cast_mut())
161 .unwrap_or_default();
162
163 unsafe { f(slf_ptr, arg_ptr).assume_owned_or_err(vm) }
164}
165
166unsafe fn call_function_with_keywords(
167 vm: &VirtualMachine,
168 method: PyMethodPointer,
169 flags: PyMethodFlags,
170 mut args: FuncArgs,
171) -> PyResult {
172 let f = unsafe { method.PyCFunctionWithKeywords };
173 let slf = take_self_arg(&mut args, flags);
174 let slf_ptr = slf
175 .as_ref()
176 .map(|obj| obj.as_object().as_raw().cast_mut())
177 .unwrap_or_default();
178 let arg_tuple = vm.ctx.new_tuple(args.args);
179 let kwargs = vm.ctx.new_dict();
180 for (k, v) in args.kwargs {
181 kwargs.set_item(&*k, v, vm)?;
182 }
183 unsafe {
184 f(
185 slf_ptr,
186 arg_tuple.as_object().as_raw().cast_mut(),
187 kwargs.as_object().as_raw().cast_mut(),
188 )
189 .assume_owned_or_err(vm)
190 }
191}
192
193unsafe fn call_fast_function_with_keywords(
194 vm: &VirtualMachine,
195 method: PyMethodPointer,
196 flags: PyMethodFlags,
197 mut args: FuncArgs,
198) -> PyResult {
199 let f = unsafe { method.PyCFunctionFastWithKeywords };
200 let slf = take_self_arg(&mut args, flags);
201 let slf_ptr = slf
202 .as_ref()
203 .map(|obj| obj.as_object().as_raw().cast_mut())
204 .unwrap_or_default();
205 let nargs = args.args.len();
206 let mut fastcall_args = args.args;
207 let kwnames_tuple = if !args.kwargs.is_empty() {
208 let mut kwnames = Vec::with_capacity(args.kwargs.len());
209 for (k, v) in args.kwargs {
210 kwnames.push(vm.ctx.new_str(k).into());
211 fastcall_args.push(v);
212 }
213 Some(vm.ctx.new_tuple(kwnames))
214 } else {
215 None
216 };
217 let kwnames_ptr = kwnames_tuple
218 .as_ref()
219 .map(|tuple| tuple.as_object().as_raw().cast_mut())
220 .unwrap_or_default();
221 let fastcall_arg_ptrs = fastcall_args.as_ptr().cast::<*mut PyObject>();
225 unsafe { f(slf_ptr, fastcall_arg_ptrs, nargs as isize, kwnames_ptr).assume_owned_or_err(vm) }
226}
227
228unsafe fn call_fast_function(
229 vm: &VirtualMachine,
230 method: PyMethodPointer,
231 flags: PyMethodFlags,
232 args: PosArgs,
233) -> PyResult {
234 let f = unsafe { method.PyCFunctionFast };
235 let mut args: FuncArgs = args.into();
236 let slf = take_self_arg(&mut args, flags);
237 let slf_ptr = slf
238 .as_ref()
239 .map(|obj| obj.as_object().as_raw().cast_mut())
240 .unwrap_or_default();
241 let fastcall_arg_ptrs = args.args.as_mut_ptr().cast::<*mut PyObject>();
245 unsafe { f(slf_ptr, fastcall_arg_ptrs, args.args.len() as isize).assume_owned_or_err(vm) }
246}
247
248fn take_self_arg(args: &mut FuncArgs, flags: PyMethodFlags) -> Option<PyObjectRef> {
249 if flags.contains(PyMethodFlags::STATIC) {
250 None
251 } else {
252 args.take_positional()
253 }
254}
255
256#[unsafe(no_mangle)]
257pub unsafe extern "C" fn PyCMethod_New(
258 ml: *mut PyMethodDef,
259 slf: *mut PyObject,
260 _module: *mut PyObject,
261 _cls: *mut PyTypeObject,
262) -> *mut PyObject {
263 with_vm(|vm| -> PyResult {
264 assert!(
265 _cls.is_null(),
266 "PyCMethod_New does not support METH_METHOD on abi3"
267 );
268 let ml = unsafe { &*ml };
269 let zelf = unsafe { slf.assume_borrowed_or_opt() }.map(ToOwned::to_owned);
270 Ok(build_method_def(vm, ml, zelf.is_some())?
271 .build_function(vm, zelf)
272 .into())
273 })
274}
275
276#[unsafe(no_mangle)]
277pub unsafe extern "C" fn PyCFunction_New(
278 ml: *mut PyMethodDef,
279 slf: *mut PyObject,
280) -> *mut PyObject {
281 unsafe { PyCMethod_New(ml, slf, core::ptr::null_mut(), core::ptr::null_mut()) }
282}
283
284#[unsafe(no_mangle)]
285pub unsafe extern "C" fn PyCFunction_NewEx(
286 ml: *mut PyMethodDef,
287 slf: *mut PyObject,
288 module: *mut PyObject,
289) -> *mut PyObject {
290 unsafe { PyCMethod_New(ml, slf, module, core::ptr::null_mut()) }
291}
292
293#[cfg(test)]
294mod tests {
295 use pyo3::exceptions::PyException;
296 use pyo3::ffi::{PyLong_FromLong, PyObject};
297 use pyo3::prelude::*;
298 use pyo3::types::{PyCFunction, PyInt, PyString};
299
300 #[test]
301 fn closure_function() {
302 Python::attach(|py| {
303 let f = PyCFunction::new_closure(py, None, None, |_args, _kwargs| "Hello from Rust!")
304 .unwrap();
305
306 assert_eq!(
307 f.call0().unwrap().cast::<PyString>().unwrap(),
308 "Hello from Rust!"
309 );
310 })
311 }
312
313 #[test]
314 fn function_no_args() {
315 Python::attach(|py| {
316 unsafe extern "C" fn c_fn(_self: *mut PyObject, _args: *mut PyObject) -> *mut PyObject {
317 assert!(_self.is_null());
318 assert!(_args.is_null());
319 unsafe { PyLong_FromLong(4200) }
320 }
321
322 let py_fn = PyCFunction::new(py, c_fn, c"py_fn", c"", None).unwrap();
323
324 let result = py_fn
325 .call0()
326 .unwrap()
327 .cast::<PyInt>()
328 .unwrap()
329 .extract::<u32>()
330 .unwrap();
331 assert_eq!(result, 4200);
332
333 assert!(py_fn.call((1,), None).is_err());
334 assert!(py_fn.call((1, 2), None).is_err());
335 })
336 }
337
338 #[test]
339 fn closure_function_error() {
340 Python::attach(|py| {
341 let f = PyCFunction::new_closure(py, None, None, |_args, _kwargs| {
342 Err::<(), _>(PyException::new_err("Something went wrong"))
343 })
344 .unwrap();
345
346 let err = f.call0().unwrap_err();
347 assert_eq!(
348 err.value(py).repr().unwrap(),
349 "Exception('Something went wrong')"
350 );
351 })
352 }
353
354 #[test]
355 fn wrap_static_no_args_function() {
356 #[pyfunction()]
357 fn f() {}
358
359 Python::attach(|py| {
360 let module = PyModule::new(py, "test_wrap_pyfunction_forms").unwrap();
361
362 let func = wrap_pyfunction!(f, &module).unwrap();
363 func.call0().unwrap();
364 });
365 }
366}