Debian Codegraph @

src/codegen.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::{quote, quote_spanned};
8 use syn::{self, spanned::Spanned, Data, DataEnum, DeriveInput, Fields, FieldsUnnamed};
9
10 pub(crate) fn impl_codegen(ast: &DeriveInput) -> TokenStream {
11 match &ast.data {
12 Data::Enum(e) => impl_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_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 gen = quote! {
59 impl<'a> Codegen<'a> for #ident #generics {
60 fn codegen(&self, state: &mut CodegenState<'a>) {
61 match self {
62 #(Self::#varnames(x) => x.codegen(state),)*
63 }
64 }
65 }
66 };
67 gen.into()
68 }