use anyhow::{bail, Error}; use itertools::Itertools; use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{
punctuated::Punctuated, Data, DataEnum, DataStruct, DeriveInput, Expr, Fields, FieldsNamed,
FieldsUnnamed, Ident, Index, Variant,
};
let variant_data = match input.data {
Data::Struct(variant_data) => variant_data,
Data::Enum(..) => bail!("Message can not be derived for an enum"),
Data::Union(..) => bail!("Message can not be derived for a union"),
};
let generics = &input.generics; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
letmut next_tag: u32 = 1; letmut fields = fields
.into_iter()
.enumerate()
.flat_map(|(i, field)| { let field_ident = field.ident.map(|x| quote!(#x)).unwrap_or_else(|| { let index = Index {
index: i as u32,
span: Span::call_site(),
};
quote!(#index)
}); match Field::new(field.attrs, Some(next_tag)) {
Ok(Some(field)) => {
next_tag = field.tags().iter().max().map(|t| t + 1).unwrap_or(next_tag);
Some(Ok((field_ident, field)))
}
Ok(None) => None,
Err(err) => Some(Err(
err.context(format!("invalid message field {}.{}", ident, field_ident))
)),
}
})
.collect::<Result<Vec<_>, _>>()?;
// We want Debug to be in declaration order let unsorted_fields = fields.clone();
// Sort the fields by tag number so that fields will be encoded in tag order. // TODO: This encodes oneof fields in the position of their lowest tag, // regardless of the currently occupied variant, is that consequential? // See: https://developers.google.com/protocol-buffers/docs/encoding#order
fields.sort_by_key(|(_, field)| field.tags().into_iter().min().unwrap()); let fields = fields;
iflet Some(duplicate_tag) = fields
.iter()
.flat_map(|(_, field)| field.tags())
.duplicates()
.next()
{
bail!( "message {} has multiple fields with tag {}",
ident,
duplicate_tag
)
};
let encoded_len = fields
.iter()
.map(|(field_ident, field)| field.encoded_len(quote!(self.#field_ident)));
let encode = fields
.iter()
.map(|(field_ident, field)| field.encode(quote!(self.#field_ident)));
let merge = fields.iter().map(|(field_ident, field)| { let merge = field.merge(quote!(value)); let tags = field.tags().into_iter().map(|tag| quote!(#tag)); let tags = Itertools::intersperse(tags, quote!(|));
fn try_enumeration(input: TokenStream) -> Result<TokenStream, Error> { let input: DeriveInput = syn::parse2(input)?; let ident = input.ident;
let generics = &input.generics; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let punctuated_variants = match input.data {
Data::Enum(DataEnum { variants, .. }) => variants,
Data::Struct(_) => bail!("Enumeration can not be derived for a struct"),
Data::Union(..) => bail!("Enumeration can not be derived for a union"),
};
// Map the variants into 'fields'. letmut variants: Vec<(Ident, Expr)> = Vec::new(); for Variant {
ident,
fields,
discriminant,
..
} in punctuated_variants
{ match fields {
Fields::Unit => (),
Fields::Named(_) | Fields::Unnamed(_) => {
bail!("Enumeration variants may not have fields")
}
}
match discriminant {
Some((_, expr)) => variants.push((ident, expr)),
None => bail!("Enumeration variants must have a discriminant"),
}
}
if variants.is_empty() {
panic!("Enumeration must have at least one variant");
}
let default = variants[0].0.clone();
let is_valid = variants.iter().map(|(_, value)| quote!(#value => true)); let from = variants
.iter()
.map(|(variant, value)| quote!(#value => ::core::option::Option::Some(#ident::#variant)));
let try_from = variants
.iter()
.map(|(variant, value)| quote!(#value => ::core::result::Result::Ok(#ident::#variant)));
let is_valid_doc = format!("Returns `true` if `value` is a variant of `{}`.", ident); let from_i32_doc = format!( "Converts an `i32` to a `{}`, or `None` if `value` is not a valid variant.",
ident
);
let expanded = quote! { impl#impl_generics#ident#ty_generics#where_clause { #[doc=#is_valid_doc] pubfn is_valid(value: i32) -> bool { match value { #(#is_valid,)*
_ => false,
}
}
#[deprecated = "Use the TryFrom<i32> implementation instead"] #[doc=#from_i32_doc] pubfn from_i32(value: i32) -> ::core::option::Option<#ident> { match value { #(#from,)*
_ => ::core::option::Option::None,
}
}
}
let variants = match input.data {
Data::Enum(DataEnum { variants, .. }) => variants,
Data::Struct(..) => bail!("Oneof can not be derived for a struct"),
Data::Union(..) => bail!("Oneof can not be derived for a union"),
};
let generics = &input.generics; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
// Map the variants into 'fields'. letmut fields: Vec<(Ident, Field)> = Vec::new(); for Variant {
attrs,
ident: variant_ident,
fields: variant_fields,
..
} in variants
{ let variant_fields = match variant_fields {
Fields::Unit => Punctuated::new(),
Fields::Named(FieldsNamed { named: fields, .. })
| Fields::Unnamed(FieldsUnnamed {
unnamed: fields, ..
}) => fields,
}; if variant_fields.len() != 1 {
bail!("Oneof enum variants must have a single field");
} match Field::new_oneof(attrs)? {
Some(field) => fields.push((variant_ident, field)),
None => bail!("invalid oneof variant: oneof variants may not be ignored"),
}
}
// Oneof variants cannot be oneofs themselves, so it's impossible to have a field with multiple // tags.
assert!(fields.iter().all(|(_, field)| field.tags().len() == 1));
let encode = fields.iter().map(|(variant_ident, field)| { let encode = field.encode(quote!(*value));
quote!(#ident::#variant_ident(ref value) => { #encode })
});
let merge = fields.iter().map(|(variant_ident, field)| { let tag = field.tags()[0]; let merge = field.merge(quote!(value));
quote! { #tag => { match field {
::core::option::Option::Some(#ident::#variant_ident(refmut value)) => { #merge
},
_ => { letmut owned_value = ::core::default::Default::default(); let value = &mut owned_value; #merge.map(|_| *field = ::core::option::Option::Some(#ident::#variant_ident(owned_value)))
},
}
}
}
});
let encoded_len = fields.iter().map(|(variant_ident, field)| { let encoded_len = field.encoded_len(quote!(*value));
quote!(#ident::#variant_ident(ref value) => #encoded_len)
});
let expanded = quote! { impl#impl_generics#ident#ty_generics#where_clause { /// Encodes the message to a buffer. pubfn encode(&self, buf: &mutimpl ::prost::bytes::BufMut) { match *self { #(#encode,)*
}
}
/// Decodes an instance of the message from a buffer, and merges it into self. pubfn merge(
field: &mut ::core::option::Option<#ident#ty_generics>,
tag: u32,
wire_type: ::prost::encoding::wire_type::WireType,
buf: &mutimpl ::prost::bytes::Buf,
ctx: ::prost::encoding::DecodeContext,
) -> ::core::result::Result<(), ::prost::DecodeError>
{ match tag { #(#merge,)*
_ => unreachable!(concat!("invalid ", stringify!(#ident), " tag: {}"), tag),
}
}
/// Returns the encoded length of the message without a length delimiter. #[inline] pubfn encoded_len(&self) -> usize { match *self { #(#encoded_len,)*
}
}
}
}; let expanded = if skip_debug {
expanded
} else { let debug = fields.iter().map(|(variant_ident, field)| { let wrapper = field.debug(quote!(*value));
quote!(#ident::#variant_ident(ref value) => { let wrapper = #wrapper;
f.debug_tuple(stringify!(#variant_ident))
.field(&wrapper)
.finish()
})
});
quote! { #expanded
#[cfg(test)] mod test { usecrate::{try_message, try_oneof}; use quote::quote;
#[test] fn test_rejects_colliding_message_fields() { let output = try_message(quote!( struct Invalid { #[prost(bool, tag = "1")]
a: bool, #[prost(oneof = "super::Whatever", tags = "4, 5, 1")]
b: Option<super::Whatever>,
}
));
assert_eq!(
output
.expect_err("did not reject colliding message fields")
.to_string(), "message Invalid has multiple fields with tag 1"
);
}
#[test] fn test_rejects_colliding_oneof_variants() { let output = try_oneof(quote!( pubenum Invalid { #[prost(bool, tag = "1")]
A(bool), #[prost(bool, tag = "3")]
B(bool), #[prost(bool, tag = "1")]
C(bool),
}
));
assert_eq!(
output
.expect_err("did not reject colliding oneof variants")
.to_string(), "invalid oneof Invalid: multiple variants have tag 1"
);
}
#[test] fn test_rejects_multiple_tags_oneof_variant() { let output = try_oneof(quote!( enum What { #[prost(bool, tag = "1", tag = "2")]
A(bool),
}
));
assert_eq!(
output
.expect_err("did not reject multiple tags on oneof variant")
.to_string(), "duplicate tag attributes: 1 and 2"
);
let output = try_oneof(quote!( enum What { #[prost(bool, tag = "3")] #[prost(tag = "4")]
A(bool),
}
));
assert!(output.is_err());
assert_eq!(
output
.expect_err("did not reject multiple tags on oneof variant")
.to_string(), "duplicate tag attributes: 3 and 4"
);
let output = try_oneof(quote!( enum What { #[prost(bool, tags = "5,6")]
A(bool),
}
));
assert!(output.is_err());
assert_eq!(
output
.expect_err("did not reject multiple tags on oneof variant")
.to_string(), "unknown attribute(s): #[prost(tags = \"5,6\")]"
);
}
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.13 Sekunden
(vorverarbeitet am 2026-08-27)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.