Skip to main content

apache_avro_derive/enums/
plain.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::attributes::{NamedTypeOptions, VariantOptions};
19use crate::case::RenameRule;
20use crate::enums::default_enum_variant;
21use crate::{aliases, preserve_optional};
22use proc_macro2::{Span, TokenStream};
23use quote::quote;
24use syn::spanned::Spanned;
25use syn::{DataEnum, Fields};
26
27pub fn schema_def(
28    container_attrs: &NamedTypeOptions,
29    data_enum: &DataEnum,
30    ident_span: Span,
31) -> Result<TokenStream, Vec<syn::Error>> {
32    let doc = preserve_optional(container_attrs.doc.as_ref());
33    let enum_aliases = aliases(&container_attrs.aliases);
34    if data_enum.variants.iter().all(|v| Fields::Unit == v.fields) {
35        let default_value = default_enum_variant(data_enum, ident_span)?;
36        let default = preserve_optional(default_value);
37        let mut symbols = Vec::new();
38        for variant in &data_enum.variants {
39            let field_attrs = VariantOptions::new(&variant.attrs, variant.span())?;
40            let name = match (field_attrs.rename, container_attrs.rename_all) {
41                (Some(rename), _) => rename,
42                (None, rename_all) if !matches!(rename_all, RenameRule::None) => {
43                    rename_all.apply_to_variant(&variant.ident.to_string())
44                }
45                _ => variant.ident.to_string(),
46            };
47            symbols.push(name);
48        }
49        Ok(quote! {
50            ::apache_avro::schema::Schema::Enum(::apache_avro::schema::EnumSchema {
51                name,
52                aliases: #enum_aliases,
53                doc: #doc,
54                symbols: vec![#(#symbols.to_owned()),*],
55                default: #default,
56                attributes: ::std::collections::BTreeMap::new(),
57            })
58        })
59    } else {
60        Err(vec![syn::Error::new(
61            ident_span,
62            "AvroSchema: derive does not work for enums with non unit structs",
63        )])
64    }
65}