|
| 1 | +use proc_macro::TokenStream; |
| 2 | +use quote::quote; |
| 3 | +use syn::{ |
| 4 | + parse_macro_input, punctuated::Punctuated, token::Comma, Attribute, Data, DataEnum, |
| 5 | + DeriveInput, Expr, ExprLit, ExprRange, Ident, Lit, RangeLimits, Result, Variant, |
| 6 | +}; |
| 7 | + |
| 8 | +/// A custom derive that supports: |
| 9 | +/// |
| 10 | +/// - `#[bytes(…)]` for single byte literals |
| 11 | +/// - `#[bytes_range(…)]` for inclusive byte ranges (b'a'..=b'z') |
| 12 | +/// - `#[fallback]` for a variant that covers everything else |
| 13 | +/// |
| 14 | +/// Example usage: |
| 15 | +/// |
| 16 | +/// ```rust |
| 17 | +/// use classification_macros::ClassifyBytes; |
| 18 | +/// |
| 19 | +/// #[derive(Clone, Copy, ClassifyBytes)] |
| 20 | +/// enum Class { |
| 21 | +/// #[bytes(b'a', b'b', b'c')] |
| 22 | +/// Letters, |
| 23 | +/// |
| 24 | +/// #[bytes_range(b'0'..=b'9')] |
| 25 | +/// Digits, |
| 26 | +/// |
| 27 | +/// #[fallback] |
| 28 | +/// Other, |
| 29 | +/// } |
| 30 | +/// ``` |
| 31 | +/// Then call `b'a'.into()` to get `Example::SomeLetters`. |
| 32 | +#[proc_macro_derive(ClassifyBytes, attributes(bytes, bytes_range, fallback))] |
| 33 | +pub fn classify_bytes_derive(input: TokenStream) -> TokenStream { |
| 34 | + let ast = parse_macro_input!(input as DeriveInput); |
| 35 | + |
| 36 | + // This derive only works on an enum |
| 37 | + let Data::Enum(DataEnum { variants, .. }) = &ast.data else { |
| 38 | + return syn::Error::new_spanned( |
| 39 | + &ast.ident, |
| 40 | + "ClassifyBytes can only be derived on an enum.", |
| 41 | + ) |
| 42 | + .to_compile_error() |
| 43 | + .into(); |
| 44 | + }; |
| 45 | + |
| 46 | + let enum_name = &ast.ident; |
| 47 | + |
| 48 | + let mut byte_map: [Option<Ident>; 256] = [const { None }; 256]; |
| 49 | + let mut fallback_variant: Option<Ident> = None; |
| 50 | + |
| 51 | + // Start parsing the variants |
| 52 | + for variant in variants { |
| 53 | + let variant_ident = &variant.ident; |
| 54 | + |
| 55 | + // If this variant has #[fallback], record it |
| 56 | + if has_fallback_attr(variant) { |
| 57 | + if fallback_variant.is_some() { |
| 58 | + let err = syn::Error::new_spanned( |
| 59 | + variant_ident, |
| 60 | + "Multiple variants have #[fallback]. Only one allowed.", |
| 61 | + ); |
| 62 | + return err.to_compile_error().into(); |
| 63 | + } |
| 64 | + fallback_variant = Some(variant_ident.clone()); |
| 65 | + } |
| 66 | + |
| 67 | + // Get #[bytes(…)] |
| 68 | + let single_bytes = get_bytes_attrs(&variant.attrs); |
| 69 | + |
| 70 | + // Get #[bytes_range(…)] |
| 71 | + let range_bytes = get_bytes_range_attrs(&variant.attrs); |
| 72 | + |
| 73 | + // Combine them |
| 74 | + let all_bytes = single_bytes |
| 75 | + .into_iter() |
| 76 | + .chain(range_bytes) |
| 77 | + .collect::<Vec<_>>(); |
| 78 | + |
| 79 | + // Mark them in the table |
| 80 | + for b in all_bytes { |
| 81 | + byte_map[b as usize] = Some(variant_ident.clone()); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + // If no fallback variant is found, default to "Other" |
| 86 | + let fallback_ident = fallback_variant.expect("A variant marked with #[fallback] is missing"); |
| 87 | + |
| 88 | + // For each of the 256 byte values, fill the table |
| 89 | + let fill = byte_map |
| 90 | + .clone() |
| 91 | + .into_iter() |
| 92 | + .map(|variant_opt| match variant_opt { |
| 93 | + Some(ident) => quote!(#enum_name::#ident), |
| 94 | + None => quote!(#enum_name::#fallback_ident), |
| 95 | + }); |
| 96 | + |
| 97 | + // Generate the final expanded code |
| 98 | + let expanded = quote! { |
| 99 | + impl #enum_name { |
| 100 | + pub const TABLE: [#enum_name; 256] = [ |
| 101 | + #(#fill),* |
| 102 | + ]; |
| 103 | + } |
| 104 | + |
| 105 | + impl From<u8> for #enum_name { |
| 106 | + fn from(byte: u8) -> Self { |
| 107 | + #enum_name::TABLE[byte as usize] |
| 108 | + } |
| 109 | + } |
| 110 | + }; |
| 111 | + |
| 112 | + TokenStream::from(expanded) |
| 113 | +} |
| 114 | + |
| 115 | +/// Checks if a variant has `#[fallback]` |
| 116 | +fn has_fallback_attr(variant: &Variant) -> bool { |
| 117 | + variant |
| 118 | + .attrs |
| 119 | + .iter() |
| 120 | + .any(|attr| attr.path().is_ident("fallback")) |
| 121 | +} |
| 122 | + |
| 123 | +/// Get all single byte literals from `#[bytes(…)]` |
| 124 | +fn get_bytes_attrs(attrs: &[Attribute]) -> Vec<u8> { |
| 125 | + let mut assigned = Vec::new(); |
| 126 | + for attr in attrs { |
| 127 | + if attr.path().is_ident("bytes") { |
| 128 | + match parse_bytes_attr(attr) { |
| 129 | + Ok(list) => assigned.extend(list), |
| 130 | + Err(e) => panic!("Error parsing #[bytes(...)]: {}", e), |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + assigned |
| 135 | +} |
| 136 | + |
| 137 | +/// Parse `#[bytes(...)]` as a comma-separated list of **byte literals**, e.g. `b'a'`, `b'\n'`. |
| 138 | +fn parse_bytes_attr(attr: &Attribute) -> Result<Vec<u8>> { |
| 139 | + // We'll parse it as a list of syn::Lit separated by commas: e.g. (b'a', b'b') |
| 140 | + let items: Punctuated<Lit, Comma> = attr.parse_args_with(Punctuated::parse_terminated)?; |
| 141 | + let mut out = Vec::new(); |
| 142 | + for lit in items { |
| 143 | + match lit { |
| 144 | + Lit::Byte(lb) => out.push(lb.value()), |
| 145 | + _ => { |
| 146 | + return Err(syn::Error::new_spanned( |
| 147 | + lit, |
| 148 | + "Expected a byte literal like b'a'", |
| 149 | + )) |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + Ok(out) |
| 154 | +} |
| 155 | + |
| 156 | +/// Get all byte ranges from `#[bytes_range(...)]` |
| 157 | +fn get_bytes_range_attrs(attrs: &[Attribute]) -> Vec<u8> { |
| 158 | + let mut assigned = Vec::new(); |
| 159 | + for attr in attrs { |
| 160 | + if attr.path().is_ident("bytes_range") { |
| 161 | + match parse_bytes_range_attr(attr) { |
| 162 | + Ok(list) => assigned.extend(list), |
| 163 | + Err(e) => panic!("Error parsing #[bytes_range(...)]: {}", e), |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | + assigned |
| 168 | +} |
| 169 | + |
| 170 | +/// Parse `#[bytes_range(...)]` as a comma-separated list of range expressions, e.g.: |
| 171 | +/// `b'a'..=b'z', b'0'..=b'9'` |
| 172 | +fn parse_bytes_range_attr(attr: &Attribute) -> Result<Vec<u8>> { |
| 173 | + // We'll parse each element as a syn::Expr, then see if it's an Expr::Range |
| 174 | + let exprs: Punctuated<Expr, Comma> = attr.parse_args_with(Punctuated::parse_terminated)?; |
| 175 | + let mut out = Vec::new(); |
| 176 | + |
| 177 | + for expr in exprs { |
| 178 | + if let Expr::Range(ExprRange { |
| 179 | + start: Some(start), |
| 180 | + end: Some(end), |
| 181 | + limits, |
| 182 | + .. |
| 183 | + }) = expr |
| 184 | + { |
| 185 | + let from = extract_byte_literal(&start)?; |
| 186 | + let to = extract_byte_literal(&end)?; |
| 187 | + |
| 188 | + match limits { |
| 189 | + RangeLimits::Closed(_) => { |
| 190 | + // b'a'..=b'z' |
| 191 | + if from <= to { |
| 192 | + out.extend(from..=to); |
| 193 | + } |
| 194 | + } |
| 195 | + RangeLimits::HalfOpen(_) => { |
| 196 | + // b'a'..b'z' => from..(to-1) |
| 197 | + if from < to { |
| 198 | + out.extend(from..to); |
| 199 | + } |
| 200 | + } |
| 201 | + } |
| 202 | + } else { |
| 203 | + return Err(syn::Error::new_spanned( |
| 204 | + expr, |
| 205 | + "Expected a byte range like b'a'..=b'z'", |
| 206 | + )); |
| 207 | + } |
| 208 | + } |
| 209 | + |
| 210 | + Ok(out) |
| 211 | +} |
| 212 | + |
| 213 | +/// Extract a u8 from an expression that can be: |
| 214 | +/// |
| 215 | +/// - `Expr::Lit(Lit::Byte(...))`, e.g. b'a' |
| 216 | +/// - `Expr::Lit(Lit::Int(...))`, e.g. 0x80 or 255 |
| 217 | +fn extract_byte_literal(expr: &Expr) -> Result<u8> { |
| 218 | + if let Expr::Lit(ExprLit { lit, .. }) = expr { |
| 219 | + match lit { |
| 220 | + // Existing case: b'a' |
| 221 | + Lit::Byte(lb) => Ok(lb.value()), |
| 222 | + |
| 223 | + // New case: 0x80, 255, etc. |
| 224 | + Lit::Int(li) => { |
| 225 | + let value = li.base10_parse::<u64>()?; |
| 226 | + if value <= 255 { |
| 227 | + Ok(value as u8) |
| 228 | + } else { |
| 229 | + Err(syn::Error::new_spanned( |
| 230 | + li, |
| 231 | + format!("Integer literal {} out of range for a byte (0..255)", value), |
| 232 | + )) |
| 233 | + } |
| 234 | + } |
| 235 | + |
| 236 | + _ => Err(syn::Error::new_spanned( |
| 237 | + lit, |
| 238 | + "Expected b'...' or an integer literal in range 0..=255", |
| 239 | + )), |
| 240 | + } |
| 241 | + } else { |
| 242 | + Err(syn::Error::new_spanned( |
| 243 | + expr, |
| 244 | + "Expected a literal expression like b'a' or 0x80", |
| 245 | + )) |
| 246 | + } |
| 247 | +} |
0 commit comments