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
extern crate proc_macro;
use proc_macro::TokenStream;
use pyo3_derive_backend::{
build_py_class, build_py_function, build_py_methods, build_py_proto, get_doc,
process_functions_in_module, py_init, PyClassArgs, PyFunctionAttr,
};
use quote::quote;
use syn::parse_macro_input;
#[proc_macro_attribute]
pub fn pymodule(attr: TokenStream, input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as syn::ItemFn);
let modname = if attr.is_empty() {
ast.sig.ident.clone()
} else {
parse_macro_input!(attr as syn::Ident)
};
if let Err(err) = process_functions_in_module(&mut ast) {
return err.to_compile_error().into();
}
let doc = match get_doc(&ast.attrs, None, false) {
Ok(doc) => doc,
Err(err) => return err.to_compile_error().into(),
};
let expanded = py_init(&ast.sig.ident, &modname, doc);
quote!(
#ast
#expanded
)
.into()
}
#[proc_macro_attribute]
pub fn pyproto(_: TokenStream, input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as syn::ItemImpl);
let expanded = build_py_proto(&mut ast).unwrap_or_else(|e| e.to_compile_error());
quote!(
#ast
#expanded
)
.into()
}
#[proc_macro_attribute]
pub fn pyclass(attr: TokenStream, input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as syn::ItemStruct);
let args = parse_macro_input!(attr as PyClassArgs);
let expanded = build_py_class(&mut ast, &args).unwrap_or_else(|e| e.to_compile_error());
quote!(
#ast
#expanded
)
.into()
}
#[proc_macro_attribute]
pub fn pymethods(_: TokenStream, input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as syn::ItemImpl);
let expanded = build_py_methods(&mut ast).unwrap_or_else(|e| e.to_compile_error());
quote!(
#ast
#expanded
)
.into()
}
#[proc_macro_attribute]
pub fn pyfunction(attr: TokenStream, input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as syn::ItemFn);
let args = parse_macro_input!(attr as PyFunctionAttr);
let expanded = build_py_function(&mut ast, args).unwrap_or_else(|e| e.to_compile_error());
quote!(
#ast
#expanded
)
.into()
}