Debian Codegraph @

src/inflate.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};
8 use syn::{self, spanned::Spanned, Data, DataEnum, DeriveInput, Fields, FieldsUnnamed};
9
10 pub(crate) fn impl_inflate(ast: &DeriveInput) -> TokenStream {
11 match &ast.data {
12 Data::Enum(e) => impl_inflate_enum(ast, e),
13 Data::Struct(s) => quote_spanned! {
14 s.struct_token.span() =>
15 compile_error!("Struct type is not supported")
16 }
17 .into(),
18 Data::Union(u) => quote_spanned! {
19 u.union_token.span() =>
20 compile_error!("Union type is not supported")
21 }
22 .into(),
23 }
24 }
25
26 fn impl_inflate_enum(ast: &DeriveInput, e: &DataEnum) -> TokenStream {
27 let mut varnames = vec![];
28 for var in e.variants.iter() {
29 match &var.fields {
30 Fields::Named(n) => {
31 return quote_spanned! {
32 n.span() =>
33 compile_error!("Named enum fields not supported")
34 }
35 .into()
36 }
37 f @ Fields::Unit => {
38 return quote_spanned! {
39 f.span() =>
40 compile_error!("Empty enum variants not supported")
41 }
42 .into()
43 }
44 Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => {
45 if unnamed.len() > 1 {
46 return quote_spanned! {
47 unnamed.span() =>
48 compile_error!("Multiple unnamed fields not supported")
49 }
50 .into();
51 }
52 varnames.push(&var.ident);
53 }
54 }
55 }
56 let ident = &ast.ident;
57 let generics = &ast.generics;
58 let ident_str = ident.to_string();
59 let inflated_ident = format_ident!(
60 "{}",
61 ident_str
62 .strip_prefix("Deflated")
63 .expect("Cannot implement Inflate on a non-Deflated item")
64 );
65 let gen = quote! {
66 impl#generics Inflate<'a> for #ident #generics {
67 type Inflated = #inflated_ident <'a>;
68 fn inflate(mut self, config: & crate::tokenizer::whitespace_parser::Config<'a>) -> std::result::Result<Self::Inflated, crate::tokenizer::whitespace_parser::WhitespaceError> {
69 match self {
70 #(Self::#varnames(x) => Ok(Self::Inflated::#varnames(x.inflate(config)?)),)*
71 }
72 }
73 }
74 };
75 gen.into()
76 }