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::{extract_spans, Diagnostic};
24use proc_macro2::TokenStream;
25use quote::ToTokens;
26use rustpython_doc as doc;
27use syn::{AttributeArgs, DeriveInput, Item};
28
29pub use compile_bytecode::Compiler;
30
31fn result_to_tokens(result: Result<TokenStream, impl Into<Diagnostic>>) -> TokenStream {
32    result
33        .map_err(|e| e.into())
34        .unwrap_or_else(ToTokens::into_token_stream)
35}
36
37pub fn derive_from_args(input: DeriveInput) -> TokenStream {
38    result_to_tokens(from_args::impl_from_args(input))
39}
40
41pub fn pyclass(attr: AttributeArgs, item: Item) -> TokenStream {
42    if matches!(item, syn::Item::Impl(_) | syn::Item::Trait(_)) {
43        result_to_tokens(pyclass::impl_pyclass_impl(attr, item))
44    } else {
45        result_to_tokens(pyclass::impl_pyclass(attr, item))
46    }
47}
48
49pub fn pyexception(attr: AttributeArgs, item: Item) -> TokenStream {
50    if matches!(item, syn::Item::Impl(_)) {
51        result_to_tokens(pyclass::impl_pyexception_impl(attr, item))
52    } else {
53        result_to_tokens(pyclass::impl_pyexception(attr, item))
54    }
55}
56
57pub fn pymodule(attr: AttributeArgs, item: Item) -> TokenStream {
58    result_to_tokens(pymodule::impl_pymodule(attr, item))
59}
60
61pub fn pystruct_sequence(input: DeriveInput) -> TokenStream {
62    result_to_tokens(pystructseq::impl_pystruct_sequence(input))
63}
64
65pub fn pystruct_sequence_try_from_object(input: DeriveInput) -> TokenStream {
66    result_to_tokens(pystructseq::impl_pystruct_sequence_try_from_object(input))
67}
68
69pub fn py_compile(input: TokenStream, compiler: &dyn Compiler) -> TokenStream {
70    result_to_tokens(compile_bytecode::impl_py_compile(input, compiler))
71}
72
73pub fn py_freeze(input: TokenStream, compiler: &dyn Compiler) -> TokenStream {
74    result_to_tokens(compile_bytecode::impl_py_freeze(input, compiler))
75}
76
77pub fn pypayload(input: DeriveInput) -> TokenStream {
78    result_to_tokens(pypayload::impl_pypayload(input))
79}
80
81pub fn pytraverse(item: DeriveInput) -> TokenStream {
82    result_to_tokens(pytraverse::impl_pytraverse(item))
83}