tabled_derive-0.10.0/.cargo_vcs_info.json0000644000000001530000000000100137020ustar { "git": { "sha1": "d61e3f60aa633423f5ca6bf6b50953013c57bf92" }, "path_in_vcs": "tabled_derive" }tabled_derive-0.10.0/Cargo.lock0000644000000035150000000000100116620ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "proc-macro-error-attr2" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" dependencies = [ "proc-macro2", "quote", ] [[package]] name = "proc-macro-error2" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", "syn", ] [[package]] name = "proc-macro2" version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] [[package]] name = "syn" version = "2.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tabled_derive" version = "0.10.0" dependencies = [ "heck", "proc-macro-error2", "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-ident" version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034" tabled_derive-0.10.0/Cargo.toml0000644000000022130000000000100116770ustar # 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.10.0" authors = ["Maxim Zhiburt "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Derive macros which is used by tabled crate" readme = false license = "MIT" repository = "https://github.com/zhiburt/tabled" [lib] name = "tabled_derive" path = "src/lib.rs" proc-macro = true [dependencies.heck] version = "0.5" [dependencies.proc-macro-error2] version = "2.0.1" [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.syn] version = "2" features = [ "full", "visit-mut", "extra-traits", ] tabled_derive-0.10.0/Cargo.toml.orig000064400000000000000000000006541046102023000153670ustar 00000000000000[package] name = "tabled_derive" version = "0.10.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 = { version = "2", features = ["full", "visit-mut", "extra-traits"] } quote = "1" proc-macro2 = "1" heck = "0.5" proc-macro-error2 = "2.0.1" tabled_derive-0.10.0/LICENSE-MIT000064400000000000000000000020561046102023000141320ustar 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.10.0/src/attributes/field_attr.rs000064400000000000000000000056651046102023000201470ustar 00000000000000use syn::{Attribute, LitInt}; use crate::{ casing_style::CasingStyle, error::Error, parse::field_attr::{parse_field_attributes, FieldAttr, FieldAttrKind}, }; #[derive(Default)] pub struct FieldAttributes { 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, pub format: Option, pub format_with_args: Option>, } pub struct FormatArg { pub expr: syn::Expr, } impl FormatArg { pub fn new(expr: syn::Expr) -> Self { Self { expr } } } impl FieldAttributes { 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_field_attributes(attrs) { let attrs = attrs?; for attr in attrs { self.insert_attribute(attr)?; } } Ok(()) } fn insert_attribute(&mut self, attr: FieldAttr) -> Result<(), Error> { match attr.kind { FieldAttrKind::Skip(b) => { if b.value { self.is_ignored = true; } } FieldAttrKind::Inline(b, prefix) => { if b.value { self.inline = true; } if let Some(prefix) = prefix { self.inline_prefix = Some(prefix.value()); } } FieldAttrKind::Rename(value) => self.rename = Some(value.value()), FieldAttrKind::RenameAll(lit) => { self.rename_all = Some(CasingStyle::from_lit(&lit)?); } FieldAttrKind::DisplayWith(path, comma, args) => { self.display_with = Some(path.value()); if comma.is_some() { let args = args.into_iter().map(FormatArg::new).collect(); self.display_with_args = Some(args); } } FieldAttrKind::FormatWith(format, comma, args) => { self.format = Some(format.value()); if comma.is_some() { let args = args.into_iter().map(FormatArg::new).collect(); self.format_with_args = Some(args); } } FieldAttrKind::Order(value) => self.order = Some(lit_int_to_usize(&value)?), } Ok(()) } } 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, ) }) } tabled_derive-0.10.0/src/attributes/mod.rs000064400000000000000000000001651046102023000165770ustar 00000000000000mod field_attr; mod type_attr; pub use field_attr::{FieldAttributes, FormatArg}; pub use type_attr::TypeAttributes; tabled_derive-0.10.0/src/attributes/type_attr.rs000064400000000000000000000036101046102023000200310ustar 00000000000000use syn::{Attribute, TypePath}; use crate::{ attributes::FormatArg, casing_style::CasingStyle, error::Error, parse::type_attr::{parse_type_attributes, TypeAttr, TypeAttrKind}, }; #[derive(Default)] pub struct TypeAttributes { pub rename_all: Option, pub inline: bool, pub inline_value: Option, pub crate_name: Option, pub display_types: Vec<(TypePath, String, Vec)>, } impl TypeAttributes { 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_type_attributes(attrs) { let attrs = attrs?; for attr in attrs { self.insert_attribute(attr)?; } } Ok(()) } fn insert_attribute(&mut self, attr: TypeAttr) -> Result<(), Error> { match attr.kind { TypeAttrKind::Crate(crate_name) => { let name = crate_name.value(); if !name.is_empty() { self.crate_name = Some(name); } } TypeAttrKind::Inline(b, prefix) => { if b.value { self.inline = true; } if let Some(prefix) = prefix { self.inline_value = Some(prefix.value()); } } TypeAttrKind::RenameAll(lit) => { self.rename_all = Some(CasingStyle::from_lit(&lit)?); } TypeAttrKind::DisplayType(type_name, func, args) => { let args = args.into_iter().map(FormatArg::new).collect(); self.display_types.push((type_name, func.value(), args)); } } Ok(()) } } tabled_derive-0.10.0/src/casing_style.rs000064400000000000000000000047311046102023000163210ustar 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("supported 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.10.0/src/error.rs000064400000000000000000000027631046102023000147710ustar 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_error2::abort! {err.span(), "{}", err} } Error::Custom { span, error, help } => match help { Some(help) => { proc_macro_error2::abort! {span, "{}", error; help="{}", help} } None => { proc_macro_error2::abort! {span, "{}", error} } }, } } tabled_derive-0.10.0/src/lib.rs000064400000000000000000000641321046102023000144040ustar 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 attributes::FormatArg; use proc_macro2::TokenStream; use proc_macro_error2::proc_macro_error; use quote::{quote, ToTokens, TokenStreamExt}; use std::{collections::HashMap, str}; use syn::visit_mut::VisitMut; use syn::{ parse_macro_input, token, Data, DataEnum, DataStruct, DeriveInput, ExprPath, Field, Fields, Ident, Index, PathSegment, Type, TypePath, Variant, }; use crate::attributes::{FieldAttributes, TypeAttributes}; use crate::error::Error; type FieldNameFn = fn(usize, &Field) -> TokenStream; #[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 = TypeAttributes::parse(&ast.attrs) .map_err(error::abort) .unwrap(); let tabled_trait_path = get_crate_name_expr(&attrs).map_err(error::abort).unwrap(); let length = get_tabled_length(ast, &attrs, &tabled_trait_path) .map_err(error::abort) .unwrap(); let info = collect_info(ast, &attrs, &tabled_trait_path) .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_trait_path 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: &TypeAttributes, trait_path: &ExprPath, ) -> Result { match &ast.data { Data::Struct(data) => get_fields_length(&data.fields, trait_path), Data::Enum(data) => { if attrs.inline { Ok(quote! { 1 }) } else { get_enum_length(data, trait_path) } } Data::Union(_) => Err(Error::message("Union type isn't supported")), } } fn get_fields_length(fields: &Fields, tabled_trait: &ExprPath) -> Result { let size_components = fields .iter() .map(|field| { let attributes = FieldAttributes::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_trait>::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::Plus::default()); Ok(stream) } fn get_enum_length(enum_ast: &DataEnum, trait_path: &ExprPath) -> Result { let variant_sizes = get_enum_variant_length(enum_ast, trait_path); let mut stream = TokenStream::new(); for (i, size) in variant_sizes.enumerate() { let size = size?; if i != 0 { stream.append_all(syn::token::Plus::default().into_token_stream()); } stream.append_all(size); } Ok(stream) } fn get_enum_variant_length<'a>( enum_ast: &'a DataEnum, trait_path: &'a ExprPath, ) -> impl Iterator> + 'a { enum_ast .variants .iter() .map(|variant| -> Result<_, Error> { let attributes = FieldAttributes::parse(&variant.attrs)?; Ok((variant, attributes)) }) .filter(|result| result.is_err() || matches!(result, Ok((_, attr)) if !attr.is_ignored)) .map(move |result| { let (variant, attr) = result?; if attr.inline { get_fields_length(&variant.fields, trait_path) } else { Ok(quote!(1)) } }) } fn collect_info( ast: &DeriveInput, attrs: &TypeAttributes, trait_path: &ExprPath, ) -> Result { match &ast.data { Data::Struct(data) => collect_info_struct(data, attrs, trait_path), Data::Enum(data) => collect_info_enum(data, attrs, &ast.ident, trait_path), Data::Union(_) => Err(Error::message("Union type isn't supported")), } } fn collect_info_struct( ast: &DataStruct, attrs: &TypeAttributes, trait_path: &ExprPath, ) -> Result { info_from_fields(&ast.fields, attrs, struct_field_name, "", trait_path) } // 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: &TypeAttributes, field_name: FieldNameFn, header_prefix: &str, trait_path: &ExprPath, ) -> Result { let count_fields = fields.len(); let attributes = fields .into_iter() .enumerate() .map(|(i, field)| -> Result<_, Error> { let mut attributes = FieldAttributes::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 attributes { 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, trait_path); headers.push(header); let field_name_result = field_name(i, field); let value = get_field_fields( &field_name_result, &field.ty, &attributes, fields, field_name, attrs, ); 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: &FieldAttributes, prefix: &str, trait_path: &ExprPath, ) -> 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, "", trait_path); } 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: &TypeAttributes, name: &Ident, trait_path: &ExprPath, ) -> 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, trait_path), } } fn _collect_info_enum( ast: &DataEnum, attrs: &TypeAttributes, trait_path: &ExprPath, ) -> 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 = FieldAttributes::parse(&v.attrs)?; merge_attributes(&mut attributes, attrs); if attributes.is_ignored { continue; } let info = info_from_variant(v, &attributes, attrs, trait_path)?; variants.push((v, info.values)); headers_list.push(info.headers); } let variant_sizes = get_enum_variant_length(ast, trait_path) .collect::, Error>>()? .into_iter(); let values = values_for_enum(variant_sizes, &variants, trait_path); let headers = quote! { [ #(#headers_list,)* ] .concat() }; Ok(Impl { headers, values }) } fn collect_info_enum_inlined( ast: &DataEnum, attrs: &TypeAttributes, 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 = FieldAttributes::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: &FieldAttributes, attrs: &TypeAttributes, trait_path: &ExprPath, ) -> 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_field_name, prefix, trait_path, ); } let variant_name = variant_name(variant, attr); let value = if let Some(func) = &attr.display_with { let args = match &attr.display_with_args { Some(args) => { args_to_tokens_with(&Fields::Unit, "e!(self), struct_field_name, args) } None => quote!(&self), }; let result = use_function(&args, func); quote! { ::std::borrow::Cow::from(#result) } } else if let Some(fmt) = &attr.format { let args = attr .format_with_args .as_ref() .and_then(|args| args_to_tokens(&Fields::Unit, struct_field_name, args)); let call = match args { Some(args) => use_format(fmt, &args), None => use_format_no_args(fmt), }; 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, tabled_trait: &ExprPath, ) -> TokenStream { if prefix.is_empty() && inline_prefix.is_empty() { quote! { <#field_type as #tabled_trait>::headers() } } else { quote! { <#field_type as #tabled_trait>::headers().into_iter() .map(|header| { let header = format!("{}{}{}", #prefix, #inline_prefix, header); ::std::borrow::Cow::Owned(header) }) .collect::>() } } } fn get_field_fields( field: &TokenStream, field_type: &Type, attr: &FieldAttributes, fields: &Fields, field_name: FieldNameFn, type_attrs: &TypeAttributes, ) -> TokenStream { if attr.inline { return quote! { #field.fields() }; } if let Some(func) = &attr.display_with { let args = match &attr.display_with_args { Some(args) => args_to_tokens_with(fields, field, field_name, args), None => quote!(&#field), }; let result = use_function(&args, func); return quote!(vec![::std::borrow::Cow::from(#result)]); } else if let Some(fmt) = &attr.format { let args = attr .format_with_args .as_ref() .and_then(|args| args_to_tokens(fields, field_name, args)); let call = match args { Some(args) => use_format(fmt, &args), None => use_format_with_one_arg(fmt, field), }; return quote!(vec![::std::borrow::Cow::Owned(#call)]); } if let Some(i) = find_display_type(field_type, &type_attrs.display_types) { let (_, func, args) = &type_attrs.display_types[i]; let args = args_to_tokens_with(fields, field, field_name, args); let func = use_function(&args, func); return quote!(vec![::std::borrow::Cow::from(#func)]); } quote!(vec![::std::borrow::Cow::Owned(format!("{}", #field))]) } fn args_to_tokens( fields: &Fields, field_name: fn(usize, &Field) -> TokenStream, args: &[FormatArg], ) -> Option { if args.is_empty() { return None; } let args = args .iter() .map(|arg| fnarg_tokens(arg, fields, field_name)) .collect::>(); Some(quote!( #(#args,)* )) } fn args_to_tokens_with( fields: &Fields, field: &TokenStream, field_name: fn(usize, &Field) -> TokenStream, args: &[FormatArg], ) -> TokenStream { if args.is_empty() { return quote!(&#field); } let mut out = vec![quote!(&#field)]; for arg in args { let arg = fnarg_tokens(arg, fields, field_name); out.push(arg); } quote!( #(#out,)* ) } fn find_display_type(ty: &Type, types: &[(TypePath, String, Vec)]) -> Option { let p: &TypePath = match ty { Type::Path(path) => path, _ => return None, }; // NOTICE: // We do iteration in a back order to satisfy a later set argument first. // // TODO: Maybe we shall change the data structure for it rather then doing a reverse iteration? // I am just saying it's dirty a little. let args = types.iter().enumerate().rev(); for (i, (arg, _, _)) in args { if arg.path == p.path { return Some(i); } // NOTICE: // There's a specical case where we wanna match a type without a generic, // e.g. 'Option' with which we wanna match all 'Option's. // // Because in the scope we can only have 1 type name, it's considered to be good, // and nothing must be broken. let arg_segment = arg.path.segments.last(); let type_segment = p.path.segments.last(); if let Some(arg) = arg_segment { if arg.arguments.is_empty() { if let Some(p) = type_segment { if p.ident == arg.ident { return Some(i); } } } } } None } 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_format(custom_format: &str, args: &TokenStream) -> TokenStream { quote! { format!(#custom_format, #args) } } fn use_format_with_one_arg(custom_format: &str, field: &TokenStream) -> TokenStream { quote! { format!(#custom_format, #field) } } fn use_format_no_args(custom_format: &str) -> TokenStream { quote! { format!(#custom_format) } } fn struct_field_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_field_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)], tabled_trait: &ExprPath, ) -> 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_field_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: &FieldAttributes) -> 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: &FieldAttributes, 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 FieldAttributes, global_attr: &TypeAttributes) { if attr.rename_all.is_none() { attr.rename_all = global_attr.rename_all; } } // to resolve invocation issues withing a macros calls // we need such a workround struct ExprSelfReplace<'a>(Option<(&'a Fields, FieldNameFn)>); impl syn::visit_mut::VisitMut for ExprSelfReplace<'_> { fn visit_expr_mut(&mut self, node: &mut syn::Expr) { match &node { syn::Expr::Path(path) => { let indent = path.path.get_ident(); if let Some(indent) = indent { if indent == "self" { *node = syn::parse_quote! { (&self) }; return; } } } syn::Expr::Field(field) => { // treating a enum variant structs which we can't reference by 'self' if let Some((fields, field_name)) = &self.0 { // check that it's plain self reference if let syn::Expr::Path(path) = field.base.as_ref() { let indent = path.path.get_ident(); if let Some(indent) = indent { if indent != "self" { return; } } } let used_field = { match &field.member { syn::Member::Named(ident) => ident.to_string(), syn::Member::Unnamed(index) => index.index.to_string(), } }; // We find the corresponding field in the local object fields instead of using self, // which would be a higher level object. This is for nested structures. for (i, field) in fields.iter().enumerate() { let field_name_result = (field_name)(i, field); let field_name = field .ident .as_ref() .map_or_else(|| i.to_string(), |i| i.to_string()); if field_name == used_field { *node = syn::parse_quote! { #field_name_result }; return; } } } } syn::Expr::Macro(_) => { // NOTE: Can we parse inners of Macros? // // A next example will fail on `self.f1` usage // with such error 'expected value, found module `self`' // // ``` // some_macro! { // struct Something { // #[tabled(display("_", format!("", self.f1)))] // field: Option, // f1: usize, // } // } // ``` } _ => (), } // Delegate to the default impl to visit nested expressions. syn::visit_mut::visit_expr_mut(self, node); } } fn fnarg_tokens(arg: &FormatArg, fields: &Fields, field_name: FieldNameFn) -> TokenStream { let mut exp = arg.expr.clone(); ExprSelfReplace(Some((fields, field_name))).visit_expr_mut(&mut exp); quote!(#exp) } 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| FieldAttributes::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) } fn get_crate_name_expr(attrs: &TypeAttributes) -> Result { let crate_name = attrs .crate_name .clone() .unwrap_or_else(|| String::from("::tabled")); let crate_name = parse_crate_name(&crate_name)?; Ok(create_tabled_trait_path(crate_name)) } fn parse_crate_name(name: &str) -> Result { syn::parse_str(name).map_err(|_| Error::message("unexpected crate attribute type")) } fn create_tabled_trait_path(mut p: ExprPath) -> ExprPath { p.path.segments.push(PathSegment { ident: Ident::new("Tabled", proc_macro2::Span::call_site()), arguments: syn::PathArguments::None, }); p } tabled_derive-0.10.0/src/parse/field_attr.rs000064400000000000000000000113011046102023000170530ustar 00000000000000use proc_macro2::{Ident, Span}; use syn::{ parenthesized, parse::Parse, punctuated::Punctuated, spanned::Spanned, token, Attribute, LitBool, LitInt, LitStr, Token, }; pub fn parse_field_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 FieldAttr { pub kind: FieldAttrKind, } impl FieldAttr { pub fn new(kind: FieldAttrKind) -> Self { Self { kind } } } #[derive(Clone)] pub enum FieldAttrKind { Skip(LitBool), Inline(LitBool, Option), Rename(LitStr), RenameAll(LitStr), DisplayWith(LitStr, Option, Punctuated), Order(LitInt), FormatWith(LitStr, Option, Punctuated), } impl Parse for FieldAttr { fn parse(input: syn::parse::ParseStream) -> syn::Result { use FieldAttrKind::*; 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(Rename(lit))), "rename_all" => return Ok(Self::new(RenameAll(lit))), "display" => return Ok(Self::new(DisplayWith(lit, None, Punctuated::new()))), "format" => return Ok(Self::new(FormatWith(lit, None, Punctuated::new()))), _ => {} } } if input.peek(LitBool) { let lit = input.parse::()?; match name_str.as_str() { "skip" => return Ok(Self::new(Skip(lit))), "inline" => return Ok(Self::new(Inline(lit, None))), _ => {} } } if input.peek(LitInt) { let lit = input.parse::()?; if let "order" = name_str.as_str() { return Ok(Self::new(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() { "format" | "display" => { 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); } }; if name_str.as_str() == "format" { return Ok(Self::new(FormatWith(lit, comma, args))); } return Ok(Self::new(DisplayWith(lit, comma, args))); } "inline" => { return Ok(Self::new(Inline( LitBool::new(true, Span::call_site()), Some(lit), ))) } _ => {} } } return Err(syn::Error::new( _paren.span.span(), "expected a `string literal` in parenthesis", )); } match name_str.as_str() { "skip" => return Ok(Self::new(Skip(LitBool::new(true, Span::call_site())))), "inline" => { return Ok(Self::new(Inline( LitBool::new(true, Span::call_site()), None, ))) } _ => {} } Err(syn::Error::new( name.span(), format!("unexpected attribute: {name_str}"), )) } } tabled_derive-0.10.0/src/parse/mod.rs000064400000000000000000000000471046102023000155220ustar 00000000000000pub mod field_attr; pub mod type_attr; tabled_derive-0.10.0/src/parse/type_attr.rs000064400000000000000000000075321046102023000167640ustar 00000000000000use proc_macro2::{Ident, Span}; use syn::{ parenthesized, parse::Parse, punctuated::Punctuated, spanned::Spanned, token, Attribute, LitBool, LitStr, Token, TypePath, }; pub fn parse_type_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 TypeAttr { pub kind: TypeAttrKind, } impl TypeAttr { pub fn new(kind: TypeAttrKind) -> Self { Self { kind } } } #[derive(Clone)] pub enum TypeAttrKind { Inline(LitBool, Option), RenameAll(LitStr), Crate(LitStr), DisplayType(TypePath, LitStr, Punctuated), } impl Parse for TypeAttr { fn parse(input: syn::parse::ParseStream) -> syn::Result { use TypeAttrKind::*; if input.peek(syn::token::Crate) { let _: syn::token::Crate = input.parse()?; let _ = input.parse::()?; let value = input.parse::()?; return Ok(Self::new(Crate(value))); } 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::()?; if name_str.as_str() == "rename_all" { return Ok(Self::new(RenameAll(lit))); } } if input.peek(LitBool) { let lit = input.parse::()?; if name_str.as_str() == "inline" { return Ok(Self::new(Inline(lit, None))); } } 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::()?; if name_str.as_str() == "inline" { return Ok(Self::new(Inline( LitBool::new(true, Span::call_site()), Some(lit), ))); } } if name_str.as_str() == "display" { let path = nested.parse::()?; let _comma = nested.parse::()?; let lit = nested.parse::()?; let mut args: Punctuated = Punctuated::new(); if nested.peek(Token![,]) { _ = 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(DisplayType(path, lit, args))); } return Err(syn::Error::new( _paren.span.span(), "expected a `string literal` in parenthesis", )); } if name_str.as_str() == "inline" { return Ok(Self::new(Inline( LitBool::new(true, Span::call_site()), None, ))); } Err(syn::Error::new( name.span(), format!("unexpected attribute: {name_str}"), )) } }