Skip to main content

rustpython_derive_impl/
lib.rs

1#![recursion_limit = "128"]
2#![doc(html_logo_url = "https://raw.githubusercontent.com/RustPython/RustPython/main/logo.png")]
3#![doc(html_root_url = "https://docs.rs/rustpython-derive/")]
4
5extern crate proc_macro;
6
7#[macro_use]
8extern crate maplit;
9
10#[macro_use]
11mod error;
12#[macro_use]
13mod util;
14
15mod compile_bytecode;
16mod from_args;
17mod pyclass;
18mod pymodule;
19mod pypayload;
20mod pystructseq;
21mod pytraverse;
22
23use error::Diagnostic;
24use proc_macro2::TokenStream;
25use quote::ToTokens;
26use syn::{DeriveInput, Item};
27use syn_ext::types::PunctuatedNestedMeta;
28
29pub use pymodule::PyModuleArgs;
30
31pub use compile_bytecode::Compiler;
32
33fn result_to_tokens(result: Result<TokenStream, impl Into<Diagnostic>>) -> TokenStream {
34    result
35        .map_err(|e| e.into())
36        .unwrap_or_else(ToTokens::into_token_stream)
37}
38
39pub fn derive_from_args(input: DeriveInput) -> TokenStream {
40    result_to_tokens(from_args::impl_from_args(input))
41}
42
43pub fn pyclass(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
44    if matches!(item, syn::Item::Impl(_) | syn::Item::Trait(_)) {
45        result_to_tokens(pyclass::impl_pyclass_impl(attr, item))
46    } else {
47        result_to_tokens(pyclass::impl_pyclass(attr, item))
48    }
49}
50
51pub fn pyexception(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
52    if matches!(item, syn::Item::Impl(_)) {
53        result_to_tokens(pyclass::impl_pyexception_impl(attr, item))
54    } else {
55        result_to_tokens(pyclass::impl_pyexception(attr, item))
56    }
57}
58
59pub fn pymodule(attr: PyModuleArgs, item: Item) -> TokenStream {
60    result_to_tokens(pymodule::impl_pymodule(attr, item))
61}
62
63pub fn pystruct_sequence(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
64    result_to_tokens(pystructseq::impl_pystruct_sequence(attr, item))
65}
66
67pub fn pystruct_sequence_data(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
68    result_to_tokens(pystructseq::impl_pystruct_sequence_data(attr, item))
69}
70
71pub fn py_compile(input: TokenStream, compiler: &dyn Compiler) -> TokenStream {
72    result_to_tokens(compile_bytecode::impl_py_compile(input, compiler))
73}
74
75pub fn py_freeze(input: TokenStream, compiler: &dyn Compiler) -> TokenStream {
76    result_to_tokens(compile_bytecode::impl_py_freeze(input, compiler))
77}
78
79pub fn pypayload(input: DeriveInput) -> TokenStream {
80    result_to_tokens(pypayload::impl_pypayload(input))
81}
82
83pub fn pytraverse(item: DeriveInput) -> TokenStream {
84    result_to_tokens(pytraverse::impl_pytraverse(item))
85}