jklamer commented on code in PR #1631:
URL: https://github.com/apache/avro/pull/1631#discussion_r846568843


##########
lang/rust/avro_derive/src/lib.rs:
##########
@@ -0,0 +1,366 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use proc_macro2::{Span, TokenStream, TokenTree};
+use quote::quote;
+
+use syn::{parse_macro_input, Attribute, DeriveInput, Error, Lit, Path, Type, 
TypePath};
+
+#[proc_macro_derive(AvroSchema, attributes(namespace))]
+// Templated from Serde
+pub fn proc_macro_derive_avro_schema(input: proc_macro::TokenStream) -> 
proc_macro::TokenStream {
+    let mut input = parse_macro_input!(input as DeriveInput);
+    derive_avro_schema(&mut input)
+        .unwrap_or_else(to_compile_errors)
+        .into()
+}
+
+fn derive_avro_schema(input: &mut DeriveInput) -> Result<TokenStream, 
Vec<syn::Error>> {
+    let namespace = get_namespace_from_attributes(&input.attrs)?;
+    let full_schema_name = vec![namespace, Some(input.ident.to_string())]
+        .into_iter()
+        .flatten()
+        .collect::<Vec<String>>()
+        .join(".");
+    let schema_def = match &input.data {
+        syn::Data::Struct(s) => {
+            get_data_struct_schema_def(&full_schema_name, s, 
input.ident.span())?
+        }
+        syn::Data::Enum(e) => get_data_enum_schema_def(&full_schema_name, e, 
input.ident.span())?,
+        _ => {
+            return Err(vec![Error::new(
+                input.ident.span(),
+                "AvroSchema derive only works for structs and simple enums ",
+            )])
+        }
+    };
+
+    let ty = &input.ident;
+    let (impl_generics, ty_generics, where_clause) = 
input.generics.split_for_impl();
+    Ok(quote! {
+        impl #impl_generics apache_avro::schema::AvroSchemaWithResolved for 
#ty #ty_generics #where_clause {
+            fn get_schema_with_resolved(resolved_schemas: &mut 
HashMap<apache_avro::schema::Name, apache_avro::schema::Schema>) -> 
apache_avro::schema::Schema {
+                let name =  
apache_avro::schema::Name::new(#full_schema_name).expect(&format!("Unable to 
parse schema name {}", #full_schema_name)[..]);
+                if resolved_schemas.contains_key(&name) {
+                    resolved_schemas.get(&name).unwrap().clone()
+                }else {
+                    resolved_schemas.insert(name.clone(), Schema::Ref{name: 
name.clone()});
+                    #schema_def
+                }
+            }
+        }
+    })
+}
+
+fn get_namespace_from_attributes(attrs: &[Attribute]) -> 
Result<Option<String>, Vec<Error>> {
+    let namespace_attr_path_constant: Path = syn::parse2::<Path>(quote! 
{namespace}).unwrap();
+    const NAMESPACE_PARSING_ERROR_CONSTANST: &str =
+        "Namespace attribute must be in form #[namespace = 
\"com.testing.namespace\"]";
+    // parse out namespace if present. Requires strict syntax
+    for attr in attrs {
+        if namespace_attr_path_constant == attr.path {
+            let mut input_tokens = attr.tokens.clone().into_iter();
+            if let (
+                Some(TokenTree::Punct(punct)),
+                Some(TokenTree::Literal(namespace_literal)),
+                None,
+            ) = (
+                input_tokens.next(),
+                input_tokens.next(),
+                input_tokens.next(),
+            ) {
+                if punct.as_char() == '=' {
+                    if let Lit::Str(lit_str) = Lit::new(namespace_literal) {
+                        return Ok(Some(lit_str.value()));
+                    }
+                }
+            }
+            return Err(vec![Error::new_spanned(
+                &attr.tokens,
+                NAMESPACE_PARSING_ERROR_CONSTANST,
+            )]);
+        }
+    }
+    Ok(None)
+}
+
+fn get_data_struct_schema_def(
+    full_schema_name: &str,
+    s: &syn::DataStruct,
+    error_span: Span,
+) -> Result<TokenStream, Vec<Error>> {
+    let mut record_field_exprs = vec![];
+    match s.fields {
+        syn::Fields::Named(ref a) => {
+            for (position, field) in a.named.iter().enumerate() {
+                let name = field.ident.as_ref().unwrap().to_string(); // we 
know everything has a name
+                let schema_expr = type_to_schema_expr(&field.ty)?;
+                let position = position;
+                record_field_exprs.push(quote! {
+                    apache_avro::schema::RecordField {
+                            name: #name.to_string(),
+                            doc: Option::None,
+                            default: Option::None,

Review Comment:
   https://issues.apache.org/jira/browse/AVRO-3484
   https://issues.apache.org/jira/browse/AVRO-3485



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to