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