#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![cfg_attr(coverage_nightly, allow(unused_features))]
#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::{
Data, DeriveInput, Error, Expr, Fields, Ident, Index, ItemEnum, Result, Token, Type,
WherePredicate, parse_macro_input, parse_quote,
};
#[proc_macro_attribute]
pub fn packet(arguments: TokenStream, input: TokenStream) -> TokenStream {
let arguments = parse_macro_input!(arguments as PacketArguments);
let input = parse_macro_input!(input as DeriveInput);
expand_packet(&input, arguments.id)
.map(|implementation| quote!(#input #implementation))
.unwrap_or_else(Error::into_compile_error)
.into()
}
#[proc_macro_attribute]
pub fn packet_set(arguments: TokenStream, input: TokenStream) -> TokenStream {
let arguments = TokenStream2::from(arguments);
if !arguments.is_empty() {
return Error::new_spanned(arguments, "packet_set does not accept arguments")
.into_compile_error()
.into();
}
let input = parse_macro_input!(input as ItemEnum);
expand_packet_set(&input)
.map(|implementation| quote!(#input #implementation))
.unwrap_or_else(Error::into_compile_error)
.into()
}
fn expand_packet(input: &DeriveInput, packet_id: Expr) -> Result<TokenStream2> {
let protocol = protocol_crate_path();
let name = &input.ident;
let fields = match &input.data {
Data::Struct(data) => &data.fields,
Data::Enum(data) => {
return Err(Error::new_spanned(
data.enum_token,
"Packet can only be derived for structs; use #[packet_set] for dispatch enums",
));
}
Data::Union(data) => {
return Err(Error::new_spanned(
data.union_token,
"Packet cannot be derived for unions",
));
}
};
let field_types: Vec<&Type> = fields.iter().map(|field| &field.ty).collect();
let mut generics = input.generics.clone();
let where_clause = generics.make_where_clause();
for field_type in field_types {
let predicate: WherePredicate = parse_quote!(
#field_type: #protocol::BinaryEncode + #protocol::BinaryDecode
);
where_clause.predicates.push(predicate);
}
let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
let (encode_fields, decode_value) = codec_body(fields, &protocol);
Ok(quote! {
impl #impl_generics #protocol::BinaryEncode for #name #type_generics #where_clause {
fn encode(
&self,
writer: &mut #protocol::BinaryWriter,
) -> #protocol::Result<()> {
#encode_fields
Ok(())
}
}
impl #impl_generics #protocol::BinaryDecode for #name #type_generics #where_clause {
fn decode(
reader: &mut #protocol::BinaryReader<'_>,
) -> #protocol::Result<Self> {
Ok(#decode_value)
}
}
impl #impl_generics #protocol::Packet for #name #type_generics #where_clause {
const ID: #protocol::PacketId = #protocol::PacketId::new(#packet_id);
}
})
}
fn expand_packet_set(input: &ItemEnum) -> Result<TokenStream2> {
if !input.generics.params.is_empty() || input.generics.where_clause.is_some() {
return Err(Error::new_spanned(
&input.generics,
"generic packet sets are not supported",
));
}
if input.variants.is_empty() {
return Err(Error::new_spanned(
&input.ident,
"packet sets must contain at least one variant",
));
}
let protocol = protocol_crate_path();
let name = &input.ident;
let mut variants = Vec::with_capacity(input.variants.len());
let mut packet_types = Vec::with_capacity(input.variants.len());
for variant in &input.variants {
if variant.discriminant.is_some() {
return Err(Error::new_spanned(
variant,
"packet-set variants cannot have discriminants",
));
}
let Fields::Unnamed(fields) = &variant.fields else {
return Err(Error::new_spanned(
variant,
"each packet-set variant must contain exactly one unnamed packet field",
));
};
if fields.unnamed.len() != 1 {
return Err(Error::new_spanned(
variant,
"each packet-set variant must contain exactly one packet type",
));
}
variants.push(&variant.ident);
packet_types.push(&fields.unnamed[0].ty);
}
Ok(quote! {
const _: () = {
const PACKET_IDS: &[u16] = &[
#(<#packet_types as #protocol::Packet>::ID.get(),)*
];
let mut left = 0;
while left < PACKET_IDS.len() {
let mut right = left + 1;
while right < PACKET_IDS.len() {
assert!(
PACKET_IDS[left] != PACKET_IDS[right],
"duplicate packet ID in #[packet_set]",
);
right += 1;
}
left += 1;
}
};
impl #protocol::PacketSet for #name {
fn decode_packet(
id: #protocol::PacketId,
reader: &mut #protocol::BinaryReader<'_>,
) -> #protocol::Result<Self> {
#(
if id == <#packet_types as #protocol::Packet>::ID {
return Ok(Self::#variants(
<#packet_types as #protocol::BinaryDecode>::decode(reader)?,
));
}
)*
Err(#protocol::ProtocolError::UnknownPacketId(id))
}
}
impl #protocol::PacketEncode for #name {
fn packet_id(&self) -> #protocol::PacketId {
match self {
#(Self::#variants(_) => <#packet_types as #protocol::Packet>::ID,)*
}
}
fn encode_payload(
&self,
writer: &mut #protocol::BinaryWriter,
) -> #protocol::Result<()> {
match self {
#(
Self::#variants(packet) => {
<#packet_types as #protocol::BinaryEncode>::encode(packet, writer)
}
)*
}
}
}
#(
impl From<#packet_types> for #name {
fn from(packet: #packet_types) -> Self {
Self::#variants(packet)
}
}
)*
})
}
fn codec_body(fields: &Fields, protocol: &TokenStream2) -> (TokenStream2, TokenStream2) {
match fields {
Fields::Named(fields) => {
let names: Vec<&Ident> = fields
.named
.iter()
.map(|field| field.ident.as_ref().expect("named field"))
.collect();
let encode = quote! {
#(
#protocol::BinaryEncode::encode(&self.#names, writer)?;
)*
};
let decode = quote! {
Self {
#(
#names: #protocol::BinaryDecode::decode(reader)?,
)*
}
};
(encode, decode)
}
Fields::Unnamed(fields) => {
let indexes: Vec<Index> = (0..fields.unnamed.len()).map(Index::from).collect();
let decode_fields = fields.unnamed.iter().map(|_| {
quote! { #protocol::BinaryDecode::decode(reader)? }
});
let encode = quote! {
#(
#protocol::BinaryEncode::encode(&self.#indexes, writer)?;
)*
};
let decode = quote! { Self(#(#decode_fields,)*) };
(encode, decode)
}
Fields::Unit => (TokenStream2::new(), quote! { Self }),
}
}
struct PacketArguments {
id: Expr,
}
impl Parse for PacketArguments {
fn parse(input: ParseStream<'_>) -> Result<Self> {
let id = if input.peek(Ident) && input.peek2(Token![=]) {
let key: Ident = input.parse().expect("peeked packet argument key");
if key != "id" {
return Err(Error::new(key.span(), "expected `id`"));
}
input
.parse::<Token![=]>()
.expect("peeked packet argument equals sign");
input.parse()?
} else {
input.parse()?
};
if !input.is_empty() {
return Err(input.error("unexpected tokens after packet ID"));
}
Ok(Self { id })
}
}
fn protocol_crate_path() -> TokenStream2 {
protocol_crate_path_for(proc_macro_crate::crate_name("packetwire").ok())
}
fn protocol_crate_path_for(found: Option<proc_macro_crate::FoundCrate>) -> TokenStream2 {
match found {
Some(proc_macro_crate::FoundCrate::Itself) => quote!(::packetwire),
Some(proc_macro_crate::FoundCrate::Name(name)) => {
let name = format_ident!("{}", name);
quote!(::#name)
}
None => quote!(::packetwire),
}
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use super::*;
use quote::ToTokens;
use syn::{parse_quote, parse_str};
#[test]
fn packet_arguments_accept_both_forms() {
let shorthand = parse_str::<PacketArguments>("0x20").unwrap();
assert_eq!(shorthand.id.to_token_stream().to_string(), "0x20");
let identifier = parse_str::<PacketArguments>("PACKET_ID").unwrap();
assert_eq!(identifier.id.to_token_stream().to_string(), "PACKET_ID");
let named = parse_str::<PacketArguments>("id = 32").unwrap();
assert_eq!(named.id.to_token_stream().to_string(), "32");
}
#[test]
fn packet_arguments_reject_unknown_keys_and_trailing_tokens() {
assert_eq!(
parse_str::<PacketArguments>("tag = 1")
.err()
.unwrap()
.to_string(),
"expected `id`"
);
assert_eq!(
parse_str::<PacketArguments>("1, 2")
.err()
.unwrap()
.to_string(),
"unexpected tokens after packet ID"
);
assert_eq!(
parse_str::<PacketArguments>("id =")
.err()
.unwrap()
.to_string(),
"unexpected end of input, expected an expression"
);
}
#[test]
fn packet_expansion_supports_all_struct_shapes_and_generics() {
for input in [
parse_quote!(
struct Named {
first: u8,
second: String,
}
),
parse_quote!(
struct Tuple(u8, String);
),
parse_quote!(
struct Unit;
),
parse_quote!(
struct Generic<T: Clone>(T)
where
T: Send;
),
] {
let expansion = expand_packet(&input, parse_quote!(7)).unwrap();
assert!(!expansion.is_empty());
}
}
#[test]
fn packet_expansion_rejects_enums_and_unions() {
let enumeration: DeriveInput = parse_quote!(
enum Bad {
Variant,
}
);
assert_eq!(
expand_packet(&enumeration, parse_quote!(1))
.unwrap_err()
.to_string(),
"Packet can only be derived for structs; use #[packet_set] for dispatch enums"
);
let union: DeriveInput = parse_quote!(union Bad { value: u32 });
assert_eq!(
expand_packet(&union, parse_quote!(1))
.unwrap_err()
.to_string(),
"Packet cannot be derived for unions"
);
}
#[test]
fn packet_set_expansion_supports_valid_enums_and_rejects_empty_ones() {
let valid: ItemEnum = parse_quote! {
enum Messages {
First(FirstPacket),
Second(SecondPacket),
}
};
assert!(!expand_packet_set(&valid).unwrap().is_empty());
let empty: ItemEnum = parse_quote!(
enum Empty {}
);
assert_eq!(
expand_packet_set(&empty).unwrap_err().to_string(),
"packet sets must contain at least one variant"
);
}
#[test]
fn packet_set_expansion_rejects_generics_and_where_clauses() {
let generic: ItemEnum = parse_quote!(
enum Generic<T> {
Value(T),
}
);
assert_eq!(
expand_packet_set(&generic).unwrap_err().to_string(),
"generic packet sets are not supported"
);
let where_clause: ItemEnum = parse_quote!(
enum Constrained
where
u8: Copy,
{
Value(u8),
}
);
assert_eq!(
expand_packet_set(&where_clause).unwrap_err().to_string(),
"generic packet sets are not supported"
);
}
#[test]
fn packet_set_expansion_rejects_discriminants_and_invalid_fields() {
let cases: [(ItemEnum, &str); 5] = [
(
parse_quote!(
enum Set {
Value(Packet) = 1,
}
),
"packet-set variants cannot have discriminants",
),
(
parse_quote!(
enum Set {
Value { packet: Packet },
}
),
"each packet-set variant must contain exactly one unnamed packet field",
),
(
parse_quote!(
enum Set {
Value,
}
),
"each packet-set variant must contain exactly one unnamed packet field",
),
(
parse_quote!(
enum Set {
Value(),
}
),
"each packet-set variant must contain exactly one packet type",
),
(
parse_quote!(
enum Set {
Value(First, Second),
}
),
"each packet-set variant must contain exactly one packet type",
),
];
for (input, expected) in cases {
assert_eq!(expand_packet_set(&input).unwrap_err().to_string(), expected);
}
}
#[test]
fn crate_path_resolution_covers_self_renamed_and_fallback() {
assert_eq!(
protocol_crate_path_for(Some(proc_macro_crate::FoundCrate::Itself)).to_string(),
":: packetwire"
);
assert_eq!(
protocol_crate_path_for(Some(proc_macro_crate::FoundCrate::Name("wire".to_owned())))
.to_string(),
":: wire"
);
assert_eq!(protocol_crate_path_for(None).to_string(), ":: packetwire");
}
}