1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
use args;
use method;
use py_method;
use syn;
use utils;
use proc_macro2::{Span, TokenStream};
pub fn py3_init(fnname: &syn::Ident, name: &syn::Ident, doc: syn::Lit) -> TokenStream {
let cb_name: syn::Ident = syn::parse_str(&format!("PyInit_{}", name)).unwrap();
quote! {
#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn #cb_name() -> *mut ::pyo3::ffi::PyObject {
::pyo3::derive_utils::make_module(concat!(stringify!(#name), "\0"), #doc, #fnname)
}
}
}
pub fn py2_init(fnname: &syn::Ident, name: &syn::Ident, doc: syn::Lit) -> TokenStream {
let cb_name: syn::Ident = syn::parse_str(&format!("init{}", name)).unwrap();
quote! {
#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn #cb_name() {
::pyo3::derive_utils::make_module(concat!(stringify!(#name), "\0"), #doc, #fnname)
}
}
}
pub fn process_functions_in_module(func: &mut syn::ItemFn) {
let mut stmts: Vec<syn::Stmt> = Vec::new();
for stmt in func.block.stmts.iter_mut() {
if let syn::Stmt::Item(syn::Item::Fn(ref mut func)) = stmt {
if let Some((module_name, python_name, pyfn_attrs)) =
extract_pyfn_attrs(&mut func.attrs)
{
let function_to_python = add_fn_to_module(func, &python_name, pyfn_attrs);
let function_wrapper_ident = function_wrapper_ident(&func.ident);
let item: syn::ItemFn = parse_quote!{
fn block_wrapper() {
#function_to_python
#module_name.add_function(&#function_wrapper_ident)?;
}
};
stmts.extend(item.block.stmts.into_iter());
}
};
stmts.push(stmt.clone());
}
func.block.stmts = stmts;
}
fn wrap_fn_argument<'a>(input: &'a syn::FnArg, name: &'a syn::Ident) -> Option<method::FnArg<'a>> {
match input {
&syn::FnArg::SelfRef(_) | &syn::FnArg::SelfValue(_) => None,
&syn::FnArg::Captured(ref cap) => {
let (mutability, by_ref, ident) = match cap.pat {
syn::Pat::Ident(ref patid) => (&patid.mutability, &patid.by_ref, &patid.ident),
_ => panic!("unsupported argument: {:?}", cap.pat),
};
let py = match cap.ty {
syn::Type::Path(ref typath) => typath
.path
.segments
.last()
.map(|seg| seg.value().ident == "Python")
.unwrap_or(false),
_ => false,
};
let opt = method::check_arg_ty_and_optional(&name, &cap.ty);
Some(method::FnArg {
name: ident,
mutability: mutability,
by_ref: by_ref,
ty: &cap.ty,
optional: opt,
py,
reference: method::is_ref(&name, &cap.ty),
})
}
&syn::FnArg::Ignored(_) => panic!("ignored argument: {:?}", name),
&syn::FnArg::Inferred(_) => panic!("inferred argument: {:?}", name),
}
}
fn extract_pyfn_attrs(
attrs: &mut Vec<syn::Attribute>,
) -> Option<(syn::Ident, syn::Ident, Vec<args::Argument>)> {
let mut new_attrs = Vec::new();
let mut fnname = None;
let mut modname = None;
let mut fn_attrs = Vec::new();
for attr in attrs.iter() {
match attr.interpret_meta() {
Some(syn::Meta::List(ref list)) if list.ident == "pyfn" => {
let meta: Vec<_> = list.nested.iter().cloned().collect();
if meta.len() >= 2 {
match meta[0] {
syn::NestedMeta::Meta(syn::Meta::Word(ref ident)) => {
modname = Some(ident.clone())
}
_ => panic!("The first parameter of pyfn must be a MetaItem"),
}
match meta[1] {
syn::NestedMeta::Literal(syn::Lit::Str(ref lits)) => {
fnname = Some(syn::parse_str(&lits.value()).unwrap());
}
_ => panic!("The second parameter of pyfn must be a Literal"),
}
if list.nested.len() >= 3 {
fn_attrs = args::parse_arguments(&meta[2..meta.len()]);
}
} else {
panic!("can not parse 'pyfn' params {:?}", attr);
}
}
_ => new_attrs.push(attr.clone()),
}
}
*attrs = new_attrs;
Some((modname?, fnname?, fn_attrs))
}
fn function_wrapper_ident(name: &syn::Ident) -> syn::Ident {
syn::Ident::new(
&format!(
"__pyo3_get_function_{}",
name.to_string().trim_left_matches("r#")
),
Span::call_site(),
)
}
pub fn add_fn_to_module(
func: &syn::ItemFn,
python_name: &syn::Ident,
pyfn_attrs: Vec<args::Argument>,
) -> TokenStream {
let mut arguments = Vec::new();
for input in func.decl.inputs.iter() {
if let Some(fn_arg) = wrap_fn_argument(input, &func.ident) {
arguments.push(fn_arg);
}
}
let ty = method::get_return_info(&func.decl.output);
let spec = method::FnSpec {
tp: method::FnType::Fn,
attrs: pyfn_attrs,
args: arguments,
output: ty,
};
let function_wrapper_ident = function_wrapper_ident(&func.ident);
let wrapper = function_c_wrapper(&func.ident, &spec);
let doc = utils::get_doc(&func.attrs, true);
let tokens = quote! {
fn #function_wrapper_ident(py: ::pyo3::Python) -> ::pyo3::PyObject {
#wrapper
let _def = ::pyo3::class::PyMethodDef {
ml_name: stringify!(#python_name),
ml_meth: ::pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap),
ml_flags: ::pyo3::ffi::METH_VARARGS | ::pyo3::ffi::METH_KEYWORDS,
ml_doc: #doc,
};
let function = unsafe {
::pyo3::PyObject::from_owned_ptr_or_panic(
py,
::pyo3::ffi::PyCFunction_New(
Box::into_raw(Box::new(_def.as_method_def())),
::std::ptr::null_mut()
)
)
};
function
}
};
tokens
}
fn function_c_wrapper(name: &syn::Ident, spec: &method::FnSpec) -> TokenStream {
let names: Vec<syn::Ident> = spec
.args
.iter()
.enumerate()
.map(|item| {
if item.1.py {
syn::Ident::new("_py", Span::call_site())
} else {
syn::Ident::new(&format!("arg{}", item.0), Span::call_site())
}
})
.collect();
let cb = quote! {
::pyo3::ReturnTypeIntoPyResult::return_type_into_py_result(#name(#(#names),*))
};
let body = py_method::impl_arg_params(spec, cb);
let body_to_result = py_method::body_to_result(&body, spec);
quote! {
unsafe extern "C" fn __wrap(
_slf: *mut ::pyo3::ffi::PyObject,
_args: *mut ::pyo3::ffi::PyObject,
_kwargs: *mut ::pyo3::ffi::PyObject) -> *mut ::pyo3::ffi::PyObject
{
const _LOCATION: &'static str = concat!(stringify!(#name), "()");
let _pool = ::pyo3::GILPool::new();
let _py = ::pyo3::Python::assume_gil_acquired();
let _args = _py.from_borrowed_ptr::<::pyo3::types::PyTuple>(_args);
let _kwargs: Option<&::pyo3::types::PyDict> = _py.from_borrowed_ptr_or_opt(_kwargs);
#body_to_result
::pyo3::callback::cb_convert(
::pyo3::callback::PyObjectCallbackConverter, _py, _result)
}
}
}