Debian Codegraph @

src/into_py.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright (c) Meta Platforms, Inc. and affiliates.
2 //
3 // This source code is licensed under the MIT license found in the
4 // LICENSE file in the root directory of this source tree
5
6 use proc_macro::TokenStream;
7 use quote::{format_ident, quote, quote_spanned, ToTokens};
8 use syn::{
9 spanned::Spanned, Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, FieldsNamed,
10 FieldsUnnamed, Type, TypePath, Visibility,
11 };
12
13 pub(crate) fn impl_into_py(ast: &DeriveInput) -> TokenStream {
14 match &ast.data {
15 Data::Enum(e) => impl_into_py_enum(ast, e),
16 Data::Struct(s) => impl_into_py_struct(ast, s),
17 Data::Union(u) => quote_spanned! {
18 u.union_token.span() =>
19 compile_error!("Union type is not supported")
20 }
21 .into(),
22 }
23 }
24
25 fn impl_into_py_enum(ast: &DeriveInput, e: &DataEnum) -> TokenStream {
26 let mut toks = vec![];
27 for var in e.variants.iter() {
28 let varname = &var.ident;
29 match &var.fields {
30 Fields::Named(n) => {
31 let mut fieldnames = vec![];
32 for field in n.named.iter() {
33 if has_attr(&field.attrs, "skip_py") {
34 continue;
35 }
36 fieldnames.push(field.ident.as_ref().unwrap());
37 }
38 let kwargs_toks = fields_to_kwargs(&var.fields, true);
39 toks.push(quote! {
40 Self::#varname { #(#fieldnames,)* .. } => {
41 use pyo3::types::PyAnyMethods;
42
43 let libcst = pyo3::types::PyModule::import(py, "libcst")?;
44 let kwargs = #kwargs_toks ;
45 Ok(libcst
46 .getattr(stringify!(#varname))
47 .expect(stringify!(no #varname found in libcst))
48 .call((), Some(&kwargs))?
49 .into())
50 }
51 })
52 }
53 f @ Fields::Unit => {
54 return quote_spanned! {
55 f.span() =>
56 compile_error!("Empty enum variants not supported")
57 }
58 .into()
59 }
60 Fields::Unnamed(_) => {
61 toks.push(quote! {
62 Self::#varname(x, ..) => x.try_into_py(py),
63 });
64 }
65 }
66 }
67 let ident = &ast.ident;
68 let generics = &ast.generics;
69 let gen = quote! {
70 use pyo3::types::IntoPyDict as _;
71 #[automatically_derived]
•72 impl#generics crate::nodes::traits::py::TryIntoPy<pyo3::Py<pyo3::PyAny>> for #ident #generics {
73 fn try_into_py(self, py: pyo3::Python) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
74 match self {
75 #(#toks)*
76 }
77 }
78 }
79 };
80 gen.into()
81 }
82
83 fn impl_into_py_struct(ast: &DeriveInput, e: &DataStruct) -> TokenStream {
84 let kwargs_toks = fields_to_kwargs(&e.fields, false);
85 let ident = &ast.ident;
86 let generics = &ast.generics;
87 let gen = quote! {
88 use pyo3::types::IntoPyDict as _;
89 #[automatically_derived]
•90 impl#generics crate::nodes::traits::py::TryIntoPy<pyo3::Py<pyo3::PyAny>> for #ident #generics {
91 fn try_into_py(self, py: pyo3::Python) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
92 use pyo3::types::PyAnyMethods;
93 let libcst = pyo3::types::PyModule::import(py, "libcst")?;
94 let kwargs = #kwargs_toks ;
95 Ok(libcst
96 .getattr(stringify!(#ident))
97 .expect(stringify!(no #ident found in libcst))
98 .call((), Some(&kwargs))?
99 .into())
100 }
101 }
102 };
103 gen.into()
104 }
105
106 fn fields_to_kwargs(fields: &Fields, is_enum: bool) -> quote::__private::TokenStream {
107 let mut empty_kwargs = false;
108 let mut py_varnames = vec![];
109 let mut rust_varnames = vec![];
110 let mut optional_py_varnames = vec![];
111 let mut optional_rust_varnames = vec![];
112 match &fields {
113 Fields::Named(FieldsNamed { named, .. }) => {
114 for field in named.iter() {
115 if has_attr(&field.attrs, "skip_py") {
116 continue;
117 }
118 if let Some(ident) = field.ident.as_ref() {
119 let include = if let Visibility::Public(_) = field.vis {
120 true
121 } else {
122 is_enum
123 };
124 if include {
125 let pyname = format_ident!("{}", ident);
126 let rustname = if is_enum {
127 ident.to_token_stream()
128 } else {
129 quote! { self.#ident }
130 };
131 if !has_attr(&field.attrs, "no_py_default") {
132 if let Type::Path(TypePath { path, .. }) = &field.ty {
133 if let Some(first) = path.segments.first() {
134 if first.ident == "Option" {
135 optional_py_varnames.push(pyname);
136 optional_rust_varnames.push(rustname);
137 continue;
138 }
139 }
140 }
141 }
142 py_varnames.push(pyname);
143 rust_varnames.push(rustname);
144 }
145 }
146 }
147 empty_kwargs = py_varnames.is_empty() && optional_py_varnames.is_empty()
148 }
149 Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => {
150 if unnamed.first().is_some() {
151 py_varnames.push(format_ident!("value"));
152 rust_varnames.push(quote! { self.0 });
153 } else {
154 empty_kwargs = true;
155 }
156 }
157 Fields::Unit => {
158 empty_kwargs = true;
159 }
160 };
161 let kwargs_pairs = quote! {
162 #(Some((stringify!(#py_varnames), #rust_varnames.try_into_py(py)?)),)*
163 };
164 let optional_pairs = quote! {
165 #(#optional_rust_varnames.map(|x| x.try_into_py(py)).transpose()?.map(|x| (stringify!(#optional_py_varnames), x)),)*
166 };
167 if empty_kwargs {
168 quote! { pyo3::types::PyDict::new(py) }
169 } else {
170 quote! {
171 [ #kwargs_pairs #optional_pairs ]
172 .iter()
173 .filter(|x| x.is_some())
174 .map(|x| x.as_ref().unwrap())
175 .collect::<Vec<_>>()
176 .into_py_dict(py)?
177 }
178 }
179 }
180
181 fn has_attr(attrs: &[Attribute], name: &'static str) -> bool {
182 attrs.iter().any(|attr| attr.path().is_ident(name))
183 }