1#![forbid(unsafe_code)]
7#![deny(missing_docs)]
8#![cfg_attr(coverage_nightly, allow(unused_features))]
9#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
10
11use proc_macro::TokenStream;
12use proc_macro2::TokenStream as TokenStream2;
13use quote::{format_ident, quote};
14use syn::parse::{Parse, ParseStream};
15use syn::{
16 Data, DeriveInput, Error, Expr, Fields, Ident, Index, ItemEnum, Result, Token, Type,
17 WherePredicate, parse_macro_input, parse_quote,
18};
19
20#[proc_macro_attribute]
21pub fn packet(arguments: TokenStream, input: TokenStream) -> TokenStream {
28 let arguments = parse_macro_input!(arguments as PacketArguments);
29 let input = parse_macro_input!(input as DeriveInput);
30 expand_packet(&input, arguments.id)
31 .map(|implementation| quote!(#input #implementation))
32 .unwrap_or_else(Error::into_compile_error)
33 .into()
34}
35
36#[proc_macro_attribute]
37pub fn packet_set(arguments: TokenStream, input: TokenStream) -> TokenStream {
45 let arguments = TokenStream2::from(arguments);
46 if !arguments.is_empty() {
47 return Error::new_spanned(arguments, "packet_set does not accept arguments")
48 .into_compile_error()
49 .into();
50 }
51
52 let input = parse_macro_input!(input as ItemEnum);
53 expand_packet_set(&input)
54 .map(|implementation| quote!(#input #implementation))
55 .unwrap_or_else(Error::into_compile_error)
56 .into()
57}
58
59fn expand_packet(input: &DeriveInput, packet_id: Expr) -> Result<TokenStream2> {
60 let protocol = protocol_crate_path();
61 let name = &input.ident;
62 let fields = match &input.data {
63 Data::Struct(data) => &data.fields,
64 Data::Enum(data) => {
65 return Err(Error::new_spanned(
66 data.enum_token,
67 "Packet can only be derived for structs; use #[packet_set] for dispatch enums",
68 ));
69 }
70 Data::Union(data) => {
71 return Err(Error::new_spanned(
72 data.union_token,
73 "Packet cannot be derived for unions",
74 ));
75 }
76 };
77
78 let field_types: Vec<&Type> = fields.iter().map(|field| &field.ty).collect();
79 let mut generics = input.generics.clone();
80 let where_clause = generics.make_where_clause();
81 for field_type in field_types {
82 let predicate: WherePredicate = parse_quote!(
83 #field_type: #protocol::BinaryEncode + #protocol::BinaryDecode
84 );
85 where_clause.predicates.push(predicate);
86 }
87 let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
88
89 let (encode_fields, decode_value) = codec_body(fields, &protocol);
90
91 Ok(quote! {
92 impl #impl_generics #protocol::BinaryEncode for #name #type_generics #where_clause {
93 fn encode(
94 &self,
95 writer: &mut #protocol::BinaryWriter,
96 ) -> #protocol::Result<()> {
97 #encode_fields
98 Ok(())
99 }
100 }
101
102 impl #impl_generics #protocol::BinaryDecode for #name #type_generics #where_clause {
103 fn decode(
104 reader: &mut #protocol::BinaryReader<'_>,
105 ) -> #protocol::Result<Self> {
106 Ok(#decode_value)
107 }
108 }
109
110 impl #impl_generics #protocol::Packet for #name #type_generics #where_clause {
111 const ID: #protocol::PacketId = #protocol::PacketId::new(#packet_id);
112 }
113 })
114}
115
116fn expand_packet_set(input: &ItemEnum) -> Result<TokenStream2> {
117 if !input.generics.params.is_empty() || input.generics.where_clause.is_some() {
118 return Err(Error::new_spanned(
119 &input.generics,
120 "generic packet sets are not supported",
121 ));
122 }
123 if input.variants.is_empty() {
124 return Err(Error::new_spanned(
125 &input.ident,
126 "packet sets must contain at least one variant",
127 ));
128 }
129
130 let protocol = protocol_crate_path();
131 let name = &input.ident;
132 let mut variants = Vec::with_capacity(input.variants.len());
133 let mut packet_types = Vec::with_capacity(input.variants.len());
134
135 for variant in &input.variants {
136 if variant.discriminant.is_some() {
137 return Err(Error::new_spanned(
138 variant,
139 "packet-set variants cannot have discriminants",
140 ));
141 }
142 let Fields::Unnamed(fields) = &variant.fields else {
143 return Err(Error::new_spanned(
144 variant,
145 "each packet-set variant must contain exactly one unnamed packet field",
146 ));
147 };
148 if fields.unnamed.len() != 1 {
149 return Err(Error::new_spanned(
150 variant,
151 "each packet-set variant must contain exactly one packet type",
152 ));
153 }
154
155 variants.push(&variant.ident);
156 packet_types.push(&fields.unnamed[0].ty);
157 }
158
159 Ok(quote! {
160 const _: () = {
161 const PACKET_IDS: &[u16] = &[
162 #(<#packet_types as #protocol::Packet>::ID.get(),)*
163 ];
164 let mut left = 0;
165 while left < PACKET_IDS.len() {
166 let mut right = left + 1;
167 while right < PACKET_IDS.len() {
168 assert!(
169 PACKET_IDS[left] != PACKET_IDS[right],
170 "duplicate packet ID in #[packet_set]",
171 );
172 right += 1;
173 }
174 left += 1;
175 }
176 };
177
178 impl #protocol::PacketSet for #name {
179 fn decode_packet(
180 id: #protocol::PacketId,
181 reader: &mut #protocol::BinaryReader<'_>,
182 ) -> #protocol::Result<Self> {
183 #(
184 if id == <#packet_types as #protocol::Packet>::ID {
185 return Ok(Self::#variants(
186 <#packet_types as #protocol::BinaryDecode>::decode(reader)?,
187 ));
188 }
189 )*
190
191 Err(#protocol::ProtocolError::UnknownPacketId(id))
192 }
193 }
194
195 impl #protocol::PacketEncode for #name {
196 fn packet_id(&self) -> #protocol::PacketId {
197 match self {
198 #(Self::#variants(_) => <#packet_types as #protocol::Packet>::ID,)*
199 }
200 }
201
202 fn encode_payload(
203 &self,
204 writer: &mut #protocol::BinaryWriter,
205 ) -> #protocol::Result<()> {
206 match self {
207 #(
208 Self::#variants(packet) => {
209 <#packet_types as #protocol::BinaryEncode>::encode(packet, writer)
210 }
211 )*
212 }
213 }
214 }
215
216 #(
217 impl From<#packet_types> for #name {
218 fn from(packet: #packet_types) -> Self {
219 Self::#variants(packet)
220 }
221 }
222 )*
223 })
224}
225
226fn codec_body(fields: &Fields, protocol: &TokenStream2) -> (TokenStream2, TokenStream2) {
227 match fields {
228 Fields::Named(fields) => {
229 let names: Vec<&Ident> = fields
230 .named
231 .iter()
232 .map(|field| field.ident.as_ref().expect("named field"))
233 .collect();
234 let encode = quote! {
235 #(
236 #protocol::BinaryEncode::encode(&self.#names, writer)?;
237 )*
238 };
239 let decode = quote! {
240 Self {
241 #(
242 #names: #protocol::BinaryDecode::decode(reader)?,
243 )*
244 }
245 };
246 (encode, decode)
247 }
248 Fields::Unnamed(fields) => {
249 let indexes: Vec<Index> = (0..fields.unnamed.len()).map(Index::from).collect();
250 let decode_fields = fields.unnamed.iter().map(|_| {
251 quote! { #protocol::BinaryDecode::decode(reader)? }
252 });
253 let encode = quote! {
254 #(
255 #protocol::BinaryEncode::encode(&self.#indexes, writer)?;
256 )*
257 };
258 let decode = quote! { Self(#(#decode_fields,)*) };
259 (encode, decode)
260 }
261 Fields::Unit => (TokenStream2::new(), quote! { Self }),
262 }
263}
264
265struct PacketArguments {
266 id: Expr,
267}
268
269impl Parse for PacketArguments {
270 fn parse(input: ParseStream<'_>) -> Result<Self> {
271 let id = if input.peek(Ident) && input.peek2(Token![=]) {
272 let key: Ident = input.parse().expect("peeked packet argument key");
273 if key != "id" {
274 return Err(Error::new(key.span(), "expected `id`"));
275 }
276 input
277 .parse::<Token![=]>()
278 .expect("peeked packet argument equals sign");
279 input.parse()?
280 } else {
281 input.parse()?
282 };
283
284 if !input.is_empty() {
285 return Err(input.error("unexpected tokens after packet ID"));
286 }
287 Ok(Self { id })
288 }
289}
290
291fn protocol_crate_path() -> TokenStream2 {
292 protocol_crate_path_for(proc_macro_crate::crate_name("packetwire").ok())
293}
294
295fn protocol_crate_path_for(found: Option<proc_macro_crate::FoundCrate>) -> TokenStream2 {
296 match found {
297 Some(proc_macro_crate::FoundCrate::Itself) => quote!(::packetwire),
298 Some(proc_macro_crate::FoundCrate::Name(name)) => {
299 let name = format_ident!("{}", name);
300 quote!(::#name)
301 }
302 None => quote!(::packetwire),
303 }
304}
305
306#[cfg(test)]
307#[cfg_attr(coverage_nightly, coverage(off))]
308mod tests {
309 use super::*;
310 use quote::ToTokens;
311 use syn::{parse_quote, parse_str};
312
313 #[test]
314 fn packet_arguments_accept_both_forms() {
315 let shorthand = parse_str::<PacketArguments>("0x20").unwrap();
316 assert_eq!(shorthand.id.to_token_stream().to_string(), "0x20");
317
318 let identifier = parse_str::<PacketArguments>("PACKET_ID").unwrap();
319 assert_eq!(identifier.id.to_token_stream().to_string(), "PACKET_ID");
320
321 let named = parse_str::<PacketArguments>("id = 32").unwrap();
322 assert_eq!(named.id.to_token_stream().to_string(), "32");
323 }
324
325 #[test]
326 fn packet_arguments_reject_unknown_keys_and_trailing_tokens() {
327 assert_eq!(
328 parse_str::<PacketArguments>("tag = 1")
329 .err()
330 .unwrap()
331 .to_string(),
332 "expected `id`"
333 );
334 assert_eq!(
335 parse_str::<PacketArguments>("1, 2")
336 .err()
337 .unwrap()
338 .to_string(),
339 "unexpected tokens after packet ID"
340 );
341 assert_eq!(
342 parse_str::<PacketArguments>("id =")
343 .err()
344 .unwrap()
345 .to_string(),
346 "unexpected end of input, expected an expression"
347 );
348 }
349
350 #[test]
351 fn packet_expansion_supports_all_struct_shapes_and_generics() {
352 for input in [
353 parse_quote!(
354 struct Named {
355 first: u8,
356 second: String,
357 }
358 ),
359 parse_quote!(
360 struct Tuple(u8, String);
361 ),
362 parse_quote!(
363 struct Unit;
364 ),
365 parse_quote!(
366 struct Generic<T: Clone>(T)
367 where
368 T: Send;
369 ),
370 ] {
371 let expansion = expand_packet(&input, parse_quote!(7)).unwrap();
372 assert!(!expansion.is_empty());
373 }
374 }
375
376 #[test]
377 fn packet_expansion_rejects_enums_and_unions() {
378 let enumeration: DeriveInput = parse_quote!(
379 enum Bad {
380 Variant,
381 }
382 );
383 assert_eq!(
384 expand_packet(&enumeration, parse_quote!(1))
385 .unwrap_err()
386 .to_string(),
387 "Packet can only be derived for structs; use #[packet_set] for dispatch enums"
388 );
389
390 let union: DeriveInput = parse_quote!(union Bad { value: u32 });
391 assert_eq!(
392 expand_packet(&union, parse_quote!(1))
393 .unwrap_err()
394 .to_string(),
395 "Packet cannot be derived for unions"
396 );
397 }
398
399 #[test]
400 fn packet_set_expansion_supports_valid_enums_and_rejects_empty_ones() {
401 let valid: ItemEnum = parse_quote! {
402 enum Messages {
403 First(FirstPacket),
404 Second(SecondPacket),
405 }
406 };
407 assert!(!expand_packet_set(&valid).unwrap().is_empty());
408
409 let empty: ItemEnum = parse_quote!(
410 enum Empty {}
411 );
412 assert_eq!(
413 expand_packet_set(&empty).unwrap_err().to_string(),
414 "packet sets must contain at least one variant"
415 );
416 }
417
418 #[test]
419 fn packet_set_expansion_rejects_generics_and_where_clauses() {
420 let generic: ItemEnum = parse_quote!(
421 enum Generic<T> {
422 Value(T),
423 }
424 );
425 assert_eq!(
426 expand_packet_set(&generic).unwrap_err().to_string(),
427 "generic packet sets are not supported"
428 );
429
430 let where_clause: ItemEnum = parse_quote!(
431 enum Constrained
432 where
433 u8: Copy,
434 {
435 Value(u8),
436 }
437 );
438 assert_eq!(
439 expand_packet_set(&where_clause).unwrap_err().to_string(),
440 "generic packet sets are not supported"
441 );
442 }
443
444 #[test]
445 fn packet_set_expansion_rejects_discriminants_and_invalid_fields() {
446 let cases: [(ItemEnum, &str); 5] = [
447 (
448 parse_quote!(
449 enum Set {
450 Value(Packet) = 1,
451 }
452 ),
453 "packet-set variants cannot have discriminants",
454 ),
455 (
456 parse_quote!(
457 enum Set {
458 Value { packet: Packet },
459 }
460 ),
461 "each packet-set variant must contain exactly one unnamed packet field",
462 ),
463 (
464 parse_quote!(
465 enum Set {
466 Value,
467 }
468 ),
469 "each packet-set variant must contain exactly one unnamed packet field",
470 ),
471 (
472 parse_quote!(
473 enum Set {
474 Value(),
475 }
476 ),
477 "each packet-set variant must contain exactly one packet type",
478 ),
479 (
480 parse_quote!(
481 enum Set {
482 Value(First, Second),
483 }
484 ),
485 "each packet-set variant must contain exactly one packet type",
486 ),
487 ];
488
489 for (input, expected) in cases {
490 assert_eq!(expand_packet_set(&input).unwrap_err().to_string(), expected);
491 }
492 }
493
494 #[test]
495 fn crate_path_resolution_covers_self_renamed_and_fallback() {
496 assert_eq!(
497 protocol_crate_path_for(Some(proc_macro_crate::FoundCrate::Itself)).to_string(),
498 ":: packetwire"
499 );
500 assert_eq!(
501 protocol_crate_path_for(Some(proc_macro_crate::FoundCrate::Name("wire".to_owned())))
502 .to_string(),
503 ":: wire"
504 );
505 assert_eq!(protocol_crate_path_for(None).to_string(), ":: packetwire");
506 }
507}