tabled_derive-0.6.0/.cargo_vcs_info.json0000644000000001530000000000100136270ustar { "git": { "sha1": "1a9fc15d327e09e8fe959460541c837714414456" }, "path_in_vcs": "tabled_derive" }tabled_derive-0.6.0/Cargo.toml0000644000000016430000000000100116320ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "tabled_derive" version = "0.6.0" authors = ["Maxim Zhiburt "] description = "Derive macros which is used by tabled crate" license = "MIT" repository = "https://github.com/zhiburt/tabled" [lib] proc-macro = true [dependencies.heck] version = "0.4" [dependencies.proc-macro-error] version = "1.0" [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.syn] version = "1" tabled_derive-0.6.0/Cargo.toml.orig000064400000000000000000000005471046102023000153150ustar 00000000000000[package] name = "tabled_derive" version = "0.6.0" authors = ["Maxim Zhiburt "] edition = "2018" description = "Derive macros which is used by tabled crate" repository = "https://github.com/zhiburt/tabled" license = "MIT" [lib] proc-macro = true [dependencies] syn = "1" quote = "1" proc-macro2 = "1" heck = "0.4" proc-macro-error = "1.0"tabled_derive-0.6.0/LICENSE-MIT000064400000000000000000000020561046102023000140570ustar 00000000000000MIT License Copyright (c) 2021 Maxim Zhiburt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tabled_derive-0.6.0/src/attributes.rs000064400000000000000000000107461046102023000157530ustar 00000000000000use syn::{Attribute, Lit, LitInt}; use crate::{casing_style::CasingStyle, error::Error, parse}; #[derive(Debug, Default)] pub struct Attributes { pub is_ignored: bool, pub inline: bool, pub inline_prefix: Option, pub rename: Option, pub rename_all: Option, pub display_with: Option, pub display_with_args: Option>, pub order: Option, } impl Attributes { pub fn parse(attrs: &[Attribute]) -> Result { let mut attributes = Self::default(); attributes.fill_attributes(attrs)?; Ok(attributes) } fn fill_attributes(&mut self, attrs: &[Attribute]) -> Result<(), Error> { for attrs in parse::parse_attributes(attrs) { let attrs = attrs?; for attr in attrs { self.insert_attribute(attr)?; } } Ok(()) } fn insert_attribute(&mut self, attr: parse::TabledAttr) -> Result<(), Error> { match attr.kind { parse::TabledAttrKind::Skip(b) => { if b.value { self.is_ignored = true; } } parse::TabledAttrKind::Inline(b, prefix) => { if b.value { self.inline = true; } if let Some(prefix) = prefix { self.inline_prefix = Some(prefix.value()); } } parse::TabledAttrKind::Rename(value) => self.rename = Some(value.value()), parse::TabledAttrKind::RenameAll(lit) => { self.rename_all = Some(CasingStyle::from_lit(&lit)?); } parse::TabledAttrKind::DisplayWith(path, comma, args) => { self.display_with = Some(path.value()); if comma.is_some() { let args = args .into_iter() .map(|lit| parse_func_arg(&lit)) .collect::, _>>()?; self.display_with_args = Some(args); } } parse::TabledAttrKind::Order(value) => self.order = Some(lit_int_to_usize(&value)?), } Ok(()) } pub fn is_ignored(&self) -> bool { self.is_ignored } } pub struct StructAttributes { pub rename_all: Option, pub inline: bool, pub inline_value: Option, } impl StructAttributes { pub fn parse(attrs: &[Attribute]) -> Result { let attrs = Attributes::parse(attrs)?; Ok(Self { rename_all: attrs.rename_all, inline: attrs.inline, inline_value: attrs.inline_prefix, }) } } fn lit_int_to_usize(value: &LitInt) -> Result { value.base10_parse::().map_err(|e| { Error::new( format!("Failed to parse {:?} as usize; {}", value.to_string(), e), value.span(), None, ) }) } #[derive(Debug)] pub enum FuncArg { SelfRef, Byte(u8), Char(char), Bool(bool), Uint(usize), Int(isize), Float(f64), String(String), Bytes(Vec), } fn parse_func_arg(expr: &syn::Expr) -> syn::Result { use syn::spanned::Spanned; match expr { syn::Expr::Lit(lit) => match &lit.lit { Lit::Str(val) => Ok(FuncArg::String(val.value())), Lit::ByteStr(val) => Ok(FuncArg::Bytes(val.value())), Lit::Byte(val) => Ok(FuncArg::Byte(val.value())), Lit::Char(val) => Ok(FuncArg::Char(val.value())), Lit::Bool(val) => Ok(FuncArg::Bool(val.value())), Lit::Float(val) => val.base10_parse::().map(FuncArg::Float), Lit::Int(val) => { if val.base10_digits().starts_with('-') { val.base10_parse::().map(FuncArg::Int) } else { val.base10_parse::().map(FuncArg::Uint) } } Lit::Verbatim(val) => Err(syn::Error::new(val.span(), "unsuported argument")), }, syn::Expr::Path(path) => { let indent = path.path.get_ident().map(|indent| indent.to_string()); if matches!(indent.as_deref(), Some("self" | "Self")) { Ok(FuncArg::SelfRef) } else { Err(syn::Error::new(path.span(), "unsuported argument")) } } expr => Err(syn::Error::new(expr.span(), "unsuported argument")), } } tabled_derive-0.6.0/src/casing_style.rs000064400000000000000000000047311046102023000162460ustar 00000000000000use crate::error::Error; /// Defines the casing for the attributes long representation. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum CasingStyle { /// Indicate word boundaries with uppercase letter, excluding the first word. Camel, /// Keep all letters lowercase and indicate word boundaries with hyphens. Kebab, /// Indicate word boundaries with uppercase letter, including the first word. Pascal, /// Keep all letters uppercase and indicate word boundaries with underscores. ScreamingSnake, /// Keep all letters lowercase and indicate word boundaries with underscores. Snake, /// Keep all letters lowercase and remove word boundaries. Lower, /// Keep all letters uppercase and remove word boundaries. Upper, /// Use the original attribute name defined in the code. Verbatim, } impl CasingStyle { pub fn from_lit(name: &syn::LitStr) -> Result { use self::CasingStyle::*; use heck::ToUpperCamelCase; let normalized = name.value().to_upper_camel_case().to_lowercase(); match normalized.as_ref() { "camel" | "camelcase" => Ok(Camel), "kebab" | "kebabcase" => Ok(Kebab), "pascal" | "pascalcase" => Ok(Pascal), "screamingsnake" | "screamingsnakecase" => Ok(ScreamingSnake), "snake" | "snakecase" => Ok(Snake), "lower" | "lowercase" => Ok(Lower), "upper" | "uppercase" => Ok(Upper), "verbatim" | "verbatimcase" => Ok(Verbatim), _ => Err(Error::new(format!("unsupported casing: `{:?}`", name.value()), name.span(), Some("supperted values are ['camelCase', 'kebab-case', 'PascalCase', 'SCREAMING_SNAKE_CASE', 'snake_case', 'lowercase', 'UPPERCASE', 'verbatim']".to_owned()))) } } pub fn cast(self, s: String) -> String { use CasingStyle::*; match self { Pascal => heck::ToUpperCamelCase::to_upper_camel_case(s.as_str()), Camel => heck::ToLowerCamelCase::to_lower_camel_case(s.as_str()), Kebab => heck::ToKebabCase::to_kebab_case(s.as_str()), Snake => heck::ToSnakeCase::to_snake_case(s.as_str()), ScreamingSnake => heck::ToShoutySnakeCase::to_shouty_snake_case(s.as_str()), Lower => heck::ToSnakeCase::to_snake_case(s.as_str()).replace('_', ""), Upper => heck::ToShoutySnakeCase::to_shouty_snake_case(s.as_str()).replace('_', ""), Verbatim => s, } } } tabled_derive-0.6.0/src/error.rs000064400000000000000000000027601046102023000147130ustar 00000000000000use proc_macro2::Span; #[derive(Debug, Clone)] pub enum Error { Syn(syn::Error), Custom { span: Span, error: String, help: Option, }, } impl Error { pub fn new(error: E, span: Span, help: Option) -> Self where E: Into, { let error = error.into(); Self::Custom { error, help, span } } pub fn message(error: E) -> Self where E: Into, { let error = error.into(); Self::Custom { error, help: None, span: Span::call_site(), } } } impl From for Error { fn from(err: syn::Error) -> Self { Error::Syn(err) } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::Syn(err) => err.fmt(f), Error::Custom { error, .. } => { write!(f, "a custom error: {error}") } } } } impl std::error::Error for Error {} pub fn abort(err: Error) -> ! { match err { Error::Syn(err) => { proc_macro_error::abort! {err.span(), "{}", err} } Error::Custom { span, error, help } => match help { Some(help) => { proc_macro_error::abort! {span, "{}", error; help="{}", help} } None => { proc_macro_error::abort! {span, "{}", error} } }, } } tabled_derive-0.6.0/src/lib.rs000064400000000000000000000457061046102023000143370ustar 00000000000000#![allow(clippy::uninlined_format_args)] #![doc( html_logo_url = "https://raw.githubusercontent.com/zhiburt/tabled/86ac146e532ce9f7626608d7fd05072123603a2e/assets/tabled-gear.svg" )] extern crate proc_macro; mod attributes; mod casing_style; mod error; mod parse; use proc_macro2::TokenStream; use proc_macro_error::proc_macro_error; use quote::{quote, ToTokens, TokenStreamExt}; use std::{collections::HashMap, str}; use syn::{ parse_macro_input, token, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, Ident, Index, Type, Variant, }; use attributes::{Attributes, FuncArg, StructAttributes}; use error::Error; #[proc_macro_derive(Tabled, attributes(tabled))] #[proc_macro_error] pub fn tabled(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); let ast = impl_tabled(&input); proc_macro::TokenStream::from(ast) } fn impl_tabled(ast: &DeriveInput) -> TokenStream { let attrs = StructAttributes::parse(&ast.attrs) .map_err(error::abort) .unwrap(); let length = get_tabled_length(ast, &attrs) .map_err(error::abort) .unwrap(); let info = collect_info(ast, &attrs).map_err(error::abort).unwrap(); let fields = info.values; let headers = info.headers; let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let expanded = quote! { impl #impl_generics ::tabled::Tabled for #name #ty_generics #where_clause { const LENGTH: usize = #length; fn fields(&self) -> Vec<::std::borrow::Cow<'_, str>> { #fields } fn headers() -> Vec<::std::borrow::Cow<'static, str>> { #headers } } }; expanded } fn get_tabled_length(ast: &DeriveInput, attrs: &StructAttributes) -> Result { match &ast.data { Data::Struct(data) => get_fields_length(&data.fields), Data::Enum(data) => { if attrs.inline { Ok(quote! { 1 }) } else { get_enum_length(data) } } Data::Union(_) => Err(Error::message("Union type isn't supported")), } } fn get_fields_length(fields: &Fields) -> Result { let size_components = fields .iter() .map(|field| { let attributes = Attributes::parse(&field.attrs)?; Ok((field, attributes)) }) .collect::, Error>>()? .into_iter() .filter(|(_, attr)| !attr.is_ignored()) .map(|(field, attr)| { if attr.inline { let field_type = &field.ty; quote!({<#field_type as Tabled>::LENGTH}) } else { quote!({ 1 }) } }); let size_components = std::iter::once(quote!(0)).chain(size_components); let mut stream = TokenStream::new(); stream.append_separated(size_components, syn::token::Add::default()); Ok(stream) } fn get_enum_length(enum_ast: &DataEnum) -> Result { let variant_sizes = get_enum_variant_length(enum_ast); let mut stream = TokenStream::new(); for (i, size) in variant_sizes.enumerate() { let size = size?; if i != 0 { stream.append_all(syn::token::Add::default().into_token_stream()); } stream.append_all(size); } Ok(stream) } fn get_enum_variant_length( enum_ast: &DataEnum, ) -> impl Iterator> + '_ { enum_ast .variants .iter() .map(|variant| -> Result<_, Error> { let attributes = Attributes::parse(&variant.attrs)?; Ok((variant, attributes)) }) .filter(|result| result.is_err() || matches!(result, Ok((_, attr)) if !attr.is_ignored())) .map(|result| { let (variant, attr) = result?; if attr.inline { get_fields_length(&variant.fields) } else { Ok(quote!(1)) } }) } fn collect_info(ast: &DeriveInput, attrs: &StructAttributes) -> Result { match &ast.data { Data::Struct(data) => collect_info_struct(data, attrs), Data::Enum(data) => collect_info_enum(data, attrs, &ast.ident), Data::Union(_) => Err(Error::message("Union type isn't supported")), } } fn collect_info_struct(ast: &DataStruct, attrs: &StructAttributes) -> Result { info_from_fields(&ast.fields, attrs, field_var_name, "") } // todo: refactoring. instead of using a lambda + prefix // we could just not emit `self.` `_x` inside // So the called would prefix it on its own fn info_from_fields( fields: &Fields, attrs: &StructAttributes, field_name: impl Fn(usize, &Field) -> TokenStream, header_prefix: &str, ) -> Result { let count_fields = fields.len(); let fields = fields .into_iter() .enumerate() .map(|(i, field)| -> Result<_, Error> { let mut attributes = Attributes::parse(&field.attrs)?; merge_attributes(&mut attributes, attrs); Ok((i, field, attributes)) }); let mut headers = Vec::new(); let mut values = Vec::new(); let mut reorder = HashMap::new(); let mut skipped = 0; for result in fields { let (i, field, attributes) = result?; if attributes.is_ignored() { skipped += 1; continue; } if let Some(order) = attributes.order { if order >= count_fields { return Err(Error::message(format!( "An order index '{order}' is out of fields scope" ))); } reorder.insert(order, i - skipped); } let header = field_headers(field, i, &attributes, header_prefix); headers.push(header); let field_name = field_name(i, field); let value = get_field_fields(&field_name, &attributes); values.push(value); } if !reorder.is_empty() { values = reorder_fields(&reorder, &values); headers = reorder_fields(&reorder, &headers); } let headers = quote!({ let mut out = Vec::new(); #(out.extend(#headers);)* out }); let values = quote!({ let mut out = Vec::new(); #(out.extend(#values);)* out }); Ok(Impl { headers, values }) } fn reorder_fields(order: &HashMap, elements: &[T]) -> Vec { let mut out: Vec> = Vec::with_capacity(elements.len()); out.resize(elements.len(), None); for (pos, index) in order { let value = elements[*index].clone(); out[*pos] = Some(value); } let mut j = 0; for el in &mut out { if el.is_some() { continue; } while order.values().any(|&pos| j == pos) { j += 1; } let v = elements[j].clone(); *el = Some(v); j += 1; } out.into_iter().flatten().collect() } fn field_headers( field: &Field, index: usize, attributes: &Attributes, prefix: &str, ) -> TokenStream { if attributes.inline { let prefix = attributes .inline_prefix .as_ref() .map_or_else(|| "", |s| s.as_str()); return get_type_headers(&field.ty, prefix, ""); } let header_name = field_header_name(field, attributes, index); if prefix.is_empty() { quote!(vec![::std::borrow::Cow::Borrowed(#header_name)]) } else { let name = format!("{prefix}{header_name}"); quote!(vec![::std::borrow::Cow::Borrowed(#name)]) } } fn collect_info_enum( ast: &DataEnum, attrs: &StructAttributes, name: &Ident, ) -> Result { match &attrs.inline { true => { let enum_name = attrs .inline_value .clone() .unwrap_or_else(|| name.to_string()); collect_info_enum_inlined(ast, attrs, enum_name) } false => _collect_info_enum(ast, attrs), } } fn _collect_info_enum(ast: &DataEnum, attrs: &StructAttributes) -> Result { // reorder variants according to order (if set) let orderedvariants = reodered_variants(ast)?; let mut headers_list = Vec::new(); let mut variants = Vec::new(); for v in orderedvariants { let mut attributes = Attributes::parse(&v.attrs)?; merge_attributes(&mut attributes, attrs); if attributes.is_ignored() { continue; } let info = info_from_variant(v, &attributes, attrs)?; variants.push((v, info.values)); headers_list.push(info.headers); } let variant_sizes = get_enum_variant_length(ast) .collect::, Error>>()? .into_iter(); let values = values_for_enum(variant_sizes, &variants); let headers = quote! { vec![ #(#headers_list,)* ] .concat() }; Ok(Impl { headers, values }) } fn collect_info_enum_inlined( ast: &DataEnum, attrs: &StructAttributes, enum_name: String, ) -> Result { let orderedvariants = reodered_variants(ast)?; let mut variants = Vec::new(); let mut names = Vec::new(); for variant in orderedvariants { let mut attributes = Attributes::parse(&variant.attrs)?; merge_attributes(&mut attributes, attrs); let mut name = String::new(); if !attributes.is_ignored() { name = variant_name(variant, &attributes); } variants.push(match_variant(variant)); names.push(name); } let headers = quote! { vec![::std::borrow::Cow::Borrowed(#enum_name)] }; let values = quote! { #[allow(unused_variables)] match &self { #(Self::#variants => vec![::std::borrow::Cow::Borrowed(#names)],)* } }; Ok(Impl { headers, values }) } fn info_from_variant( variant: &Variant, attr: &Attributes, attrs: &StructAttributes, ) -> Result { if attr.inline { let prefix = attr .inline_prefix .as_ref() .map_or_else(|| "", |s| s.as_str()); return info_from_fields(&variant.fields, attrs, variant_var_name, prefix); } let variant_name = variant_name(variant, attr); let value = if let Some(func) = &attr.display_with { let args = match &attr.display_with_args { None => None, Some(args) => match args.is_empty() { true => None, false => { let args = args.iter().map(fnarg_tokens).collect::>(); Some(quote!( #(#args,)* )) } }, }; let call = match args { Some(args) => use_function(&args, func), None => use_function_no_args(func), }; quote! { ::std::borrow::Cow::from(#call) } } else { let default_value = "+"; quote! { ::std::borrow::Cow::Borrowed(#default_value) } }; // we need exactly string because of it must be inlined as string let headers = quote! { vec![::std::borrow::Cow::Borrowed(#variant_name)] }; // we need exactly string because of it must be inlined as string let values = quote! { vec![#value] }; Ok(Impl { headers, values }) } struct Impl { headers: TokenStream, values: TokenStream, } fn get_type_headers(field_type: &Type, inline_prefix: &str, prefix: &str) -> TokenStream { if prefix.is_empty() && inline_prefix.is_empty() { quote! { <#field_type as Tabled>::headers() } } else { quote! { <#field_type as Tabled>::headers().into_iter() .map(|header| { let header = format!("{}{}{}", #prefix, #inline_prefix, header); ::std::borrow::Cow::Owned(header) }) .collect::>() } } } fn get_field_fields(field: &TokenStream, attr: &Attributes) -> TokenStream { if attr.inline { return quote! { #field.fields() }; } if let Some(func) = &attr.display_with { let args = match &attr.display_with_args { None => Some(quote!(&#field)), Some(args) => match args.is_empty() { true => None, false => { let args = args.iter().map(fnarg_tokens).collect::>(); Some(quote!( #(#args,)* )) } }, }; let call = match args { Some(args) => use_function(&args, func), None => use_function_no_args(func), }; return quote!(vec![::std::borrow::Cow::from(#call)]); } quote!(vec![::std::borrow::Cow::Owned(format!("{}", #field))]) } fn use_function(args: &TokenStream, function: &str) -> TokenStream { let path: syn::Result = syn::parse_str(function); match path { Ok(path) => { quote! { #path(#args) } } Err(_) => { let function = Ident::new(function, proc_macro2::Span::call_site()); quote! { #function(#args) } } } } fn use_function_no_args(function: &str) -> TokenStream { let path: syn::Result = syn::parse_str(function); match path { Ok(path) => { quote! { #path() } } Err(_) => { let function = Ident::new(function, proc_macro2::Span::call_site()); quote! { #function() } } } } fn field_var_name(index: usize, field: &Field) -> TokenStream { let f = field.ident.as_ref().map_or_else( || Index::from(index).to_token_stream(), quote::ToTokens::to_token_stream, ); quote!(self.#f) } fn variant_var_name(index: usize, field: &Field) -> TokenStream { match &field.ident { Some(indent) => indent.to_token_stream(), None => Ident::new( format!("x_{index}").as_str(), proc_macro2::Span::call_site(), ) .to_token_stream(), } } fn values_for_enum( variant_sizes: impl Iterator, variants: &[(&Variant, TokenStream)], ) -> TokenStream { let branches = variants.iter().map(|(variant, _)| match_variant(variant)); let fields = variants .iter() .map(|(_, values)| values) .collect::>(); let mut stream = TokenStream::new(); for (i, (branch, fields)) in branches.into_iter().zip(fields).enumerate() { let branch = quote! { Self::#branch => { let offset = offsets[#i]; let fields: Vec<::std::borrow::Cow<'_, str>> = #fields; for (i, field) in fields.into_iter().enumerate() { out_vec[i+offset] = field; } }, }; stream.append_all(branch); } quote! { // To be able to insert variant fields in proper places we do this MAGIC with offset. // // We check headers output as it's static and has an information // about length of each field header if it was inlined. // // It's a bit strange trick but I haven't found any better // how to calculate a size and offset. let mut offsets: &mut [usize] = &mut [0, #(#variant_sizes,)*]; for i in 1 .. offsets.len() { offsets[i] += offsets[i-1] } let size = ::LENGTH; let mut out_vec = vec![::std::borrow::Cow::Borrowed(""); size]; #[allow(unused_variables)] match &self { #stream _ => return vec![::std::borrow::Cow::Borrowed(""); size], // variant is hidden so we return an empty vector }; out_vec } } fn variant_idents(v: &Variant) -> Vec { v.fields .iter() .enumerate() // we intentionally not ignore these fields to be able to build a pattern correctly // .filter(|(_, field)| !Attr::parse(&field.attrs).is_ignored()) .map(|(index, field)| variant_var_name(index, field)) .collect::>() } fn match_variant(v: &Variant) -> TokenStream { let mut token = TokenStream::new(); token.append_all(v.ident.to_token_stream()); let fields = variant_idents(v); match &v.fields { Fields::Named(_) => { token::Brace::default().surround(&mut token, |s| { s.append_separated(fields, quote! {,}); }); } Fields::Unnamed(_) => { token::Paren::default().surround(&mut token, |s| { s.append_separated(fields, quote! {,}); }); } Fields::Unit => {} }; token } fn variant_name(variant: &Variant, attributes: &Attributes) -> String { attributes .rename .clone() .or_else(|| { attributes .rename_all .as_ref() .map(|case| case.cast(variant.ident.to_string())) }) .unwrap_or_else(|| variant.ident.to_string()) } fn field_header_name(f: &Field, attr: &Attributes, index: usize) -> String { if let Some(name) = &attr.rename { return name.to_string(); } match &f.ident { Some(name) => { let name = name.to_string(); match &attr.rename_all { Some(case) => case.cast(name), None => name, } } None => index.to_string(), } } fn merge_attributes(attr: &mut Attributes, global_attr: &StructAttributes) { if attr.rename_all.is_none() { attr.rename_all = global_attr.rename_all; } } fn fnarg_tokens(arg: &FuncArg) -> TokenStream { match arg { FuncArg::SelfRef => quote! { &self }, FuncArg::Byte(val) => quote! { #val }, FuncArg::Char(val) => quote! { #val }, FuncArg::Bool(val) => quote! { #val }, FuncArg::Uint(val) => quote! { #val }, FuncArg::Int(val) => quote! { #val }, FuncArg::Float(val) => quote! { #val }, FuncArg::String(val) => quote! { #val }, FuncArg::Bytes(val) => { let val = syn::LitByteStr::new(val, proc_macro2::Span::call_site()); quote! { #val } } } } fn reodered_variants(ast: &DataEnum) -> Result, Error> { let mut reorder = HashMap::new(); let mut skip = 0; let count = ast.variants.len(); for (i, attr) in ast .variants .iter() .map(|v| Attributes::parse(&v.attrs).unwrap_or_default()) .enumerate() { if attr.is_ignored { skip += 1; continue; } if let Some(order) = attr.order { if order >= count { return Err(Error::message(format!( "An order index '{order}' is out of fields scope" ))); } reorder.insert(order, i - skip); } } let mut orderedvariants = ast.variants.iter().collect::>(); if !reorder.is_empty() { orderedvariants = reorder_fields(&reorder, &orderedvariants); } Ok(orderedvariants) } tabled_derive-0.6.0/src/parse.rs000064400000000000000000000107531046102023000146750ustar 00000000000000use proc_macro2::{Ident, Span}; use syn::{ parenthesized, parse::Parse, punctuated::Punctuated, token, Attribute, LitBool, LitInt, LitStr, Token, }; pub fn parse_attributes( attributes: &[Attribute], ) -> impl Iterator>> + '_ { attributes .iter() .filter(|attr| attr.path.is_ident("tabled")) .map(|attr| attr.parse_args_with(Punctuated::::parse_terminated)) .map(|result| result.map(IntoIterator::into_iter)) } pub struct TabledAttr { pub ident: Ident, pub kind: TabledAttrKind, } impl TabledAttr { pub fn new(ident: Ident, kind: TabledAttrKind) -> Self { Self { ident, kind } } } #[derive(Clone)] pub enum TabledAttrKind { Skip(LitBool), Inline(LitBool, Option), Rename(LitStr), RenameAll(LitStr), DisplayWith(LitStr, Option, Punctuated), Order(LitInt), } impl Parse for TabledAttr { fn parse(input: syn::parse::ParseStream) -> syn::Result { use TabledAttrKind::*; let name: Ident = input.parse()?; let name_str = name.to_string(); if input.peek(Token![=]) { let assign_token = input.parse::()?; if input.peek(LitStr) { let lit = input.parse::()?; match name_str.as_str() { "rename" => return Ok(Self::new(name, Rename(lit))), "rename_all" => return Ok(Self::new(name, RenameAll(lit))), "display_with" => { return Ok(Self::new(name, DisplayWith(lit, None, Punctuated::new()))) } _ => {} } } if input.peek(LitBool) { let lit = input.parse::()?; match name_str.as_str() { "skip" => return Ok(Self::new(name, Skip(lit))), "inline" => return Ok(Self::new(name, Inline(lit, None))), _ => {} } } if input.peek(LitInt) { let lit = input.parse::()?; if let "order" = name_str.as_str() { return Ok(Self::new(name, Order(lit))); } } return Err(syn::Error::new( assign_token.span, "expected `string literal` or `expression` after `=`", )); } if input.peek(token::Paren) { let nested; let _paren = parenthesized!(nested in input); if nested.peek(LitStr) { let lit = nested.parse::()?; match name_str.as_str() { "display_with" => { let mut args = Punctuated::new(); let mut comma = None; if nested.peek(Token![,]) { comma = Some(nested.parse::()?); while !nested.is_empty() { let val = nested.parse()?; args.push_value(val); if nested.is_empty() { break; } let punct = nested.parse()?; args.push_punct(punct); } }; return Ok(Self::new(name, DisplayWith(lit, comma, args))); } "inline" => { return Ok(Self::new( name, Inline(LitBool::new(true, Span::call_site()), Some(lit)), )) } _ => {} } } return Err(syn::Error::new( _paren.span, "expected a `string literal` in parenthesis", )); } match name_str.as_str() { "skip" => return Ok(Self::new(name, Skip(LitBool::new(true, Span::call_site())))), "inline" => { return Ok(Self::new( name, Inline(LitBool::new(true, Span::call_site()), None), )) } _ => {} } Err(syn::Error::new( name.span(), format!("unexpected attribute: {name_str}"), )) } }