Skip to content

Commit

Permalink
[chore] replace panic with .to_compiler_error in macros (#409)
Browse files Browse the repository at this point in the history
Replace `panic!` with `to_compiler_error` in macros.

There seem to be no tests for macros, maybe worth adding but probably
deserves a separate issue

resolves #348

---------

Signed-off-by: Niko <[email protected]>
Co-authored-by: Nick Lanham <[email protected]>
  • Loading branch information
r3stl355 and nicklan authored Oct 22, 2024
1 parent 6e8bd3e commit 8de8689
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions derive-macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use proc_macro2::{Ident, TokenStream};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Fields, Meta, PathArguments, Type};
use syn::{
parse_macro_input, Data, DataStruct, DeriveInput, Error, Fields, Meta, PathArguments, Type,
};

/// Derive a `delta_kernel::schemas::ToDataType` implementation for the annotated struct. The actual
/// field names in the schema (and therefore of the struct members) are all mandated by the Delta
Expand Down Expand Up @@ -63,7 +65,13 @@ fn gen_schema_fields(data: &Data) -> TokenStream {
fields: Fields::Named(fields),
..
}) => &fields.named,
_ => panic!("this derive macro only works on structs with named fields"),
_ => {
return Error::new(
Span::call_site(),
"this derive macro only works on structs with named fields",
)
.to_compile_error()
}
};

let schema_fields = fields.iter().map(|field| {
Expand All @@ -84,23 +92,24 @@ fn gen_schema_fields(data: &Data) -> TokenStream {
match &segment.arguments {
PathArguments::None => quote! { #segment_ident :: },
PathArguments::AngleBracketed(angle_args) => quote! { #segment_ident::#angle_args :: },
_ => panic!("Can only handle <> type path args"),
_ => Error::new(segment.arguments.span(), "Can only handle <> type path args").to_compile_error()
}
});
if have_schema_null {
if let Some(first_ident) = type_path.path.segments.first().map(|seg| &seg.ident) {
if first_ident != "HashMap" {
panic!("Can only use drop_null_container_values on HashMap fields, not {first_ident:?}");
return Error::new(
first_ident.span(),
format!("Can only use drop_null_container_values on HashMap fields, not {first_ident}")
).to_compile_error()
}
}
quote_spanned! { field.span() => #(#type_path_quoted),* get_nullable_container_struct_field(stringify!(#name))}
} else {
quote_spanned! { field.span() => #(#type_path_quoted),* get_struct_field(stringify!(#name))}
}
}
_ => {
panic!("Can't handle type: {:?}", field.ty);
}
_ => Error::new(field.span(), format!("Can't handle type: {:?}", field.ty)).to_compile_error()
}
});
quote! { #(#schema_fields),* }
Expand Down

0 comments on commit 8de8689

Please sign in to comment.