Debian Codegraph @

src/cstnode.rs

raw symbols SCIP
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 self,
10 parse::{Parse, ParseStream},
11 parse_quote,
12 punctuated::{Pair, Punctuated},
13 spanned::Spanned,
14 token::Comma,
15 AngleBracketedGenericArguments, Attribute, Data, DataEnum, DataStruct, DeriveInput, Field,
16 Fields, FieldsNamed, FieldsUnnamed, GenericArgument, Generics, Ident, Meta, Path,
17 PathArguments, PathSegment, Token, Type, TypePath, Visibility,
18 };
19
20 pub(crate) struct CSTNodeParams {
21 traits: Punctuated<SupportedTrait, Token![,]>,
22 }
23
24 #[derive(PartialEq, Eq)]
25 enum SupportedTrait {
26 ParenthesizedNode,
27 Codegen,
28 Inflate,
29 NoIntoPy,
30 Default,
31 }
32
33 pub(crate) fn impl_cst_node(ast: DeriveInput, args: CSTNodeParams) -> TokenStream {
34 match ast.data {
35 Data::Enum(e) => impl_enum(args, ast.attrs, ast.vis, ast.ident, ast.generics, e),
36 Data::Struct(s) => impl_struct(args, ast.attrs, ast.vis, ast.ident, ast.generics, s),
37 Data::Union(u) => quote_spanned! {
38 u.union_token.span() =>
39 compile_error!("Union type is not supported")
40 }
41 .into(),
42 }
43 }
44
45 impl CSTNodeParams {
46 fn has_trait(&self, treyt: &SupportedTrait) -> bool {
47 self.traits.iter().any(|x| x == treyt)
48 }
49 }
50
51 impl Parse for SupportedTrait {
52 fn parse(input: ParseStream) -> syn::Result<Self> {
53 if input.peek(Ident) {
54 let id: Ident = input.parse()?;
55 return match id.to_string().as_str() {
56 "ParenthesizedNode" => Ok(Self::ParenthesizedNode),
57 "Codegen" => Ok(Self::Codegen),
58 "Inflate" => Ok(Self::Inflate),
59 "NoIntoPy" => Ok(Self::NoIntoPy),
60 "Default" => Ok(Self::Default),
61 _ => Err(input.error("Not a supported trait to derive for cst_node")),
62 };
63 }
64 Err(input.error("Pass in trait names to be derived"))
65 }
66 }
67
68 impl Parse for CSTNodeParams {
69 fn parse(input: ParseStream) -> syn::Result<Self> {
70 Ok(Self {
71 traits: input.parse_terminated(SupportedTrait::parse, Token![,])?,
72 })
73 }
74 }
75
76 // enum Foo<'a> {
77 // Variant(Box<Variant<'a>>),
78 // }
79 // =>
80 // enum Foo<'a> {
81 // Variant(Box<Variant<'a>>),
82 // }
83 // enum DeflatedFoo<'r, 'a> {
84 // Variant(Box<DeflatedVariant<'r, 'a>>),
85 // }
86
87 fn impl_enum(
88 args: CSTNodeParams,
89 mut attrs: Vec<Attribute>,
90 vis: Visibility,
91 ident: Ident,
92 generics: Generics,
93 mut e: DataEnum,
94 ) -> TokenStream {
95 let deflated_vis = vis.clone();
96 let deflated_ident = format_ident!("Deflated{}", &ident);
97 let deflated_generics: Generics = parse_quote!(<'r, 'a>);
98 let mut deflated_variant_tokens = vec![];
99
100 for var in e.variants.iter_mut() {
101 let (inflated_fields, deflated_fields) = impl_fields(var.fields.clone());
102 var.fields = deflated_fields;
103 deflated_variant_tokens.push(var.to_token_stream());
104 var.fields = inflated_fields;
105 }
106 add_inflated_attrs(&args, &mut attrs);
107 let inflated = DeriveInput {
108 attrs,
109 vis,
110 ident,
111 generics,
112 data: Data::Enum(e),
113 };
114
115 let deflated_attrs = get_deflated_attrs(&args);
116
117 let gen = quote! {
118 #[derive(Debug, PartialEq, Eq, Clone)]
119 #inflated
120
121 #[derive(Debug, PartialEq, Eq, Clone)]
122 #(#deflated_attrs)*
123 #deflated_vis enum #deflated_ident#deflated_generics {
124 #(#deflated_variant_tokens,)*
125 }
126 };
127 gen.into()
128 }
129
130 fn get_deflated_attrs(args: &CSTNodeParams) -> Vec<Attribute> {
131 let mut deflated_attrs: Vec<Attribute> = vec![];
132 if args.has_trait(&SupportedTrait::Inflate) {
133 deflated_attrs.push(parse_quote!(#[derive(Inflate)]));
134 }
135 if args.has_trait(&SupportedTrait::ParenthesizedNode) {
136 deflated_attrs.push(parse_quote!(#[derive(ParenthesizedDeflatedNode)]))
137 }
138 if args.has_trait(&SupportedTrait::Default) {
139 deflated_attrs.push(parse_quote!(#[derive(Default)]));
140 }
141 deflated_attrs
142 }
143
144 fn add_inflated_attrs(args: &CSTNodeParams, attrs: &mut Vec<Attribute>) {
145 if args.has_trait(&SupportedTrait::Codegen) {
146 attrs.push(parse_quote!(#[derive(Codegen)]));
147 }
148 if args.has_trait(&SupportedTrait::ParenthesizedNode) {
149 attrs.push(parse_quote!(#[derive(ParenthesizedNode)]));
150 }
151 if args.has_trait(&SupportedTrait::Default) {
152 attrs.push(parse_quote!(#[derive(Default)]));
153 }
154 if !args.has_trait(&SupportedTrait::NoIntoPy) {
155 attrs.push(parse_quote!(#[cfg_attr(feature = "py", derive(TryIntoPy))]));
156 }
157 }
158
159 // pub struct Foo<'a> {
160 // pub bar: Bar<'a>,
161 // pub value: &'a str,
162 // pub whitespace_after: SimpleWhitespace<'a>,
163 // pub(crate) tok: Option<TokenRef>,
164 // }
165 // =>
166 // pub struct Foo<'a> {
167 // pub bar: Bar<'a>,
168 // pub value: &'a str,
169 // pub whitespace_after: SimpleWhitespace<'a>,
170 // }
171 // struct DeflatedFoo<'r, 'a> {
172 // pub bar: DeflatedBar<'r, 'a>,
173 // pub value: &'a str,
174 // pub tok: Option<TokenRef<'r, 'a>>
175 // }
176
177 fn impl_struct(
178 args: CSTNodeParams,
179 mut attrs: Vec<Attribute>,
180 vis: Visibility,
181 ident: Ident,
182 generics: Generics,
183 mut s: DataStruct,
184 ) -> TokenStream {
185 let deflated_vis = vis.clone();
186 let deflated_ident = format_ident!("Deflated{}", &ident);
187 let deflated_generics: Generics = parse_quote!(<'r, 'a>);
188
189 let (inflated_fields, deflated_fields) = impl_fields(s.fields);
190 s.fields = inflated_fields;
191
192 add_inflated_attrs(&args, &mut attrs);
193
194 let inflated = DeriveInput {
195 attrs,
196 vis,
197 ident,
198 generics,
199 data: Data::Struct(s),
200 };
201
202 let deflated_attrs = get_deflated_attrs(&args);
203
204 let gen = quote! {
205 #[derive(Debug, PartialEq, Eq, Clone)]
206 #inflated
207
208 #[derive(Debug, PartialEq, Eq, Clone)]
209 #(#deflated_attrs)*
210 #deflated_vis struct #deflated_ident#deflated_generics
211 #deflated_fields
212
213 };
214 gen.into()
215 }
216
217 fn impl_fields(fields: Fields) -> (Fields, Fields) {
218 match &fields {
219 Fields::Unnamed(fs) => {
220 let deflated_fields = impl_unnamed_fields(fs.clone());
221 (fields, Fields::Unnamed(deflated_fields))
222 }
223 Fields::Named(fs) => impl_named_fields(fs.clone()),
224 Fields::Unit => (Fields::Unit, Fields::Unit),
225 }
226 }
227
228 fn impl_unnamed_fields(mut deflated_fields: FieldsUnnamed) -> FieldsUnnamed {
229 let mut added_lifetime = false;
230 deflated_fields.unnamed = deflated_fields
231 .unnamed
232 .into_pairs()
233 .map(|pair| {
234 let (deflated, lifetime) = make_into_deflated(pair);
235 added_lifetime |= lifetime;
236 deflated
237 })
238 .collect();
239
240 // Make sure all Deflated* types have 'r 'a lifetime params
241 if !added_lifetime {
242 deflated_fields.unnamed.push(parse_quote! {
243 std::marker::PhantomData<&'r &'a ()>
244 });
245 }
246 deflated_fields
247 }
248
249 fn impl_named_fields(mut fields: FieldsNamed) -> (Fields, Fields) {
250 let mut deflated_fields = fields.clone();
251 let mut added_lifetime = false;
252 // Drop whitespace fields from deflated fields
253 // And add lifetimes to tokenref fields
254 deflated_fields.named = deflated_fields
255 .named
256 .into_pairs()
257 .filter(|pair| {
258 let id = pair.value().ident.as_ref().unwrap().to_string();
259 !id.contains("whitespace")
260 && id != "footer"
261 && id != "header"
262 && id != "leading_lines"
263 && id != "lines_after_decorators"
264 })
265 .map(|pair| {
266 if is_builtin(pair.value()) {
267 pair
268 } else {
269 let (deflated, lifetime) = make_into_deflated(pair);
270 added_lifetime |= lifetime;
271 deflated
272 }
273 })
274 .map(|pair| {
275 let (mut val, punct) = pair.into_tuple();
276 val.attrs = val.attrs.into_iter().filter(is_not_intopy_attr).collect();
277 Pair::new(val, punct)
278 })
279 .collect();
280
281 // Make sure all Deflated* types have 'r 'a lifetime params
282 if !added_lifetime {
283 deflated_fields.named.push(parse_quote! {
284 _phantom: std::marker::PhantomData<&'r &'a ()>
285 });
286 }
287
288 // Drop tokenref fields from inflated fields
289 fields.named = fields
290 .named
291 .into_pairs()
292 .filter(|pair| !is_token_ref(pair.value()))
293 .collect();
294
295 (Fields::Named(fields), Fields::Named(deflated_fields))
296 }
297
298 fn is_builtin(field: &Field) -> bool {
299 get_pathseg(&field.ty)
300 .map(|seg| {
301 let segstr = seg.ident.to_string();
302 segstr == "str" || segstr == "bool" || segstr == "String"
303 })
304 .unwrap_or_default()
305 }
306
307 fn is_token_ref(field: &Field) -> bool {
308 if let Some(seg) = rightmost_path_segment(&field.ty) {
309 return format!("{}", seg.ident) == "TokenRef";
310 }
311 false
312 }
313
314 // foo::bar -> foo::Deflatedbar<'r, 'a>
315 fn make_into_deflated(mut pair: Pair<Field, Comma>) -> (Pair<Field, Comma>, bool) {
316 let mut added_lifetime = true;
317 if let Some(seg) = rightmost_path_segment_mut(&mut pair.value_mut().ty) {
318 let seg_name = seg.ident.to_string();
319 if seg_name != "TokenRef" {
320 seg.ident = format_ident!("Deflated{}", seg_name);
321 }
322 match seg.arguments {
323 PathArguments::None => {
324 seg.arguments = PathArguments::AngleBracketed(parse_quote!(<'r, 'a>));
325 }
326 PathArguments::AngleBracketed(AngleBracketedGenericArguments {
327 ref mut args, ..
328 }) => {
329 args.insert(0, parse_quote!('r));
330 }
331 _ => todo!(),
332 }
333 } else {
334 added_lifetime = false;
335 }
336 (pair, added_lifetime)
337 }
338
339 // foo::bar::baz<quux<'a>> -> baz<quux<'a>>
340 fn get_pathseg(ty: &Type) -> Option<&PathSegment> {
341 match ty {
342 Type::Path(TypePath { path, .. }) => path.segments.last(),
343 _ => None,
344 }
345 }
346
347 // foo::bar::baz<quux<'a>> -> quux<'a>
348 fn rightmost_path_segment(ty: &Type) -> Option<&PathSegment> {
349 let mut candidate = get_pathseg(ty);
350 loop {
351 if let Some(pathseg) = candidate {
352 if let PathArguments::AngleBracketed(AngleBracketedGenericArguments { args, .. }) =
353 &pathseg.arguments
354 {
355 if let Some(GenericArgument::Type(t)) = args.last() {
356 candidate = get_pathseg(t);
357 continue;
358 }
359 }
360 }
361 break;
362 }
363 candidate
364 }
365
366 fn get_pathseg_mut(ty: &mut Type) -> Option<&mut PathSegment> {
367 match ty {
368 Type::Path(TypePath { path, .. }) => path.segments.last_mut(),
369 _ => None,
370 }
371 }
372
373 fn has_more_mut(candidate: &Option<&mut PathSegment>) -> bool {
374 if let Some(PathArguments::AngleBracketed(AngleBracketedGenericArguments {
375 ref args, ..
376 })) = candidate.as_ref().map(|c| &c.arguments)
377 {
378 matches!(args.last(), Some(GenericArgument::Type(_)))
379 } else {
380 false
381 }
382 }
383
384 fn rightmost_path_segment_mut(ty: &mut Type) -> Option<&mut PathSegment> {
385 let mut candidate = get_pathseg_mut(ty);
386
387 while has_more_mut(&candidate) {
388 candidate = match candidate.unwrap().arguments {
389 PathArguments::AngleBracketed(AngleBracketedGenericArguments {
390 ref mut args, ..
391 }) => {
392 if let Some(GenericArgument::Type(t)) = args.last_mut() {
393 get_pathseg_mut(t)
394 } else {
395 unreachable!();
396 }
397 }
398 _ => unreachable!(),
399 };
400 }
401
402 candidate
403 }
404
405 fn is_not_intopy_attr(attr: &Attribute) -> bool {
406 let path = attr.path();
407 // support #[cfg_attr(feature = "py", skip_py)]
408 if path.is_ident("cfg_attr") {
409 return match attr.parse_args_with(|input: ParseStream| {
410 let _: Meta = input.parse()?;
411 let _: Token![,] = input.parse()?;
412 let nested_path: Path = input.parse()?;
413 let _: Option<Token![,]> = input.parse()?;
414 Ok(nested_path)
415 }) {
416 Ok(nested_path) => !is_intopy_attr_path(&nested_path),
417 Err(_) => false,
418 };
419 }
420 !is_intopy_attr_path(path)
421 }
422
423 fn is_intopy_attr_path(path: &Path) -> bool {
424 path.is_ident("skip_py") || path.is_ident("no_py_default")
425 }
426
427 #[test]
428 fn trybuild() {
429 let t = trybuild::TestCases::new();
430 t.pass("tests/pass/*.rs");
431 }
432
433 #[test]
434 fn test_is_not_intopy_attr() {
435 assert!(!is_not_intopy_attr(&parse_quote!(#[skip_py])));
436 assert!(!is_not_intopy_attr(&parse_quote!(#[no_py_default])));
437 assert!(!is_not_intopy_attr(
438 &parse_quote!(#[cfg_attr(foo="bar",skip_py)])
439 ));
440 assert!(!is_not_intopy_attr(
441 &parse_quote!(#[cfg_attr(foo="bar",no_py_default)])
442 ));
443 assert!(is_not_intopy_attr(&parse_quote!(#[skippy])));
444 assert!(is_not_intopy_attr(
445 &parse_quote!(#[cfg_attr(foo="bar",skippy)])
446 ));
447 }