├── .gitignore ├── justfile ├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── rustfmt.toml ├── tests ├── delegate_mut.rs ├── delegate_lifetime.rs ├── derive_delegate_single.rs ├── derive_delegate.rs └── derive_delegate_either.rs ├── framework ├── src │ ├── no_args.rs │ ├── lib.rs │ ├── impl_filler.rs │ ├── item_map.rs │ ├── derive_filler.rs │ ├── impl_completer.rs │ └── derive_completer.rs └── Cargo.toml ├── codegen ├── Cargo.toml └── src │ ├── lib.rs │ ├── impl_fillers │ ├── default.rs │ ├── log.rs │ └── delegate.rs │ ├── fill.rs │ ├── derive.rs │ ├── util.rs │ ├── make.rs │ └── derive_fillers │ └── derive_delegate.rs ├── Cargo.toml ├── examples └── example.rs ├── README.md ├── LICENSE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | **/*.rs.bk 4 | .*.sw[a-z] 5 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | set shell := ["bash", "-O", "globstar", "-c"] 2 | 3 | fmt: 4 | rustfmt +nightly ./**/*.rs 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | fn_single_line = true 2 | format_code_in_doc_comments = true 3 | format_strings = true 4 | group_imports = "StdExternalCrate" 5 | imports_granularity = "Module" 6 | struct_field_align_threshold = 40 7 | use_field_init_shorthand = true 8 | use_small_heuristics = "Max" 9 | -------------------------------------------------------------------------------- /tests/delegate_mut.rs: -------------------------------------------------------------------------------- 1 | #[portrait::make] 2 | trait MyTrait { 3 | fn with_mut_arg(&self, mut _x: u32) { 4 | println!("with_mut_arg"); 5 | } 6 | } 7 | struct A {} 8 | 9 | impl MyTrait for A {} 10 | 11 | struct B { 12 | inner: A, 13 | } 14 | 15 | #[portrait::fill(portrait::delegate(A; self.inner))] // Without this, the panic will not be triggered. 16 | impl MyTrait for B {} 17 | -------------------------------------------------------------------------------- /framework/src/no_args.rs: -------------------------------------------------------------------------------- 1 | use syn::parse::{Parse, ParseStream}; 2 | use syn::Result; 3 | 4 | /// No arguments accepted by the macro. 5 | pub struct NoArgs; 6 | 7 | impl Parse for NoArgs { 8 | fn parse(input: ParseStream) -> Result { 9 | if input.is_empty() { 10 | Ok(Self) 11 | } else { 12 | Err(input.error("No argument expected")) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tests/delegate_lifetime.rs: -------------------------------------------------------------------------------- 1 | #[portrait::make] 2 | trait MyTrait { 3 | fn with_lifetime<'a>(&'a self); 4 | } 5 | struct A {} 6 | 7 | impl MyTrait for A { 8 | fn with_lifetime<'a>(&'a self) { 9 | println!("do nothing"); 10 | } 11 | } 12 | 13 | struct B { 14 | inner: A, 15 | } 16 | 17 | #[portrait::fill(portrait::delegate(A; self.inner))] // Without this, the panic will not be triggered. 18 | impl MyTrait for B {} 19 | -------------------------------------------------------------------------------- /framework/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "portrait-framework" 3 | version = "0.3.1" 4 | authors = ["SOFe "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/SOF3/portrait" 8 | homepage = "https://github.com/SOF3/portrait" 9 | description = "Framework for implementing portrait fillers" 10 | 11 | [dependencies] 12 | heck = "0.4.1" 13 | proc-macro2 = "1.0.50" 14 | quote = "1.0.23" 15 | rand = "0.8.5" 16 | syn = {version = "2.0.4", features = ["full", "visit"]} 17 | -------------------------------------------------------------------------------- /tests/derive_delegate_single.rs: -------------------------------------------------------------------------------- 1 | #[portrait::make] 2 | trait Foo { 3 | fn foo(&self, arg1: i32, arg2: &str, arg3: &mut i64) -> bool; 4 | } 5 | 6 | #[portrait::fill(portrait::default)] 7 | impl Foo for i32 {} 8 | 9 | #[portrait::fill(portrait::default)] 10 | impl Foo for String {} 11 | 12 | #[portrait::derive(Foo with portrait::derive_delegate)] 13 | enum Impls { 14 | A(i32), 15 | B(String), 16 | } 17 | 18 | fn main() { 19 | fn assert(_: impl Foo) {} 20 | 21 | assert(Impls::A(1)); 22 | } 23 | -------------------------------------------------------------------------------- /tests/derive_delegate.rs: -------------------------------------------------------------------------------- 1 | #[portrait::make] 2 | trait Foo { 3 | fn new(arg1: i32, arg2: &str, arg3: &mut i64) -> Self; 4 | fn print(&self); 5 | fn clone(&self) -> Self; 6 | #[portrait(derive_delegate(reduce = |a, b| a && b))] 7 | fn eq(&self, other: &Self) -> bool; 8 | } 9 | 10 | #[portrait::fill(portrait::default)] 11 | impl Foo for i32 {} 12 | 13 | #[portrait::fill(portrait::default)] 14 | impl Foo for String {} 15 | 16 | #[portrait::derive(Foo with portrait::derive_delegate)] 17 | struct Fields { 18 | a: i32, 19 | b: String, 20 | } 21 | 22 | fn main() { 23 | fn assert(_: impl Foo) {} 24 | 25 | assert(Fields { a: 1, b: String::new() }); 26 | } 27 | -------------------------------------------------------------------------------- /codegen/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "portrait-codegen" 3 | version = "0.3.1" 4 | authors = ["SOFe "] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/SOF3/portrait" 8 | homepage = "https://github.com/SOF3/portrait" 9 | description = "Internal procedural macros for portrait" 10 | 11 | [features] 12 | default-filler = [] 13 | delegate-filler = [] 14 | derive-delegate-filler = [] 15 | log-filler = [] 16 | 17 | [lib] 18 | proc-macro = true 19 | 20 | [dependencies] 21 | heck = "0.4.1" 22 | proc-macro2 = "1.0.50" 23 | quote = "1.0.23" 24 | rand = "0.8.5" 25 | itertools = "0.12.1" 26 | syn = {version = "2.0.4", features = ["full", "visit", "visit-mut"]} 27 | portrait-framework = {version = "0.3.1", path = "../framework"} 28 | -------------------------------------------------------------------------------- /framework/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Framework for developing portrait filler macros. 2 | //! 3 | //! # Example 4 | 5 | #![cfg_attr(not(debug_assertions), deny(missing_docs))] 6 | 7 | mod impl_filler; 8 | pub use impl_filler::{impl_filler, FillImpl}; 9 | 10 | mod derive_filler; 11 | pub use derive_filler::{derive_filler, FillDerive}; 12 | 13 | mod no_args; 14 | pub use no_args::NoArgs; 15 | 16 | mod impl_completer; 17 | pub use impl_completer::{ 18 | complete_impl, completer_impl_filler, completer_impl_filler2, GenerateImpl, ImplContext, 19 | }; 20 | 21 | mod derive_completer; 22 | pub use derive_completer::{ 23 | complete_derive, completer_derive_filler, completer_derive_filler2, DeriveContext, 24 | GenerateDerive, 25 | }; 26 | 27 | mod item_map; 28 | pub use item_map::{subtract_items, ImplItemMap, TraitItemMap}; 29 | -------------------------------------------------------------------------------- /tests/derive_delegate_either.rs: -------------------------------------------------------------------------------- 1 | use either::Either; 2 | 3 | #[portrait::make] 4 | trait Foo { 5 | #[portrait(derive_delegate(enum_either))] 6 | fn foo(&self, non_copy: String) -> impl Iterator + DoubleEndedIterator; 7 | } 8 | 9 | impl Foo for i32 { 10 | fn foo(&self, _non_copy: String) -> impl Iterator + DoubleEndedIterator { 11 | [1, 2].into_iter() 12 | } 13 | } 14 | 15 | impl Foo for String { 16 | fn foo(&self, _non_copy: String) -> impl Iterator + DoubleEndedIterator { 17 | std::iter::repeat(5).take(5) 18 | } 19 | } 20 | 21 | #[portrait::derive(Foo with portrait::derive_delegate)] 22 | enum Impls { 23 | A(i32), 24 | B(i32), 25 | C(String), 26 | D(String), 27 | } 28 | 29 | fn main() { 30 | fn assert(_: impl Foo) {} 31 | 32 | assert(Impls::A(1)); 33 | } 34 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [".", "codegen", "framework"] 3 | 4 | [package] 5 | name = "portrait" 6 | version = "0.3.1" 7 | authors = ["SOFe "] 8 | edition = "2021" 9 | license = "Apache-2.0" 10 | repository = "https://github.com/SOF3/portrait" 11 | homepage = "https://github.com/SOF3/portrait" 12 | readme = "README.md" 13 | description = "Fills an `impl` with the associated items required by the trait." 14 | 15 | [features] 16 | default = ["default-filler", "delegate-filler", "log-filler", "derive-delegate-filler"] 17 | default-filler = ["portrait-codegen/default-filler"] 18 | delegate-filler = ["portrait-codegen/delegate-filler"] 19 | derive-delegate-filler = ["portrait-codegen/derive-delegate-filler"] 20 | log-filler = ["portrait-codegen/log-filler"] 21 | 22 | [dependencies] 23 | portrait-codegen = {version = "0.3.1", path = "./codegen"} 24 | 25 | [dev-dependencies] 26 | either = "1.13.0" 27 | log = "0.4.17" 28 | static_assertions = "1.1.0" 29 | -------------------------------------------------------------------------------- /examples/example.rs: -------------------------------------------------------------------------------- 1 | mod def { 2 | use core::num; 3 | use std::net::Ipv4Addr; 4 | use std::{cell, string}; 5 | 6 | #[portrait::make(import( 7 | core::num, 8 | std::net::Ipv4Addr, 9 | std::{cell, string}, 10 | ))] 11 | pub trait Definition { 12 | fn foo() -> i32; 13 | fn bar(&self) -> u32; 14 | fn qux( 15 | &mut self, 16 | ip: Ipv4Addr, 17 | val: cell::RefMut<'_, (num::NonZeroU8,)>, 18 | ) -> std::collections::BTreeSet; 19 | 20 | type Corge; 21 | } 22 | } 23 | 24 | mod user { 25 | use crate::def::{definition_portrait, Definition}; 26 | 27 | struct DefaultUser(T); 28 | 29 | #[portrait::fill(portrait::default)] 30 | impl Definition for DefaultUser { 31 | // portrait::default cannot fill types because there is no such thing as "default type". 32 | type Corge = Option; 33 | } 34 | 35 | struct DelegateUser { 36 | inner: DefaultUser, 37 | } 38 | 39 | #[portrait::fill(portrait::delegate(DefaultUser; self.inner))] 40 | impl Definition for DelegateUser {} 41 | } 42 | 43 | fn main() {} 44 | -------------------------------------------------------------------------------- /codegen/src/lib.rs: -------------------------------------------------------------------------------- 1 | use proc_macro::TokenStream; 2 | 3 | mod util; 4 | 5 | mod make; 6 | #[proc_macro_attribute] 7 | pub fn make(attr: TokenStream, item: TokenStream) -> TokenStream { 8 | make::run(attr.into(), item.into()).unwrap_or_else(|err| err.into_compile_error()).into() 9 | } 10 | 11 | mod fill; 12 | #[proc_macro_attribute] 13 | pub fn fill(attr: TokenStream, item: TokenStream) -> TokenStream { 14 | fill::run(attr.into(), item.into()).unwrap_or_else(|err| err.into_compile_error()).into() 15 | } 16 | 17 | mod derive; 18 | #[proc_macro_attribute] 19 | pub fn derive(attr: TokenStream, item: TokenStream) -> TokenStream { 20 | derive::run(attr.into(), item.into()).unwrap_or_else(|err| err.into_compile_error()).into() 21 | } 22 | 23 | macro_rules! fillers { 24 | ($dir:ident $completer_filler:ident: $($names:ident = $feature:literal,)*) => { 25 | mod $dir { 26 | $( 27 | #[cfg(feature = $feature)] 28 | pub(super) mod $names; 29 | )* 30 | } 31 | 32 | $( 33 | #[cfg(feature = $feature)] 34 | #[proc_macro] 35 | pub fn $names(input: TokenStream) -> TokenStream { 36 | portrait_framework::$completer_filler(input, $dir::$names::Generator) 37 | } 38 | )* 39 | } 40 | } 41 | 42 | fillers! { derive_fillers completer_derive_filler: 43 | derive_delegate = "derive-delegate-filler", 44 | } 45 | 46 | fillers! { impl_fillers completer_impl_filler: 47 | default = "default-filler", 48 | delegate = "delegate-filler", 49 | log = "log-filler", 50 | } 51 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | fmt: 7 | name: rustfmt check 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | toolchain: nightly 14 | profile: default 15 | - run: git ls-files | grep -P '.*\.rs$' | xargs rustfmt +nightly --check 16 | lint: 17 | name: clippy lint 18 | runs-on: ubuntu-latest 19 | strategy: 20 | matrix: 21 | toolchain: 22 | - stable 23 | - beta 24 | - nightly 25 | stability: 26 | - "" 27 | - "--release" 28 | steps: 29 | - uses: actions/checkout@v2 30 | - uses: actions-rs/toolchain@v1 31 | with: 32 | toolchain: ${{matrix.toolchain}} 33 | profile: default 34 | default: true 35 | - uses: actions-rs/clippy-check@v1 36 | with: 37 | token: ${{secrets.GITHUB_TOKEN}} 38 | args: --all ${{matrix.stability}} 39 | name: debug${{matrix.stability}} 40 | test: 41 | name: unit tests 42 | runs-on: ubuntu-latest 43 | strategy: 44 | matrix: 45 | toolchain: 46 | - stable 47 | - beta 48 | - nightly 49 | stability: 50 | - "" 51 | - "--release" 52 | steps: 53 | - uses: actions/checkout@v2 54 | - uses: actions-rs/toolchain@v1 55 | with: 56 | toolchain: ${{matrix.toolchain}} 57 | profile: default 58 | default: true 59 | override: true 60 | - name: cargo test 61 | if: ${{ matrix.toolchain != 'nightly' || matrix.stability != '' }} 62 | run: "cargo test --all ${{matrix.stability}}" 63 | - name: cargo test 64 | if: ${{ matrix.toolchain == 'nightly' && matrix.stability == '' }} 65 | run: "cargo test --no-fail-fast --all" 66 | env: 67 | CARGO_INCREMENTAL: "0" 68 | RUSTFLAGS: '-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off' 69 | RUSTDOCFLAGS: '-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off' 70 | - id: coverage 71 | name: coverage report 72 | if: ${{ matrix.toolchain == 'nightly' && matrix.stability == '' }} 73 | uses: actions-rs/grcov@v0.1 74 | - name: upload to codecov 75 | if: ${{ matrix.toolchain == 'nightly' && matrix.stability == '' }} 76 | uses: codecov/codecov-action@v2.1.0 77 | with: 78 | files: ${{ steps.coverage.outputs.report }} 79 | -------------------------------------------------------------------------------- /codegen/src/impl_fillers/default.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::Span; 2 | use quote::quote; 3 | use syn::spanned::Spanned; 4 | use syn::{Error, Result}; 5 | 6 | pub(crate) struct Generator(pub(crate) portrait_framework::NoArgs); 7 | impl portrait_framework::GenerateImpl for Generator { 8 | fn generate_const( 9 | &mut self, 10 | _: portrait_framework::ImplContext, 11 | item: &syn::TraitItemConst, 12 | ) -> Result { 13 | Ok(syn::ImplItemConst { 14 | attrs: item 15 | .attrs 16 | .iter() 17 | .filter(|attr| attr.path().is_ident("cfg")) 18 | .cloned() 19 | .collect(), 20 | vis: syn::Visibility::Inherited, 21 | defaultness: None, 22 | const_token: item.const_token, 23 | ident: item.ident.clone(), 24 | generics: item.generics.clone(), 25 | colon_token: item.colon_token, 26 | ty: item.ty.clone(), 27 | eq_token: syn::Token![=](item.span()), 28 | expr: syn::parse_quote!(Default::default()), 29 | semi_token: item.semi_token, 30 | }) 31 | } 32 | 33 | fn generate_fn( 34 | &mut self, 35 | _: portrait_framework::ImplContext, 36 | item: &syn::TraitItemFn, 37 | ) -> Result { 38 | Ok(syn::ImplItemFn { 39 | attrs: item 40 | .attrs 41 | .iter() 42 | .filter(|attr| attr.path().is_ident("cfg")) 43 | .cloned() 44 | .collect(), 45 | vis: syn::Visibility::Inherited, 46 | defaultness: None, 47 | sig: unuse_sig(item.sig.clone()), 48 | block: syn::parse_quote! { 49 | { Default::default() } 50 | }, 51 | }) 52 | } 53 | 54 | fn generate_type( 55 | &mut self, 56 | _: portrait_framework::ImplContext, 57 | item: &syn::TraitItemType, 58 | ) -> Result { 59 | Err(Error::new_spanned( 60 | item, 61 | "portrait::default cannot implement associated types automatically", 62 | )) 63 | } 64 | } 65 | 66 | fn unuse_sig(mut sig: syn::Signature) -> syn::Signature { 67 | for input in &mut sig.inputs { 68 | if let syn::FnArg::Typed(typed) = input { 69 | typed.attrs.push(syn::Attribute { 70 | pound_token: syn::Token![#](Span::call_site()), 71 | style: syn::AttrStyle::Outer, 72 | bracket_token: syn::token::Bracket(Span::call_site()), 73 | meta: syn::Meta::List(syn::MetaList { 74 | path: syn::parse_quote!(allow), 75 | delimiter: syn::MacroDelimiter::Paren(syn::token::Paren(typed.span())), 76 | tokens: quote!(unused_variables), 77 | }), 78 | }); 79 | } 80 | } 81 | sig 82 | } 83 | -------------------------------------------------------------------------------- /framework/src/impl_filler.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use syn::parse::{Parse, ParseStream}; 3 | use syn::Result; 4 | 5 | /// Determines how to fill an `impl` block. 6 | pub trait FillImpl { 7 | /// The arguments passed to the filler through macros. 8 | type Args: Parse; 9 | 10 | /// Completes the impl given a portrait of the trait items. 11 | fn fill( 12 | self, 13 | portrait: &[syn::TraitItem], 14 | args: Self::Args, 15 | item_impl: &syn::ItemImpl, 16 | ) -> Result; 17 | } 18 | 19 | /// Parses the macro input directly and passes them to the filler. 20 | /// 21 | /// Use this function if information of all implemented/unimplemented trait/impl items 22 | /// are required at the same time. 23 | /// If the filler just maps each unimplemented trait item to an impl item statelessly, 24 | /// use [`completer_impl_filler2`](crate::completer_impl_filler2)/[`proc_macro_impl_filler`](crate::proc_macro_impl_filler) for shorthand. 25 | pub fn impl_filler(input: TokenStream, filler: FillerT) -> Result { 26 | let Input:: { portrait, args, item_impl, debug_print } = syn::parse2(input)?; 27 | 28 | let output = filler.fill(&portrait, args, &item_impl)?; 29 | 30 | if debug_print { 31 | println!("{output}"); 32 | } 33 | 34 | Ok(output) 35 | } 36 | 37 | mod kw { 38 | syn::custom_keyword!(TRAIT_PORTRAIT); 39 | syn::custom_keyword!(ARGS); 40 | syn::custom_keyword!(IMPL); 41 | syn::custom_keyword!(DEBUG_PRINT_FILLER_OUTPUT); 42 | } 43 | 44 | pub(crate) struct Input { 45 | pub(crate) portrait: Vec, 46 | pub(crate) args: ArgsT, 47 | pub(crate) item_impl: syn::ItemImpl, 48 | pub(crate) debug_print: bool, 49 | } 50 | 51 | impl Parse for Input { 52 | fn parse(input: ParseStream) -> Result { 53 | input.parse::()?; 54 | 55 | let portrait_braced; 56 | syn::braced!(portrait_braced in input); 57 | let mut portrait = Vec::new(); 58 | while !portrait_braced.is_empty() { 59 | let item_braced; 60 | syn::braced!(item_braced in portrait_braced); 61 | let item: syn::TraitItem = item_braced.parse()?; 62 | if !item_braced.is_empty() { 63 | return Err(item_braced.error("braces should only contain one trait item")); 64 | } 65 | portrait.push(item); 66 | } 67 | 68 | input.parse::()?; 69 | let args_braced; 70 | syn::braced!(args_braced in input); 71 | let args: ArgsT = args_braced.parse()?; 72 | if !args_braced.is_empty() { 73 | return Err(args_braced.error("args not fully parsed")); 74 | } 75 | 76 | input.parse::()?; 77 | let impl_braced; 78 | syn::braced!(impl_braced in input); 79 | let item_impl = impl_braced.parse()?; 80 | if !impl_braced.is_empty() { 81 | return Err(impl_braced.error("trailing tokens after impl block")); 82 | } 83 | 84 | input.parse::()?; 85 | let dpfo_braced; 86 | syn::braced!(dpfo_braced in input); 87 | let dpfo: syn::LitBool = dpfo_braced.parse()?; 88 | if !dpfo_braced.is_empty() { 89 | return Err(impl_braced.error("trailing tokens after impl block")); 90 | } 91 | 92 | if !input.is_empty() { 93 | return Err(input.error("trailing tokens in macro input")); 94 | } 95 | 96 | Ok(Self { portrait, args, item_impl, debug_print: dpfo.value }) 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /codegen/src/fill.rs: -------------------------------------------------------------------------------- 1 | use heck::ToSnakeCase; 2 | use proc_macro2::TokenStream; 3 | use quote::{format_ident, quote}; 4 | use syn::parse::{Parse, ParseStream}; 5 | use syn::{Error, Result}; 6 | 7 | pub(crate) fn run(attr: TokenStream, item: TokenStream) -> Result { 8 | let Attr { debug_print, debug_print_filler_output, mod_path, attr_path, args: attr_args } = 9 | syn::parse2(attr)?; 10 | 11 | let item: syn::ItemImpl = syn::parse2(item)?; 12 | 13 | let target = match &item.trait_ { 14 | None => { 15 | return Err(Error::new_spanned( 16 | item.impl_token, 17 | "#[fill] can only be used on trait impl blocks", 18 | )) 19 | } 20 | Some((Some(bang), ..)) => { 21 | return Err(Error::new_spanned(bang, "#[fill] cannot be used on negated trait impl")) 22 | } 23 | Some((None, trait_path, _)) => trait_path, 24 | }; 25 | 26 | let mod_path = mod_path.unwrap_or_else(|| { 27 | // deduce the path to the portrait imports module based on the trait path 28 | let mut mod_path = target.clone(); 29 | let mod_name = mod_path.segments.last_mut().expect("path segments should be nonempty"); 30 | mod_name.ident = format_ident!("{}_portrait", mod_name.ident.to_string().to_snake_case()); 31 | mod_name.arguments = syn::PathArguments::None; 32 | mod_path 33 | }); 34 | 35 | let output = quote! { 36 | const _: () = { 37 | use #mod_path::imports::*; 38 | 39 | #target! { 40 | @TARGET {#attr_path} 41 | @ARGS {#attr_args} 42 | @IMPL {#item} 43 | @DEBUG_PRINT_FILLER_OUTPUT {#debug_print_filler_output} 44 | } 45 | }; 46 | }; 47 | 48 | if debug_print { 49 | println!("{output}"); 50 | } 51 | 52 | Ok(output) 53 | } 54 | 55 | mod kw { 56 | syn::custom_keyword!(MOD_PATH); 57 | syn::custom_keyword!(__DEBUG_PRINT); 58 | syn::custom_keyword!(DEBUG_PRINT_FILLER_OUTPUT); 59 | } 60 | 61 | struct Attr { 62 | debug_print: bool, 63 | debug_print_filler_output: bool, 64 | mod_path: Option, 65 | attr_path: syn::Path, 66 | args: Option, 67 | } 68 | 69 | impl Parse for Attr { 70 | fn parse(input: ParseStream) -> Result { 71 | let mut debug_print = false; 72 | let mut debug_print_filler_output = false; 73 | let mut mod_path = None; 74 | 75 | while input.peek(syn::Token![@]) { 76 | input.parse::().expect("peek result"); 77 | 78 | let lh = input.lookahead1(); 79 | if lh.peek(kw::__DEBUG_PRINT) { 80 | input.parse::().expect("peek result"); 81 | 82 | debug_print = true; 83 | } else if lh.peek(kw::DEBUG_PRINT_FILLER_OUTPUT) { 84 | input.parse::().expect("peek result"); 85 | 86 | debug_print_filler_output = true; 87 | } else if lh.peek(kw::MOD_PATH) { 88 | input.parse::().expect("peek result"); 89 | 90 | let inner; 91 | syn::parenthesized!(inner in input); 92 | mod_path = Some(inner.parse()?); 93 | } else { 94 | return Err(lh.error()); 95 | } 96 | } 97 | 98 | let path = input.parse()?; 99 | 100 | let mut args = None; 101 | if !input.is_empty() { 102 | let inner; 103 | syn::parenthesized!(inner in input); 104 | args = Some(inner.parse()?); 105 | } 106 | 107 | Ok(Self { debug_print, debug_print_filler_output, mod_path, attr_path: path, args }) 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /codegen/src/derive.rs: -------------------------------------------------------------------------------- 1 | use heck::ToSnakeCase; 2 | use proc_macro2::TokenStream; 3 | use quote::{format_ident, quote}; 4 | use syn::parse::{Parse, ParseStream}; 5 | use syn::Result; 6 | 7 | use crate::util; 8 | 9 | pub(crate) fn run(attr: TokenStream, item: TokenStream) -> Result { 10 | let Attr { 11 | debug_print, 12 | debug_print_filler_output, 13 | mod_path, 14 | trait_path, 15 | attr_path, 16 | args: attr_args, 17 | } = syn::parse2(attr)?; 18 | 19 | let item: syn::DeriveInput = syn::parse2(item)?; 20 | 21 | let mod_path = mod_path.unwrap_or_else(|| { 22 | // deduce the path to the portrait imports module based on the trait path 23 | let mut mod_path = trait_path.clone(); 24 | let mod_name = mod_path.segments.last_mut().expect("path segments should be nonempty"); 25 | mod_name.ident = format_ident!("{}_portrait", mod_name.ident.to_string().to_snake_case()); 26 | mod_name.arguments = syn::PathArguments::None; 27 | mod_path 28 | }); 29 | 30 | let item_stripped = util::strip_attr("portrait", &item, syn::visit_mut::visit_derive_input_mut); 31 | 32 | let output = quote! { 33 | #item_stripped 34 | 35 | const _: () = { 36 | use #mod_path::imports::*; 37 | 38 | #trait_path! { 39 | @TARGET {#attr_path} 40 | @TRAIT_PATH {#trait_path} 41 | @ARGS {#attr_args} 42 | @INPUT {#item} 43 | @DEBUG_PRINT_FILLER_OUTPUT {#debug_print_filler_output} 44 | } 45 | }; 46 | }; 47 | 48 | if debug_print { 49 | println!("{output}"); 50 | } 51 | 52 | Ok(output) 53 | } 54 | 55 | mod kw { 56 | syn::custom_keyword!(MOD_PATH); 57 | syn::custom_keyword!(__DEBUG_PRINT); 58 | syn::custom_keyword!(DEBUG_PRINT_FILLER_OUTPUT); 59 | syn::custom_keyword!(with); 60 | } 61 | 62 | struct Attr { 63 | debug_print: bool, 64 | debug_print_filler_output: bool, 65 | mod_path: Option, 66 | trait_path: syn::Path, 67 | attr_path: syn::Path, 68 | args: Option, 69 | } 70 | 71 | impl Parse for Attr { 72 | fn parse(input: ParseStream) -> Result { 73 | let mut debug_print = false; 74 | let mut debug_print_filler_output = false; 75 | let mut mod_path = None; 76 | 77 | while input.peek(syn::Token![@]) { 78 | input.parse::().expect("peek result"); 79 | 80 | let lh = input.lookahead1(); 81 | if lh.peek(kw::__DEBUG_PRINT) { 82 | input.parse::().expect("peek result"); 83 | 84 | debug_print = true; 85 | } else if lh.peek(kw::DEBUG_PRINT_FILLER_OUTPUT) { 86 | input.parse::().expect("peek result"); 87 | 88 | debug_print_filler_output = true; 89 | } else if lh.peek(kw::MOD_PATH) { 90 | input.parse::().expect("peek result"); 91 | 92 | let inner; 93 | syn::parenthesized!(inner in input); 94 | mod_path = Some(inner.parse()?); 95 | } else { 96 | return Err(lh.error()); 97 | } 98 | } 99 | 100 | let trait_path = input.parse()?; 101 | let _for_token: kw::with = input.parse()?; 102 | let attr_path = input.parse()?; 103 | 104 | let mut args = None; 105 | if !input.is_empty() { 106 | let inner; 107 | syn::parenthesized!(inner in input); 108 | args = Some(inner.parse()?); 109 | } 110 | 111 | Ok(Self { debug_print, debug_print_filler_output, mod_path, trait_path, attr_path, args }) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /framework/src/item_map.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use syn::{Error, Result}; 4 | 5 | /// Shorthand for `TraitItemMap::new().minus(ImplItemMap::new())`. 6 | pub fn subtract_items<'t>( 7 | trait_items: &'t [syn::TraitItem], 8 | impl_block: &'t syn::ItemImpl, 9 | ) -> syn::Result> { 10 | let mut items = TraitItemMap::new(trait_items); 11 | items.minus(&ImplItemMap::new(impl_block))?; 12 | Ok(items) 13 | } 14 | 15 | /// Indexes items in a trait by namespaced identifier. 16 | #[derive(Default)] 17 | pub struct TraitItemMap<'t> { 18 | /// Associated constants in the trait. 19 | pub consts: HashMap, 20 | /// Associated functions in the trait. 21 | pub fns: HashMap, 22 | /// Associated types in the trait. 23 | pub types: HashMap, 24 | } 25 | 26 | impl<'t> TraitItemMap<'t> { 27 | /// Constructs the trait item index from a slice of trait items. 28 | pub fn new(trait_items: &'t [syn::TraitItem]) -> Self { 29 | let mut map = Self::default(); 30 | for item in trait_items { 31 | match item { 32 | syn::TraitItem::Const(item) => { 33 | map.consts.insert(item.ident.clone(), item); 34 | } 35 | syn::TraitItem::Fn(item) => { 36 | map.fns.insert(item.sig.ident.clone(), item); 37 | } 38 | syn::TraitItem::Type(item) => { 39 | map.types.insert(item.ident.clone(), item); 40 | } 41 | _ => {} 42 | } 43 | } 44 | map 45 | } 46 | 47 | /// Removes the items found in the impl, leaving only unimplemented items. 48 | pub fn minus(&mut self, impl_items: &ImplItemMap) -> Result<()> { 49 | for (ident, impl_item) in &impl_items.consts { 50 | if self.consts.remove(ident).is_none() { 51 | return Err(Error::new_spanned( 52 | impl_item, 53 | "no associated constant called {ident} in trait", 54 | )); 55 | } 56 | } 57 | 58 | for (ident, impl_item) in &impl_items.fns { 59 | if self.fns.remove(ident).is_none() { 60 | return Err(Error::new_spanned( 61 | impl_item, 62 | "no associated function called {ident} in trait", 63 | )); 64 | } 65 | } 66 | 67 | for (ident, impl_item) in &impl_items.types { 68 | if self.types.remove(ident).is_none() { 69 | return Err(Error::new_spanned( 70 | impl_item, 71 | "no associated type called {ident} in trait", 72 | )); 73 | } 74 | } 75 | 76 | Ok(()) 77 | } 78 | } 79 | 80 | /// Indexes items in an impl block by namespaced identifier. 81 | #[derive(Default)] 82 | pub struct ImplItemMap<'t> { 83 | /// Associated constants in the implementation. 84 | pub consts: HashMap, 85 | /// Associated functions in the implementation. 86 | pub fns: HashMap, 87 | /// Associated types in the implementation. 88 | pub types: HashMap, 89 | } 90 | 91 | impl<'t> ImplItemMap<'t> { 92 | /// Constructs the impl item index from an impl block. 93 | pub fn new(impl_block: &'t syn::ItemImpl) -> Self { 94 | let mut map = Self::default(); 95 | for item in &impl_block.items { 96 | match item { 97 | syn::ImplItem::Const(item) => { 98 | map.consts.insert(item.ident.clone(), item); 99 | } 100 | syn::ImplItem::Fn(item) => { 101 | map.fns.insert(item.sig.ident.clone(), item); 102 | } 103 | syn::ImplItem::Type(item) => { 104 | map.types.insert(item.ident.clone(), item); 105 | } 106 | _ => {} 107 | } 108 | } 109 | map 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /framework/src/derive_filler.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use syn::parse::{Parse, ParseStream}; 3 | use syn::Result; 4 | 5 | /// Determines how to derive an impl. 6 | pub trait FillDerive { 7 | /// The arguments passed to the filler through macros. 8 | type Args: Parse; 9 | 10 | /// Derives the impl given a portrait of the trait items and the derived item. 11 | fn fill( 12 | self, 13 | trait_path: &syn::Path, 14 | portrait: &[syn::TraitItem], 15 | args: Self::Args, 16 | input: &syn::DeriveInput, 17 | ) -> Result; 18 | } 19 | 20 | /// Parses the macro input directly and passes them to the filler. 21 | /// 22 | /// Use this function if information of all implemented/unimplemented trait/impl items 23 | /// are required at the same time. 24 | /// If the filler just maps each unimplemented trait item to an impl item statelessly, 25 | /// use [`completer_derive_filler2`](crate::completer_derive_filler2)/[`proc_macro_derive_filler`](crate::proc_macro_derive_filler) for shorthand. 26 | pub fn derive_filler( 27 | input: TokenStream, 28 | filler: FillerT, 29 | ) -> Result { 30 | let Input:: { trait_path, portrait, args, input, debug_print } = 31 | syn::parse2(input)?; 32 | 33 | let output = filler.fill(&trait_path, &portrait, args, &input)?; 34 | 35 | if debug_print { 36 | println!("{output}"); 37 | } 38 | 39 | Ok(output) 40 | } 41 | 42 | mod kw { 43 | syn::custom_keyword!(TRAIT_PORTRAIT); 44 | syn::custom_keyword!(TRAIT_PATH); 45 | syn::custom_keyword!(ARGS); 46 | syn::custom_keyword!(INPUT); 47 | syn::custom_keyword!(DEBUG_PRINT_FILLER_OUTPUT); 48 | } 49 | 50 | pub(crate) struct Input { 51 | pub(crate) trait_path: syn::Path, 52 | pub(crate) portrait: Vec, 53 | pub(crate) args: ArgsT, 54 | pub(crate) input: syn::DeriveInput, 55 | pub(crate) debug_print: bool, 56 | } 57 | 58 | impl Parse for Input { 59 | fn parse(input: ParseStream) -> Result { 60 | input.parse::()?; 61 | 62 | let portrait_braced; 63 | syn::braced!(portrait_braced in input); 64 | let mut portrait = Vec::new(); 65 | while !portrait_braced.is_empty() { 66 | let item_braced; 67 | syn::braced!(item_braced in portrait_braced); 68 | let item: syn::TraitItem = item_braced.parse()?; 69 | if !item_braced.is_empty() { 70 | return Err(item_braced.error("braces should only contain one trait item")); 71 | } 72 | portrait.push(item); 73 | } 74 | 75 | input.parse::()?; 76 | let trait_path_braced; 77 | syn::braced!(trait_path_braced in input); 78 | let trait_path: syn::Path = trait_path_braced.parse()?; 79 | if !trait_path_braced.is_empty() { 80 | return Err(trait_path_braced.error("trait path not fully parsed")); 81 | } 82 | 83 | input.parse::()?; 84 | let args_braced; 85 | syn::braced!(args_braced in input); 86 | let args: ArgsT = args_braced.parse()?; 87 | if !args_braced.is_empty() { 88 | return Err(args_braced.error("args not fully parsed")); 89 | } 90 | 91 | input.parse::()?; 92 | let input_braced; 93 | syn::braced!(input_braced in input); 94 | let derive_input = input_braced.parse()?; 95 | if !input_braced.is_empty() { 96 | return Err(input_braced.error("trailing tokens after input block")); 97 | } 98 | 99 | input.parse::()?; 100 | let dpfo_braced; 101 | syn::braced!(dpfo_braced in input); 102 | let dpfo: syn::LitBool = dpfo_braced.parse()?; 103 | if !dpfo_braced.is_empty() { 104 | return Err(input_braced.error("trailing tokens after input block")); 105 | } 106 | 107 | if !input.is_empty() { 108 | return Err(input.error("trailing tokens in macro input")); 109 | } 110 | 111 | Ok(Self { trait_path, portrait, args, input: derive_input, debug_print: dpfo.value }) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /codegen/src/impl_fillers/log.rs: -------------------------------------------------------------------------------- 1 | use itertools::Itertools; 2 | use proc_macro2::{Span, TokenStream}; 3 | use quote::quote; 4 | use syn::parse::{Parse, ParseStream}; 5 | use syn::punctuated::Punctuated; 6 | use syn::spanned::Spanned; 7 | use syn::{Error, Result}; 8 | 9 | use crate::util::set_sig_arg_span; 10 | 11 | pub(crate) struct Generator(pub(crate) Arg); 12 | impl portrait_framework::GenerateImpl for Generator { 13 | fn generate_const( 14 | &mut self, 15 | _ctx: portrait_framework::ImplContext, 16 | item: &syn::TraitItemConst, 17 | ) -> syn::Result { 18 | Err(Error::new_spanned( 19 | item, 20 | "portrait::log cannot implement associated constants automatically", 21 | )) 22 | } 23 | 24 | fn generate_fn( 25 | &mut self, 26 | _ctx: portrait_framework::ImplContext, 27 | item: &syn::TraitItemFn, 28 | ) -> syn::Result { 29 | let Arg { logger, args: prefix_args, .. } = &mut self.0; 30 | 31 | if !prefix_args.empty_or_trailing() { 32 | prefix_args.push_punct(syn::Token![,](Span::call_site())); 33 | } 34 | 35 | let mut sig = item.sig.clone(); 36 | set_sig_arg_span(&mut sig, prefix_args.span())?; 37 | 38 | let mut fmt_args = Vec::new(); 39 | 40 | for param in sig.inputs.iter() { 41 | let (attrs, pat) = match param { 42 | syn::FnArg::Receiver(_) => continue, 43 | syn::FnArg::Typed(pat_ty) => (&pat_ty.attrs, &pat_ty.pat), 44 | }; 45 | 46 | let mut arg_expr = quote!(#pat); 47 | 48 | let cfg_attrs: Vec<_> = 49 | attrs.iter().filter(|attr| attr.path().is_ident("cfg")).collect(); 50 | if !cfg_attrs.is_empty() { 51 | let cfg_args = cfg_attrs 52 | .iter() 53 | .map(|attr| attr.parse_args::()) 54 | .collect::>>()?; 55 | 56 | arg_expr = quote! {{ 57 | #[cfg(all(#(#cfg_args),*))] { #arg_expr } 58 | #[cfg(not(all(#(#cfg_args),*)))] { ::portrait::DummyDebug("(cfg disabled)") } 59 | }}; 60 | } 61 | 62 | fmt_args.push(arg_expr); 63 | } 64 | 65 | let fmt_string = format!("{}({})", &sig.ident, fmt_args.iter().map(|_| "{:?}").join(", ")); 66 | 67 | Ok(syn::ImplItemFn { 68 | attrs: item.attrs.iter().filter(|attr| attr.path().is_ident("cfg")).cloned().collect(), 69 | vis: syn::Visibility::Inherited, 70 | defaultness: None, 71 | sig, 72 | block: syn::parse_quote! {{ 73 | #logger!(#prefix_args #fmt_string, #(#fmt_args),*) 74 | }}, 75 | }) 76 | } 77 | 78 | fn generate_type( 79 | &mut self, 80 | _ctx: portrait_framework::ImplContext, 81 | item: &syn::TraitItemType, 82 | ) -> syn::Result { 83 | let Arg { ret_ty, .. } = &self.0; 84 | 85 | let ty = match ret_ty { 86 | Some((_, ty)) => (**ty).clone(), 87 | None => syn::Type::Tuple(syn::TypeTuple { 88 | paren_token: syn::token::Paren(item.span()), 89 | elems: Punctuated::new(), 90 | }), 91 | }; 92 | 93 | Ok(syn::ImplItemType { 94 | attrs: item.attrs.iter().filter(|attr| attr.path().is_ident("cfg")).cloned().collect(), 95 | vis: syn::Visibility::Inherited, 96 | defaultness: None, 97 | type_token: item.type_token, 98 | ident: item.ident.clone(), 99 | generics: item.generics.clone(), 100 | eq_token: syn::Token![=](item.span()), 101 | ty, 102 | semi_token: item.semi_token, 103 | }) 104 | } 105 | } 106 | 107 | pub(crate) struct Arg { 108 | logger: syn::Path, 109 | ret_ty: Option<(syn::Token![->], Box)>, 110 | _comma_token: Option, 111 | args: Punctuated, 112 | } 113 | 114 | impl Parse for Arg { 115 | fn parse(input: ParseStream) -> syn::Result { 116 | let logger = input.parse()?; 117 | 118 | let ret_ty = if input.peek(syn::Token![->]) { 119 | let r_arrow = input.parse().expect("peeked"); 120 | let ty = input.parse()?; 121 | Some((r_arrow, Box::new(ty))) 122 | } else { 123 | None 124 | }; 125 | 126 | let mut comma_token: Option = None; 127 | let mut args = Punctuated::new(); 128 | if input.peek(syn::Token![,]) { 129 | comma_token = Some(input.parse().expect("peeked")); 130 | args = Punctuated::parse_terminated(input)?; 131 | } 132 | 133 | Ok(Self { logger, ret_ty, _comma_token: comma_token, args }) 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /framework/src/impl_completer.rs: -------------------------------------------------------------------------------- 1 | extern crate proc_macro; 2 | 3 | use proc_macro2::TokenStream; 4 | use quote::quote; 5 | use syn::parse::Parse; 6 | use syn::Result; 7 | 8 | use crate::{impl_filler, subtract_items, FillImpl}; 9 | 10 | /// One-line wrapper that declares a filler macro. 11 | /// 12 | /// # Example 13 | /// ``` 14 | /// # extern crate proc_macro; 15 | /// # 16 | /// portrait_framework::proc_macro_impl_filler!(foo, Generator); 17 | /// struct Generator(portrait_framework::NoArgs); 18 | /// impl portrait_framework::GenerateImpl for Generator { 19 | /// fn generate_const( 20 | /// &mut self, 21 | /// context: portrait_framework::ImplContext, 22 | /// item: &syn::TraitItemConst, 23 | /// ) -> syn::Result { 24 | /// todo!() 25 | /// } 26 | /// fn generate_fn( 27 | /// &mut self, 28 | /// context: portrait_framework::ImplContext, 29 | /// item: &syn::TraitItemFn, 30 | /// ) -> syn::Result { 31 | /// todo!() 32 | /// } 33 | /// fn generate_type( 34 | /// &mut self, 35 | /// context: portrait_framework::ImplContext, 36 | /// item: &syn::TraitItemType, 37 | /// ) -> syn::Result { 38 | /// todo!() 39 | /// } 40 | /// } 41 | /// ``` 42 | /// 43 | /// This declares a filler macro called `foo`, 44 | /// where each missing item is generated by calling the corresponding funciton. 45 | #[macro_export] 46 | macro_rules! proc_macro_impl_filler { 47 | ($ident:ident, $generator:path) => { 48 | pub fn $ident(input: ::proc_macro::TokenStream) -> ::proc_macro::TokenStream { 49 | portrait_framework::completer_impl_filler(input, $generator) 50 | } 51 | }; 52 | } 53 | 54 | /// Shorthand from [`fn@impl_filler`] to [`complete_impl`] ([`proc_macro`] version). 55 | pub fn completer_impl_filler( 56 | input: proc_macro::TokenStream, 57 | ctor: fn(ArgsT) -> GeneratorT, 58 | ) -> proc_macro::TokenStream { 59 | completer_impl_filler2(input.into(), ctor).unwrap_or_else(syn::Error::into_compile_error).into() 60 | } 61 | 62 | /// Shorthand from [`fn@impl_filler`] to [`complete_impl`] ([`proc_macro2`] version). 63 | pub fn completer_impl_filler2( 64 | input: TokenStream, 65 | ctor: fn(ArgsT) -> GeneratorT, 66 | ) -> Result { 67 | struct Filler(fn(ArgsT) -> GenerateT); 68 | 69 | impl FillImpl for Filler { 70 | type Args = ArgsT; 71 | 72 | fn fill( 73 | self, 74 | portrait: &[syn::TraitItem], 75 | args: Self::Args, 76 | item_impl: &syn::ItemImpl, 77 | ) -> Result { 78 | let tokens = complete_impl(portrait, item_impl, self.0(args))?; 79 | Ok(quote!(#tokens)) 80 | } 81 | } 82 | 83 | impl_filler(input, Filler(ctor)) 84 | } 85 | 86 | /// Invokes the generator on each unimplemented item 87 | /// and returns a clone of `impl_block` with the generated items. 88 | pub fn complete_impl( 89 | trait_items: &[syn::TraitItem], 90 | impl_block: &syn::ItemImpl, 91 | mut generator: impl GenerateImpl, 92 | ) -> syn::Result { 93 | let mut output = impl_block.clone(); 94 | 95 | let ctx = ImplContext { all_trait_items: trait_items, impl_block }; 96 | 97 | let items = subtract_items(trait_items, impl_block)?; 98 | for trait_item in items.consts.values() { 99 | let impl_item = generator.generate_const(ImplContext { ..ctx }, trait_item)?; 100 | output.items.push(syn::ImplItem::Const(impl_item)); 101 | } 102 | for trait_item in items.fns.values() { 103 | let impl_item = generator.generate_fn(ImplContext { ..ctx }, trait_item)?; 104 | output.items.push(syn::ImplItem::Fn(impl_item)); 105 | } 106 | for trait_item in items.types.values() { 107 | let impl_item = generator.generate_type(ImplContext { ..ctx }, trait_item)?; 108 | output.items.push(syn::ImplItem::Type(impl_item)); 109 | } 110 | 111 | Ok(output) 112 | } 113 | 114 | /// Available context parameters passed to generators. 115 | #[non_exhaustive] 116 | pub struct ImplContext<'t> { 117 | /// All known trait items in the portrait. 118 | pub all_trait_items: &'t [syn::TraitItem], 119 | /// The input impl block. 120 | pub impl_block: &'t syn::ItemImpl, 121 | } 122 | 123 | /// Generates missing items. 124 | pub trait GenerateImpl { 125 | /// Implements an associated constant. 126 | fn generate_const( 127 | &mut self, 128 | ctx: ImplContext, 129 | item: &syn::TraitItemConst, 130 | ) -> Result; 131 | 132 | /// Implements an associated function. 133 | fn generate_fn(&mut self, ctx: ImplContext, item: &syn::TraitItemFn) 134 | -> Result; 135 | 136 | /// Implements an associated type. 137 | fn generate_type( 138 | &mut self, 139 | ctx: ImplContext, 140 | item: &syn::TraitItemType, 141 | ) -> Result; 142 | } 143 | -------------------------------------------------------------------------------- /codegen/src/util.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] // due to disabled features 2 | 3 | use proc_macro2::{Span, TokenStream, TokenTree}; 4 | use quote::ToTokens; 5 | use syn::parse::{Parse, ParseStream, Parser}; 6 | use syn::Result; 7 | 8 | pub(crate) struct Once(pub(crate) Option<(Span, T)>); 9 | 10 | impl Default for Once { 11 | fn default() -> Self { Self(None) } 12 | } 13 | 14 | impl Once { 15 | pub(crate) fn set(&mut self, value: T, span: Span) -> Result<()> { 16 | if let Some((old_span, _)) = self.0.replace((span, value)) { 17 | return Err(syn::Error::new( 18 | Span::join(&span, old_span).unwrap_or(span), 19 | "Argument cannot be set twice", 20 | )); 21 | } 22 | Ok(()) 23 | } 24 | 25 | pub(crate) fn try_get(self) -> Option { self.0.map(|(_, t)| t) } 26 | 27 | pub(crate) fn get_or(self, f: impl FnOnce() -> T) -> T { self.try_get().unwrap_or_else(f) } 28 | } 29 | 30 | pub(crate) trait ParseArgs: Default { 31 | fn parse_once(&mut self, input: ParseStream) -> Result<()>; 32 | } 33 | 34 | pub(crate) struct Args(pub(crate) T); 35 | impl Parse for Args { 36 | fn parse(input: ParseStream) -> Result { 37 | let mut args = T::default(); 38 | 39 | parse_args(input, &mut args)?; 40 | 41 | Ok(Self(args)) 42 | } 43 | } 44 | 45 | fn parse_args(input: ParseStream, args: &mut impl ParseArgs) -> Result<()> { 46 | while !input.is_empty() { 47 | args.parse_once(input)?; 48 | 49 | if let Err(err) = input.parse::() { 50 | if !input.is_empty() { 51 | return Err(err); 52 | } 53 | } 54 | } 55 | 56 | Ok(()) 57 | } 58 | 59 | pub(crate) fn set_sig_arg_span(sig: &mut syn::Signature, span: Span) -> Result<()> { 60 | for input in &mut sig.inputs { 61 | match input { 62 | syn::FnArg::Receiver(receiver) => { 63 | receiver.self_token.span = span; 64 | } 65 | syn::FnArg::Typed(pat_ty) => { 66 | let pat = &mut *pat_ty.pat; 67 | *pat = copy_with_span(pat, syn::Pat::parse_multi, span)?; 68 | } 69 | } 70 | } 71 | 72 | Ok(()) 73 | } 74 | 75 | fn copy_with_span>(t: &T, parser: P, span: Span) -> Result { 76 | let mut ts = t.to_token_stream(); 77 | ts = copy_ts_with_span(ts, span); 78 | parser.parse2(ts) 79 | } 80 | 81 | fn copy_ts_with_span(ts: TokenStream, span: Span) -> TokenStream { 82 | ts.into_iter() 83 | .map(|mut tt| { 84 | if let TokenTree::Group(group) = tt { 85 | let group_ts = copy_ts_with_span(group.stream(), span); 86 | tt = TokenTree::Group(proc_macro2::Group::new(group.delimiter(), group_ts)); 87 | } 88 | tt.set_span(span); 89 | tt 90 | }) 91 | .collect() 92 | } 93 | 94 | pub(crate) fn parse_grouped_attr( 95 | attrs: &[syn::Attribute], 96 | group_name: &str, 97 | ) -> Result { 98 | let mut args = T::default(); 99 | 100 | for attr in attrs { 101 | if attr.path().is_ident("portrait") { 102 | attr.parse_args_with(|input: ParseStream| { 103 | loop { 104 | let ident = input.parse::()?; 105 | if ident == group_name { 106 | let inner; 107 | syn::parenthesized!(inner in input); 108 | 109 | parse_args(&inner, &mut args)?; 110 | } else { 111 | // skip group 112 | 113 | if input.peek(syn::Token![=]) { 114 | let _: syn::Token![=] = input.parse()?; 115 | let _: syn::Expr = input.parse()?; 116 | } else if input.peek(syn::token::Paren) { 117 | let _inner; 118 | syn::parenthesized!(_inner in input); 119 | } 120 | } 121 | 122 | if input.peek(syn::Token![,]) { 123 | let _: syn::Token![,] = input.parse()?; 124 | 125 | if input.is_empty() { 126 | break; 127 | } 128 | } else { 129 | if !input.is_empty() { 130 | return Err(input.error("trailing tokens")); 131 | } 132 | break; 133 | } 134 | } 135 | 136 | Ok(()) 137 | })?; 138 | } 139 | } 140 | 141 | Ok(args) 142 | } 143 | 144 | pub(crate) struct StripAttrVisitor { 145 | ident: &'static str, 146 | } 147 | impl syn::visit_mut::VisitMut for StripAttrVisitor { 148 | fn visit_attribute_mut(&mut self, attr: &mut syn::Attribute) { 149 | if attr.path().is_ident(self.ident) { 150 | attr.meta = syn::parse_quote! { 151 | cfg(all()) // universal quantification over empty set is always true 152 | }; 153 | } 154 | } 155 | } 156 | 157 | pub(crate) fn strip_attr( 158 | ident: &'static str, 159 | item: &T, 160 | visit_mut: fn(&mut StripAttrVisitor, &mut T), 161 | ) -> T { 162 | let mut item_stripped = item.clone(); 163 | let mut visitor = StripAttrVisitor { ident }; 164 | visit_mut(&mut visitor, &mut item_stripped); 165 | item_stripped 166 | } 167 | -------------------------------------------------------------------------------- /codegen/src/make.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashSet; 2 | 3 | use heck::ToSnakeCase; 4 | use proc_macro2::TokenStream; 5 | use quote::{format_ident, quote, quote_spanned, ToTokens}; 6 | use syn::parse::{Parse, ParseStream}; 7 | use syn::spanned::Spanned; 8 | use syn::visit::{visit_path, Visit}; 9 | use syn::{parenthesized, Result}; 10 | 11 | use crate::util; 12 | use crate::util::{Once, ParseArgs}; 13 | 14 | pub(crate) fn run(attr: TokenStream, item: TokenStream) -> Result { 15 | let item = syn::parse2::(item)?; 16 | let vis = &item.vis; 17 | let unstripped_trait_items = item.items.clone(); 18 | 19 | let item_ident = &item.ident; 20 | 21 | let util::Args(ItemArgs { debug_print, name: mod_name, imports, auto_imports }) = 22 | syn::parse2::>(attr)?; 23 | let mod_name = 24 | mod_name.get_or(|| format_ident!("{}_portrait", item.ident.to_string().to_snake_case())); 25 | 26 | let mut imports: Vec<_> = imports.into_iter().map(ToTokens::into_token_stream).collect(); 27 | if auto_imports.get_or(|| false) { 28 | let mut import_collector = ImportCollector::default(); 29 | for trait_item in &item.items { 30 | import_collector.visit_trait_item(trait_item) 31 | } 32 | 33 | imports.extend(import_collector.idents.iter().map(|ident| quote!(super::super::#ident))); 34 | } 35 | 36 | let pub_export = match vis { 37 | syn::Visibility::Public(_) => quote! { 38 | #[doc(hidden)] 39 | #[macro_export] 40 | }, 41 | _ => quote!(), 42 | }; 43 | // random name required because macro may be exported despite unused 44 | let macro_random_name = format_ident!("portrait_items_{:x}", rand::random::()); 45 | 46 | let import_vis = match vis { 47 | syn::Visibility::Inherited => quote_spanned!(vis.span() => pub(in super::super)), 48 | syn::Visibility::Public(_) => quote!(#vis), 49 | syn::Visibility::Restricted(restricted) => { 50 | match restricted.in_token { 51 | None if restricted.path.is_ident("self") => { 52 | quote_spanned!(vis.span() => pub(in super::super)) 53 | } 54 | None if restricted.path.is_ident("super") => { 55 | quote_spanned!(vis.span() => pub(in super::super::super)) 56 | } 57 | None if restricted.path.is_ident("crate") => quote!(#vis), 58 | None => return Err(syn::Error::new_spanned(vis, "invalid visibility scope")), 59 | Some(_) => quote!(#vis), // absolute path 60 | } 61 | } 62 | }; 63 | 64 | let item_stripped = util::strip_attr("portrait", &item, syn::visit_mut::visit_item_trait_mut); 65 | 66 | let output = quote! { 67 | #item_stripped 68 | 69 | #pub_export 70 | macro_rules! #macro_random_name { 71 | ( 72 | @TARGET {$target_macro:path} 73 | $( 74 | @$arg_key:ident { $($arg_value:tt)* } 75 | )* 76 | ) => { 77 | $target_macro! { 78 | TRAIT_PORTRAIT { #({#unstripped_trait_items})* } 79 | $( 80 | $arg_key { $($arg_value)* } 81 | )* 82 | } 83 | } 84 | } 85 | 86 | #[allow(non_snake_case)] 87 | #vis use #macro_random_name as #item_ident; 88 | 89 | #[allow(non_snake_case)] 90 | #vis mod #mod_name { 91 | pub mod imports { 92 | #(#import_vis use #imports;)* 93 | } 94 | } 95 | }; 96 | if debug_print.get_or(|| false) { 97 | println!("{output}"); 98 | } 99 | Ok(output) 100 | } 101 | 102 | #[derive(Default)] 103 | struct ItemArgs { 104 | debug_print: Once, 105 | name: Once, 106 | imports: Vec, 107 | auto_imports: Once, 108 | } 109 | 110 | mod kw { 111 | syn::custom_keyword!(__debug_print); 112 | syn::custom_keyword!(name); 113 | syn::custom_keyword!(import); 114 | syn::custom_keyword!(auto_imports); 115 | } 116 | 117 | impl ParseArgs for ItemArgs { 118 | fn parse_once(&mut self, input: ParseStream) -> Result<()> { 119 | let lh = input.lookahead1(); 120 | if lh.peek(kw::__debug_print) { 121 | let key = input.parse::()?; 122 | self.debug_print.set(true, key.span())?; 123 | } else if lh.peek(kw::name) { 124 | let key = input.parse::()?; 125 | _ = input.parse::()?; 126 | self.name.set(input.parse()?, key.span())?; 127 | } else if lh.peek(kw::import) { 128 | _ = input.parse::()?; 129 | let inner; 130 | _ = parenthesized!(inner in input); 131 | let imports = inner.parse_terminated(syn::UseTree::parse, syn::Token![,])?; 132 | self.imports.extend(imports); 133 | } else if lh.peek(kw::auto_imports) { 134 | let key = input.parse::()?; 135 | self.debug_print.set(true, key.span())?; 136 | } else { 137 | return Err(lh.error()); 138 | } 139 | Ok(()) 140 | } 141 | } 142 | 143 | #[derive(Default)] 144 | struct ImportCollector { 145 | idents: HashSet, 146 | } 147 | 148 | impl<'ast> Visit<'ast> for ImportCollector { 149 | fn visit_path(&mut self, path: &'ast syn::Path) { 150 | if path.leading_colon.is_none() { 151 | let segment = path.segments.first().expect("path segments should be nonempty"); 152 | self.idents.insert(segment.ident.clone()); 153 | } 154 | 155 | visit_path(self, path) 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # portrait 2 | 3 | [![GitHub actions](https://github.com/SOF3/portrait/workflows/CI/badge.svg)](https://github.com/SOF3/portrait/actions?query=workflow%3ACI) 4 | [![crates.io](https://img.shields.io/crates/v/portrait.svg)](https://crates.io/crates/portrait) 5 | [![crates.io](https://img.shields.io/crates/d/portrait.svg)](https://crates.io/crates/portrait) 6 | [![docs.rs](https://docs.rs/portrait/badge.svg)](https://docs.rs/portrait) 7 | [![GitHub](https://img.shields.io/github/last-commit/SOF3/portrait)](https://github.com/SOF3/portrait) 8 | [![GitHub](https://img.shields.io/github/stars/SOF3/portrait?style=social)](https://github.com/SOF3/portrait) 9 | 10 | Fill impl-trait blocks with default, delegation and more. 11 | 12 | ## Motivation 13 | 14 | Rust traits support provided methods, 15 | which are great for backwards compatibility and implementation coding efficiency. 16 | However they come with some limitations: 17 | 18 | - There is no reasonable way to implement an associated function 19 | if its return type is an associated type. 20 | - If a trait contains many highly similar associated functions, 21 | writing the defaults involves a lot of boilerplate. 22 | But users can only provide one default implementation for each method 23 | through procedural macros. 24 | 25 | With `portrait`, the default implementations are provided 26 | at `impl`-level granularity instead of trait-level. 27 | 28 | ## Usage 29 | 30 | First of all, make a portrait of the trait to implement 31 | with the `#[portrait::make]` attribute: 32 | 33 | ```rs 34 | #[portrait::make] 35 | trait FooBar { 36 | // ... 37 | } 38 | ``` 39 | 40 | Implement the trait partially and leave the rest to the `#[portrait::fill]` attribute: 41 | 42 | ```rs 43 | #[portrait::fill(portrait::default)] 44 | impl FooBar {} 45 | ``` 46 | 47 | The `portrait::default` part is the path to the "filler macro", 48 | which is the item that actually fills the `impl` block. 49 | The syntax is similar to `#[derive(path::to::Macro)]`. 50 | 51 | If there are implementations in a different module, 52 | the imports used in trait items need to be manually passed to the make attribute: 53 | 54 | ```rs 55 | #[portrait::make(import( 56 | foo, bar::*, 57 | // same syntax as use statements 58 | ))] 59 | trait FooBar {...} 60 | ``` 61 | 62 | If the fill attribute fails with an error about undefined `foo_bar_portrait`, 63 | import it manually together with the FooBar trait; 64 | the `#[portrait::make]` attribute generates this new module 65 | in the same module as the `FooBar` trait. 66 | 67 | ## Provided fillers 68 | 69 | `portrait` provides the following filler macros: 70 | 71 | - `default`: 72 | Implements each missing method and constant by delegating to `Default::default()` 73 | (`Default` is const-unstable and requires nightly with `#![feature(const_default_impls)]`). 74 | - `delegate`: 75 | Proxies each missing method, constant and type 76 | to an expression (usually `self.field`) or another type implementing the same trait. 77 | - `log`: 78 | Calls a `format!`-like macro with the method arguments. 79 | 80 | ## How this works 81 | 82 | Rust macros are invoked at an early stage of the compilation chain. 83 | As a result, attribute macros only have access to the literal representation 84 | of the item they are applied on, 85 | and cross-item derivation is not directly possible. 86 | Most macros evade this problem by trying to generate code 87 | that works regardless of the inaccessible information, 88 | e.g. the `Default` derive macro works by invoking `Default::default()` 89 | without checking whether the actual field type actually implements `Default` 90 | (since the compiler would do at a later stage anyway). 91 | 92 | Unfortunately this approach does not work in the use case of `portrait`, 93 | where the attribute macro requires compile time (procedural macro runtime) access 94 | to the items of the trait referenced in the `impl` block; 95 | the only available information is the path to the trait 96 | (which could even be renamed to a different identifier). 97 | 98 | `portrait` addresses this challenge by 99 | asking the trait to export its information (its "portrait") 100 | in the form of a token stream in advance. 101 | Through the `#[portrait::make]` attribute, 102 | a *declarative* macro with the same identifier is derived, 103 | containing the trait items. 104 | The (`#[portrait::fill]`) attribute on the `impl` block 105 | then passes its inputs to the declarative macro, 106 | which in turn forwards them to the actual attribute implementation 107 | (e.g. `#[portrait::make]`) along with the trait items. 108 | 109 | Now the actual attribute has access to both the trait items and the user impl, 110 | but that's not quite yet the end of story. 111 | The trait items are written in the scope of the trait definition, 112 | but the attribute macro output is in the scope of the impl definition. 113 | The most apparent effect is that 114 | imports in the trait module do not take effect on the impl output. 115 | To avoid updating implementors frequently due to changes in the trait module, 116 | the `#[portrait::make]` attribute also derives a module 117 | that contains the imports used in the trait 118 | to be automatically imported in the impl block. 119 | 120 | It turns out that, as of current compiler limitations, 121 | private imports actually cannot be re-exported publicly 122 | even though the imported type is public, 123 | so it becomes impractical to scan the trait item automatically for paths to re-export 124 | (prelude types also need special treatment since they are not part of the module). 125 | The problem of heterogeneous scope thus becomes exposed to users inevitably: 126 | either type all required re-exports manually through import, 127 | or make the imports visible to a further scope. 128 | 129 | Another difficulty is that 130 | module identifiers share the same symbol space as trait identifiers 131 | (because `module::Foo` is indistinguishable from `Trait::Foo`). 132 | Thus, the module containing the imports cannot be imported together with the trait, 133 | and users have to manually import/export both symbols 134 | unless the trait is referenced through its enclosing module. 135 | 136 | ## Disclaimer 137 | 138 | `portrait` is not the first one to use declarative macros in attributes. 139 | [`macro_rules_attribute`][macro_rules_attribute] also implements a similar idea, 140 | although without involving the framework of generating the `macro_rules!` part. 141 | 142 | [macro_rules_attribute]: https://docs.rs/macro_rules_attribute/ 143 | -------------------------------------------------------------------------------- /codegen/src/impl_fillers/delegate.rs: -------------------------------------------------------------------------------- 1 | use std::iter; 2 | 3 | use proc_macro2::Span; 4 | use quote::{quote, ToTokens}; 5 | use syn::parse::{Parse, ParseStream}; 6 | use syn::spanned::Spanned; 7 | 8 | use crate::util::set_sig_arg_span; 9 | 10 | pub(crate) struct Generator(pub(crate) Arg); 11 | impl portrait_framework::GenerateImpl for Generator { 12 | fn generate_const( 13 | &mut self, 14 | ctx: portrait_framework::ImplContext, 15 | item: &syn::TraitItemConst, 16 | ) -> syn::Result { 17 | let Arg { ty: delegate_ty, .. } = &self.0; 18 | let trait_path = &ctx.impl_block.trait_.as_ref().expect("checked in framework").1; 19 | let item_ident = &item.ident; 20 | let expr = syn::parse_quote!(<#delegate_ty as #trait_path>::#item_ident); 21 | Ok(syn::ImplItemConst { 22 | attrs: item.attrs.iter().filter(|attr| attr.path().is_ident("cfg")).cloned().collect(), 23 | vis: syn::Visibility::Inherited, 24 | defaultness: None, 25 | const_token: item.const_token, 26 | ident: item.ident.clone(), 27 | generics: item.generics.clone(), 28 | colon_token: item.colon_token, 29 | ty: item.ty.clone(), 30 | eq_token: syn::Token![=](item.span()), 31 | expr, 32 | semi_token: item.semi_token, 33 | }) 34 | } 35 | 36 | fn generate_fn( 37 | &mut self, 38 | ctx: portrait_framework::ImplContext, 39 | item: &syn::TraitItemFn, 40 | ) -> syn::Result { 41 | let Arg { ty: delegate_ty, value: delegate_value } = &self.0; 42 | let trait_path = &ctx.impl_block.trait_.as_ref().expect("checked in framework").1; 43 | 44 | let mut sig = item.sig.clone(); 45 | 46 | if let Some(delegate_expr) = delegate_value { 47 | set_sig_arg_span(&mut sig, delegate_expr.expr.span())?; 48 | } 49 | let sig_ident = sig.ident.clone(); 50 | 51 | let args = sig 52 | .inputs 53 | .iter_mut() 54 | .map(|fn_arg| match fn_arg { 55 | syn::FnArg::Receiver(receiver) => { 56 | let arg_attrs: Vec<_> = receiver 57 | .attrs 58 | .iter() 59 | .filter(|attr| attr.path().is_ident("cfg")) 60 | .cloned() 61 | .collect(); 62 | let ref_ = if let Some((and, _lifetime)) = &receiver.reference { 63 | Some(quote!(#and)) 64 | } else { 65 | None 66 | }; 67 | let mut_ = receiver.mutability; 68 | 69 | let delegate_expr = &delegate_value 70 | .as_ref() 71 | .ok_or_else(|| { 72 | syn::Error::new_spanned( 73 | &receiver, 74 | "Delegate value must be passed to implement traits with references", 75 | ) 76 | })? 77 | .expr; 78 | 79 | Ok(quote! { #(#arg_attrs)* #ref_ #mut_ #delegate_expr }) 80 | } 81 | syn::FnArg::Typed(typed) => { 82 | let arg_attrs: Vec<_> = typed 83 | .attrs 84 | .iter() 85 | .filter(|attr| attr.path().is_ident("cfg")) 86 | .cloned() 87 | .collect(); 88 | if let syn::Pat::Ident(pat) = &mut *typed.pat { 89 | if pat.ident == "self" { 90 | // Note: this syntax only works if delegate_expr returns exactly the receiver type. 91 | let delegate_expr = &delegate_value 92 | .as_ref() 93 | .ok_or_else(|| { 94 | syn::Error::new_spanned( 95 | typed, 96 | "Delegate value must be passed to implement traits with \ 97 | references", 98 | ) 99 | })? 100 | .expr; 101 | return Ok(quote! { #(#arg_attrs)* #delegate_expr }); 102 | } else { 103 | // Suppress `mut` when passing arguments. 104 | pat.mutability = None; 105 | } 106 | } 107 | 108 | let pat = &typed.pat; 109 | Ok(quote! { #(#arg_attrs)* #pat }) 110 | } 111 | }) 112 | .collect::>>()?; 113 | 114 | let inline_attr = syn::Attribute { 115 | pound_token: syn::Token![#](Span::call_site()), 116 | style: syn::AttrStyle::Outer, 117 | bracket_token: syn::token::Bracket(Span::call_site()), 118 | meta: syn::Meta::Path(syn::parse_quote!(inline)), 119 | }; 120 | 121 | Ok(syn::ImplItemFn { 122 | attrs: item 123 | .attrs 124 | .iter() 125 | .filter(|attr| attr.path().is_ident("cfg")) 126 | .cloned() 127 | .chain(iter::once(inline_attr)) 128 | .collect(), 129 | vis: syn::Visibility::Inherited, 130 | defaultness: None, 131 | sig, 132 | block: syn::parse_quote! {{ 133 | <#delegate_ty as #trait_path>::#sig_ident(#(#args,)*) 134 | }}, 135 | }) 136 | } 137 | 138 | fn generate_type( 139 | &mut self, 140 | ctx: portrait_framework::ImplContext, 141 | item: &syn::TraitItemType, 142 | ) -> syn::Result { 143 | let Arg { ty: delegate_ty, .. } = &self.0; 144 | let trait_path = &ctx.impl_block.trait_.as_ref().expect("checked in framework").1; 145 | let item_ident = &item.ident; 146 | let generics_unbound: Vec<_> = item 147 | .generics 148 | .params 149 | .iter() 150 | .map(|param| match param { 151 | syn::GenericParam::Type(ty) => ty.ident.to_token_stream(), 152 | syn::GenericParam::Lifetime(lt) => lt.lifetime.to_token_stream(), 153 | syn::GenericParam::Const(const_) => const_.ident.to_token_stream(), 154 | }) 155 | .collect(); 156 | let generics_unbound = 157 | (!generics_unbound.is_empty()).then(|| quote!(< #(#generics_unbound),* >)); 158 | let ty = syn::parse_quote!(<#delegate_ty as #trait_path>::#item_ident #generics_unbound); 159 | Ok(syn::ImplItemType { 160 | attrs: item.attrs.iter().filter(|attr| attr.path().is_ident("cfg")).cloned().collect(), 161 | vis: syn::Visibility::Inherited, 162 | defaultness: None, 163 | type_token: item.type_token, 164 | ident: item.ident.clone(), 165 | generics: item.generics.clone(), 166 | eq_token: syn::Token![=](item.span()), 167 | ty, 168 | semi_token: item.semi_token, 169 | }) 170 | } 171 | } 172 | 173 | pub(crate) struct Arg { 174 | ty: syn::Type, 175 | value: Option, 176 | } 177 | struct ArgValue { 178 | _semi_token: syn::Token![;], 179 | expr: syn::Expr, 180 | } 181 | 182 | impl Parse for Arg { 183 | fn parse(input: ParseStream) -> syn::Result { 184 | let ty = input.parse()?; 185 | let value = if input.peek(syn::Token![;]) { 186 | let semi_token = input.parse().expect("peeked"); 187 | let expr = input.parse()?; 188 | Some(ArgValue { _semi_token: semi_token, expr }) 189 | } else { 190 | None 191 | }; 192 | 193 | Ok(Self { ty, value }) 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /framework/src/derive_completer.rs: -------------------------------------------------------------------------------- 1 | extern crate proc_macro; 2 | 3 | use proc_macro2::{Span, TokenStream}; 4 | use quote::{quote, ToTokens}; 5 | use syn::parse::Parse; 6 | use syn::spanned::Spanned; 7 | use syn::Result; 8 | 9 | use crate::{derive_filler, FillDerive}; 10 | 11 | /// One-line wrapper that declares a filler macro. 12 | /// 13 | /// # Example 14 | /// ``` 15 | /// # extern crate proc_macro; 16 | /// # 17 | /// portrait_framework::proc_macro_derive_filler!(foo, Generator); 18 | /// struct Generator(portrait_framework::NoArgs); 19 | /// impl portrait_framework::GenerateDerive for Generator { 20 | /// fn generate_const( 21 | /// &mut self, 22 | /// context: portrait_framework::DeriveContext, 23 | /// item: &syn::TraitItemConst, 24 | /// ) -> syn::Result { 25 | /// todo!() 26 | /// } 27 | /// fn generate_fn( 28 | /// &mut self, 29 | /// context: portrait_framework::DeriveContext, 30 | /// item: &syn::TraitItemFn, 31 | /// ) -> syn::Result { 32 | /// todo!() 33 | /// } 34 | /// fn generate_type( 35 | /// &mut self, 36 | /// context: portrait_framework::DeriveContext, 37 | /// item: &syn::TraitItemType, 38 | /// ) -> syn::Result { 39 | /// todo!() 40 | /// } 41 | /// } 42 | /// ``` 43 | /// 44 | /// This declares a filler macro called `foo`, 45 | /// where each missing item is generated by calling the corresponding funciton. 46 | #[macro_export] 47 | macro_rules! proc_macro_derive_filler { 48 | ($ident:ident, $generator:path) => { 49 | pub fn $ident(input: ::proc_macro::TokenStream) -> ::proc_macro::TokenStream { 50 | portrait_framework::completer_derive_filler(input, $generator) 51 | } 52 | }; 53 | } 54 | 55 | /// Shorthand from [`fn@derive_filler`] to [`complete_derive`] ([`proc_macro`] version). 56 | pub fn completer_derive_filler( 57 | input: proc_macro::TokenStream, 58 | ctor: fn(ArgsT) -> GeneratorT, 59 | ) -> proc_macro::TokenStream { 60 | completer_derive_filler2(input.into(), ctor) 61 | .unwrap_or_else(syn::Error::into_compile_error) 62 | .into() 63 | } 64 | 65 | /// Shorthand from [`fn@derive_filler`] to [`complete_derive`] ([`proc_macro2`] version). 66 | pub fn completer_derive_filler2( 67 | input: TokenStream, 68 | ctor: fn(ArgsT) -> GeneratorT, 69 | ) -> Result { 70 | struct Filler(fn(ArgsT) -> GenerateT); 71 | 72 | impl FillDerive for Filler { 73 | type Args = ArgsT; 74 | 75 | fn fill( 76 | self, 77 | trait_path: &syn::Path, 78 | portrait: &[syn::TraitItem], 79 | args: Self::Args, 80 | input: &syn::DeriveInput, 81 | ) -> Result { 82 | let tokens = complete_derive(trait_path, portrait, input, self.0(args))?; 83 | Ok(quote!(#tokens)) 84 | } 85 | } 86 | 87 | derive_filler(input, Filler(ctor)) 88 | } 89 | 90 | /// Invokes the generator on each unimplemented item 91 | /// and returns a clone of `impl_block` with the generated items. 92 | pub fn complete_derive( 93 | trait_path: &syn::Path, 94 | trait_items: &[syn::TraitItem], 95 | input: &syn::DeriveInput, 96 | mut generator: impl GenerateDerive, 97 | ) -> syn::Result { 98 | let ctx = DeriveContext { trait_path, all_trait_items: trait_items, input }; 99 | 100 | let mut generics_params: Vec<_> = input.generics.params.iter().cloned().collect(); 101 | let mut generics_where: Vec<_> = input 102 | .generics 103 | .where_clause 104 | .iter() 105 | .flat_map(|clause| clause.predicates.iter().cloned()) 106 | .collect(); 107 | // TODO generic trait support (this behavior may be filler-dependent) 108 | generator.extend_generics( 109 | DeriveContext { ..ctx }, 110 | &mut generics_params, 111 | &mut generics_where, 112 | )?; 113 | 114 | let self_ty = syn::Type::Path({ 115 | let input_ident = &input.ident; 116 | let self_generics = (!input.generics.params.is_empty()).then(|| { 117 | let type_param_names = input.generics.params.iter().map(|param| match param { 118 | syn::GenericParam::Lifetime(lt) => lt.lifetime.to_token_stream(), 119 | syn::GenericParam::Type(ty) => ty.ident.to_token_stream(), 120 | syn::GenericParam::Const(const_) => const_.ident.to_token_stream(), 121 | }); 122 | 123 | quote!(<#(#type_param_names),*>) 124 | }); 125 | 126 | syn::parse_quote!(#input_ident #self_generics) 127 | }); 128 | 129 | let mut items = Vec::new(); 130 | for trait_item in trait_items { 131 | let item = match trait_item { 132 | syn::TraitItem::Const(const_item) => { 133 | syn::ImplItem::Const(generator.generate_const(DeriveContext { ..ctx }, const_item)?) 134 | } 135 | syn::TraitItem::Fn(fn_item) => { 136 | syn::ImplItem::Fn(generator.generate_fn(DeriveContext { ..ctx }, fn_item)?) 137 | } 138 | syn::TraitItem::Type(type_item) => { 139 | syn::ImplItem::Type(generator.generate_type(DeriveContext { ..ctx }, type_item)?) 140 | } 141 | _ => continue, // assume other tokens do not generate an item 142 | }; 143 | items.push(item); 144 | } 145 | 146 | let mut attrs: Vec<_> = 147 | input.attrs.iter().filter(|attr| attr.path().is_ident("cfg")).cloned().collect(); 148 | generator.extend_attrs(DeriveContext { ..ctx }, &mut attrs)?; 149 | 150 | Ok(syn::ItemImpl { 151 | attrs, 152 | defaultness: None, 153 | unsafety: None, // TODO support explicit unsafe derive 154 | impl_token: syn::Token![impl](Span::call_site()), 155 | generics: syn::Generics { 156 | lt_token: (!generics_params.is_empty()) 157 | .then(|| syn::Token![<](input.generics.span())), 158 | gt_token: (!generics_params.is_empty()) 159 | .then(|| syn::Token![>](input.generics.span())), 160 | params: generics_params.into_iter().collect(), 161 | where_clause: (!generics_where.is_empty()).then(|| syn::WhereClause { 162 | where_token: syn::Token![where](Span::call_site()), 163 | predicates: generics_where.into_iter().collect(), 164 | }), 165 | }, 166 | trait_: Some((None, trait_path.clone(), syn::Token![for](Span::call_site()))), 167 | self_ty: Box::new(self_ty), 168 | brace_token: syn::token::Brace::default(), 169 | items, 170 | }) 171 | } 172 | 173 | /// Available context parameters passed to generators. 174 | #[non_exhaustive] 175 | pub struct DeriveContext<'t> { 176 | /// The path to reference the implemented trait. 177 | pub trait_path: &'t syn::Path, 178 | /// All known trait items in the portrait. 179 | pub all_trait_items: &'t [syn::TraitItem], 180 | /// The input struct/enum/union. 181 | pub input: &'t syn::DeriveInput, 182 | } 183 | 184 | /// Generates missing items. 185 | pub trait GenerateDerive { 186 | /// Implements an associated constant. 187 | fn generate_const( 188 | &mut self, 189 | ctx: DeriveContext, 190 | item: &syn::TraitItemConst, 191 | ) -> Result; 192 | 193 | /// Implements an associated function. 194 | fn generate_fn( 195 | &mut self, 196 | ctx: DeriveContext, 197 | item: &syn::TraitItemFn, 198 | ) -> Result; 199 | 200 | /// Implements an associated type. 201 | fn generate_type( 202 | &mut self, 203 | ctx: DeriveContext, 204 | item: &syn::TraitItemType, 205 | ) -> Result; 206 | 207 | /// Provides additional type bounds for the `impl` block. 208 | fn extend_generics( 209 | &mut self, 210 | _ctx: DeriveContext, 211 | _generics_params: &mut Vec, 212 | _generics_where: &mut Vec, 213 | ) -> Result<()> { 214 | Ok(()) 215 | } 216 | 217 | /// Provides additional attributes for the `impl` block. 218 | fn extend_attrs( 219 | &mut self, 220 | _ctx: DeriveContext, 221 | _attrs: &mut Vec, 222 | ) -> Result<()> { 223 | Ok(()) 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | 41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 42 | 43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Fill impl-trait blocks with default, delegation and more. 2 | //! 3 | //! ## Motivation 4 | //! 5 | //! Rust traits support provided methods, 6 | //! which are great for backwards compatibility and implementation coding efficiency. 7 | //! However they come with some limitations: 8 | //! 9 | //! - There is no reasonable way to implement an associated function 10 | //! if its return type is an associated type. 11 | //! - If a trait contains many highly similar associated functions, 12 | //! writing the defaults involves a lot of boilerplate. 13 | //! But users can only provide one default implementation for each method 14 | //! through procedural macros. 15 | //! 16 | //! With `portrait`, the default implementations are provided 17 | //! at `impl`-level granularity instead of trait-level. 18 | //! 19 | //! ## Usage 20 | //! 21 | //! First of all, make a portrait of the trait to implement 22 | //! with the `#[portrait::make]` attribute: 23 | //! 24 | //! ```rs 25 | //! #[portrait::make] 26 | //! trait FooBar { 27 | //! // ... 28 | //! } 29 | //! ``` 30 | //! 31 | //! Implement the trait partially and leave the rest to the `#[portrait::fill]` attribute: 32 | //! 33 | //! ```rs 34 | //! #[portrait::fill(portrait::default)] 35 | //! impl FooBar {} 36 | //! ``` 37 | //! 38 | //! The `portrait::default` part is the path to the "filler macro", 39 | //! which is the item that actually fills the `impl` block. 40 | //! The syntax is similar to `#[derive(path::to::Macro)]`. 41 | //! 42 | //! If there are implementations in a different module, 43 | //! the imports used in trait items need to be manually passed to the make attribute: 44 | //! 45 | //! ```rs 46 | //! #[portrait::make(import( 47 | //! foo, bar::*, 48 | //! // same syntax as use statements 49 | //! ))] 50 | //! trait FooBar {...} 51 | //! ``` 52 | //! 53 | //! If the fill attribute fails with an error about undefined `foo_bar_portrait`, 54 | //! import it manually together with the FooBar trait; 55 | //! the `#[portrait::make]` attribute generates this new module 56 | //! in the same module as the `FooBar` trait. 57 | //! 58 | //! ## Provided fillers 59 | //! 60 | //! `portrait` provides the following filler macros: 61 | //! 62 | //! - [`default`]: 63 | //! Implements each missing method and constant by delegating to [`Default::default()`] 64 | //! (`Default` is const-unstable and requires nightly with `#![feature(const_default_impls)]`). 65 | //! - [`delegate`]: 66 | //! Proxies each missing method, constant and type 67 | //! to an expression (usually `self.field`) or another type implementing the same trait. 68 | //! - [`log`]: 69 | //! Calls a [`format!`]-like macro with the method arguments. 70 | //! 71 | //! ## How this works 72 | //! 73 | //! Rust macros are invoked at an early stage of the compilation chain. 74 | //! As a result, attribute macros only have access to the literal representation 75 | //! of the item they are applied on, 76 | //! and cross-item derivation is not directly possible. 77 | //! Most macros evade this problem by trying to generate code 78 | //! that works regardless of the inaccessible information, 79 | //! e.g. the `Default` derive macro works by invoking `Default::default()` 80 | //! without checking whether the actual field type actually implements `Default` 81 | //! (since the compiler would do at a later stage anyway). 82 | //! 83 | //! Unfortunately this approach does not work in the use case of `portrait`, 84 | //! where the attribute macro requires compile time (procedural macro runtime) access 85 | //! to the items of the trait referenced in the `impl` block; 86 | //! the only available information is the path to the trait 87 | //! (which could even be renamed to a different identifier). 88 | //! 89 | //! `portrait` addresses this challenge by 90 | //! asking the trait to export its information (its "portrait") 91 | //! in the form of a token stream in advance. 92 | //! Through the `#[portrait::make]` attribute, 93 | //! a *declarative* macro with the same identifier is derived, 94 | //! containing the trait items. 95 | //! The (`#[portrait::fill]`) attribute on the `impl` block 96 | //! then passes its inputs to the declarative macro, 97 | //! which in turn forwards them to the actual attribute implementation 98 | //! (e.g. `#[portrait::make]`) along with the trait items. 99 | //! 100 | //! Now the actual attribute has access to both the trait items and the user impl, 101 | //! but that's not quite yet the end of story. 102 | //! The trait items are written in the scope of the trait definition, 103 | //! but the attribute macro output is in the scope of the impl definition. 104 | //! The most apparent effect is that 105 | //! imports in the trait module do not take effect on the impl output. 106 | //! To avoid updating implementors frequently due to changes in the trait module, 107 | //! the `#[portrait::make]` attribute also derives a module 108 | //! that contains the imports used in the trait 109 | //! to be automatically imported in the impl block. 110 | //! 111 | //! It turns out that, as of current compiler limitations, 112 | //! private imports actually cannot be re-exported publicly 113 | //! even though the imported type is public, 114 | //! so it becomes impractical to scan the trait item automatically for paths to re-export 115 | //! (prelude types also need special treatment since they are not part of the module). 116 | //! The problem of heterogeneous scope thus becomes exposed to users inevitably: 117 | //! either type all required re-exports manually through import, 118 | //! or make the imports visible to a further scope. 119 | //! 120 | //! Another difficulty is that 121 | //! module identifiers share the same symbol space as trait identifiers 122 | //! (because `module::Foo` is indistinguishable from `Trait::Foo`). 123 | //! Thus, the module containing the imports cannot be imported together with the trait, 124 | //! and users have to manually import/export both symbols 125 | //! unless the trait is referenced through its enclosing module. 126 | //! 127 | //! ## Disclaimer 128 | //! 129 | //! `portrait` is not the first one to use declarative macros in attributes. 130 | //! [`macro_rules_attribute`][macro_rules_attribute] also implements a similar idea, 131 | //! although without involving the framework of generating the `macro_rules!` part. 132 | //! 133 | //! [macro_rules_attribute]: https://docs.rs/macro_rules_attribute/ 134 | 135 | #![no_std] 136 | 137 | use core::fmt; 138 | 139 | /// Placeholder values when a [cfg](attr@cfg)-disabled parameter is used in [`log`]. 140 | #[doc(hidden)] 141 | pub struct DummyDebug { 142 | /// The placeholder text 143 | pub text: &'static str, 144 | } 145 | 146 | impl fmt::Debug for DummyDebug { 147 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.text) } 148 | } 149 | 150 | /// **Impl filler**: 151 | /// Generates a dummy implementation that returns [`Default::default()`] 152 | /// in all associated constants and functions. 153 | /// 154 | /// # Example 155 | /// ``` 156 | /// // Constant defaults require the `const_default_impls` feature 157 | /// #![cfg_attr(feature = "const-default-impls", feature(const_default_impls))] 158 | /// 159 | /// #[portrait::make] 160 | /// trait Foo { 161 | /// fn qux() -> u64; 162 | /// 163 | /// #[cfg(feature = "const-default-impls")] 164 | /// const BAR: i32; 165 | /// } 166 | /// 167 | /// struct Corge; 168 | /// 169 | /// #[portrait::fill(portrait::default)] 170 | /// impl Foo for Corge {} 171 | /// 172 | /// assert_eq!(Corge::qux(), 0u64); 173 | /// 174 | /// #[cfg(feature = "const-default-impls")] 175 | /// assert_eq!(Corge::BAR, 0i32); 176 | /// ``` 177 | #[doc(inline)] 178 | #[cfg(feature = "default-filler")] 179 | pub use portrait_codegen::default; 180 | // 181 | 182 | // 183 | /// **Impl filler**: 184 | /// Generates an implementation that delegates 185 | /// to another implementation of the same trait. 186 | /// 187 | /// # Syntax 188 | /// ``` 189 | /// # /* 190 | /// #[portrait::fill(portrait::delegate($delegate_type:ty; $self_to_delegate_value:expr))] 191 | /// # */ 192 | /// ``` 193 | /// 194 | /// Alternatively, if the trait does not contain any associated functions with a receiver: 195 | /// ``` 196 | /// # /* 197 | /// #[portrait::fill(portrait::delegate($delegate_type:ty))] 198 | /// # */ 199 | /// ``` 200 | /// 201 | /// - `$delegate_type` is the type that the implementation should delegate to. 202 | /// - `$self_to_delegate_value` is an expression that returns the value to delegate methods with a receiver to. 203 | /// References are automatically generated by the macro if required. 204 | /// 205 | /// # Example 206 | /// ``` 207 | /// #[portrait::make] 208 | /// trait Foo { 209 | /// const BAR: i32; 210 | /// fn qux(&mut self, i: i64) -> u32; 211 | /// fn corge() -> u64; 212 | /// type Grault; 213 | /// } 214 | /// 215 | /// // This is our delegation target type. 216 | /// struct Real(T); 217 | /// impl Foo for Real { 218 | /// const BAR: i32 = 1; 219 | /// fn qux(&mut self, i: i64) -> u32 { i as u32 } 220 | /// fn corge() -> u64 { 3 } 221 | /// type Grault = Option; 222 | /// } 223 | /// 224 | /// struct Wrapper { 225 | /// real: Real, 226 | /// } 227 | /// 228 | /// #[portrait::fill(portrait::delegate(Real; self.real))] 229 | /// impl Foo for Wrapper {} 230 | /// // Note: We cannot use `U` as the generic type 231 | /// // because it is used in `type Grault` in the trait definition. 232 | /// 233 | /// assert_eq!(Wrapper::::BAR, 1); 234 | /// assert_eq!(Wrapper:: { real: Real(0) }.qux(2), 2); 235 | /// assert_eq!(Wrapper::::corge(), 3); 236 | /// let _: as Foo>::Grault = Some(1u8); 237 | /// ``` 238 | /// 239 | /// # Debugging tips 240 | /// If you see error E0275 or `warn(unconditional_recursion)`, 241 | /// it is because you try to delegate to the same type. 242 | /// Note that it does not make sense to delegate to a value of the same type 243 | /// since all constants and types would be recursively defined (`type X = X;`), 244 | /// and all functions would be recursively implemented (`fn x() { x() }`). 245 | #[doc(inline)] 246 | #[cfg(feature = "delegate-filler")] 247 | pub use portrait_codegen::delegate; 248 | // 249 | 250 | // 251 | /// Invokes a portrait derive macro on the applied type. 252 | /// 253 | /// # Usage 254 | /// ``` 255 | /// # /* 256 | /// #[portrait::derive(@OPTION1(...) @OPTION2 path::to::Trait with path::to::derive_filler(...))] 257 | /// struct Foo { 258 | /// // ... 259 | /// } 260 | /// # */ 261 | /// ``` 262 | /// 263 | /// The `(...)` parts are optional arguments passed for the option or the filler. 264 | /// If the option/filler does not expect any arguments, the entire parentheses may be omitted. 265 | /// 266 | /// ## Special options 267 | /// 268 | /// ### `DEBUG_PRINT_FILLER_OUTPUT` 269 | /// > Syntax: `@DEBUG_PRINT_FILLER_OUTPUT` 270 | /// 271 | /// Prints the output of the filler macro, used for filler macro developers to debug their code. 272 | /// 273 | /// ### `MOD_PATH` 274 | /// > Syntax: `@MOD_PATH(path::to::name)` 275 | /// 276 | /// Specifies the derived module path if it is imported differently 277 | /// or overridden with `name` in [`#[make]`](make). 278 | #[doc(inline)] 279 | pub use portrait_codegen::derive; 280 | // 281 | 282 | // 283 | /// **Derive filler**: 284 | /// Delegate functions to each of the fields in the struct. 285 | /// 286 | /// # Semantics 287 | /// Trait functions are implemented by calling the same function on each struct field 288 | /// in the order specified in the struct definition. 289 | /// 290 | /// ## Parameters 291 | /// Parameters are passed as-is into each field delegation call. 292 | /// Hence, all parameters must implement [`Copy`] or be a reference. 293 | /// 294 | /// If the parameter type is `Self`/`&Self`/`&mut Self`, 295 | /// the corresponding field is passed to the delegation call instead. 296 | /// 297 | /// ## Return values 298 | /// If the return type is `()`, no return values are involved. 299 | /// 300 | /// If the return type is `Self`, a new `Self` is constructed, 301 | /// with each field as the result of the delegation call for that field. 302 | /// 303 | /// For all other return types, the function should use the attribute 304 | /// 305 | /// ``` 306 | /// # /* 307 | /// #[portrait(derive_delegate(reduce = reduce_fn))] 308 | /// # */ 309 | /// ``` 310 | /// 311 | /// `reduce_fn(a, b)` is called to reduce the return value of every two fields to the output. 312 | /// `reduce_fn` may be a generic function that yields different inputs and outputs, 313 | /// provided that the final reduction call returns the type requested by the trait. 314 | /// 315 | /// # Options 316 | /// The `#[portrait(derive_delegate(...))]` attribute can be applied on associated functions 317 | /// to configure the derived delegation for the function. 318 | /// 319 | /// ## `try` 320 | /// If the `try` option is applied, the return type must be in the form `R`, 321 | /// e.g. `Result`, `Option`, etc., where the type implements [`Try`](std::ops::Try). 322 | /// Each delegation gets an `?` operator to return the error branch, 323 | /// and the result is wrapped by an `Ok(...)` call. 324 | /// `Ok` can be overridden by providing a value to the `try` option, e.g. 325 | /// 326 | /// ``` 327 | /// # /* 328 | /// #[portrait(derive_delegate(try = Some))] 329 | /// fn take(&self) -> Option; 330 | /// # */ 331 | /// ``` 332 | /// 333 | /// ## `reduce`, `reduce_base` 334 | /// If the `reduce` option is applied, 335 | /// the return values of delegation calls are combined by the reducer. 336 | /// The option requires a value that resolves to 337 | /// a function that accepts two parameters and returns a value. 338 | /// The type of the reducer is not fixed; 339 | /// the types of parameters and return values are resolved separately. 340 | /// 341 | /// If a `reduce_base` is supplied, the reducer starts with the base expression. 342 | /// Otherwise, it starts with the first two values. 343 | /// Example use cases include: 344 | /// 345 | /// ``` 346 | /// # /* 347 | /// /// Returns the logical conjunction of all fields. 348 | /// #[portrait(derive_delegate(reduce = |a, b| a && b))] 349 | /// fn all(&self) -> bool; 350 | /// 351 | /// /// Returns the sum of all field counts plus one. 352 | /// #[portrait(derive_delegate(reduce = |a, b| a + b, reduce_base = 1))] 353 | /// fn count(&self) -> usize; 354 | /// # */ 355 | /// ``` 356 | /// 357 | /// ## `enum_either` 358 | /// If the `enum_either` option is applied, when deriving from enums, 359 | /// each match arm is wrapped with a nested tree of `Either::Left(..)`/`Either::Right(..)`s 360 | /// such that each arm bijects to a unique variant of some `Either>>`. 361 | /// This is useful for delegating to separate enum implementations 362 | /// when the return type is opaque (e.g. return-impl-trait). 363 | /// 364 | /// ``` 365 | /// # /* 366 | /// #[portrait(derive_delegate(enum_either))] 367 | /// fn iter(&self) -> impl Iterator; 368 | /// # */ 369 | /// ``` 370 | /// 371 | /// Note that portrait only knows how to implement the trait with this associated function, 372 | /// but does not derive anything for the trait bound `Trait` in `-> impl Trait`. 373 | /// In particular, this means that someone has to have implemented `Trait` for `Either`. 374 | /// 375 | /// For traits not implemented by `Either` by default, an alternative wrapper could be used 376 | /// by specifying the "left" and "right" operands in the attribute: 377 | /// 378 | /// ``` 379 | /// # /* 380 | /// #[portrait(derive_delegate(enum_either = (left_wrapper, right_wrapper)))] 381 | /// fn as_trait(&self) -> impl Trait; 382 | /// # */ 383 | /// ``` 384 | /// 385 | /// # Example 386 | /// ``` 387 | /// #[portrait::make] 388 | /// trait Foo { 389 | /// fn new(arg1: i32, arg2: &str, arg3: &mut i64) -> Self; 390 | /// fn print(&self); 391 | /// fn clone(&self) -> Self; 392 | /// #[portrait(derive_delegate(reduce = |a, b| a && b))] 393 | /// fn eq(&self, other: &Self) -> bool; 394 | /// } 395 | /// 396 | /// # #[portrait::fill(portrait::default)] 397 | /// impl Foo for i32 {} 398 | /// # #[portrait::fill(portrait::default)] 399 | /// impl Foo for String {} 400 | /// 401 | /// #[portrait::derive(Foo with portrait::derive_delegate)] 402 | /// struct Fields { 403 | /// a: i32, 404 | /// b: String, 405 | /// } 406 | /// ``` 407 | /// 408 | /// Enums are also supported with a few restrictions: 409 | /// 410 | /// - All associated functions must have a receiver. 411 | /// - Non-receiver parameters must not take a `Self`-based type. 412 | /// ``` 413 | /// #[portrait::make] 414 | /// trait Foo { 415 | /// fn print(&self); 416 | /// fn clone(&self) -> Self; 417 | /// } 418 | /// 419 | /// # #[portrait::fill(portrait::default)] 420 | /// impl Foo for i32 {} 421 | /// # #[portrait::fill(portrait::default)] 422 | /// impl Foo for String {} 423 | /// 424 | /// #[portrait::derive(Foo with portrait::derive_delegate)] 425 | /// enum Variants { 426 | /// Foo { a: i32, b: String }, 427 | /// Bar(i32, String), 428 | /// } 429 | /// ``` 430 | /// 431 | /// Traits are implemented for generic types as long as the implementation is feasible, 432 | /// unlike the standard macros that implement on the generic variables directly. 433 | /// ``` 434 | /// #[portrait::make] 435 | /// trait Create { 436 | /// fn create() -> Self; 437 | /// } 438 | /// 439 | /// impl Create for Vec { 440 | /// fn create() -> Self { vec![] } 441 | /// } 442 | /// 443 | /// #[portrait::derive(Create with portrait::derive_delegate)] 444 | /// struct Fields { 445 | /// v: Vec, 446 | /// } 447 | /// 448 | /// static_assertions::assert_impl_all!(Fields: Create); 449 | /// static_assertions::assert_not_impl_any!(i32: Create); 450 | /// ``` 451 | #[doc(inline)] 452 | #[cfg(feature = "derive-delegate-filler")] 453 | pub use portrait_codegen::derive_delegate; 454 | // 455 | 456 | // 457 | /// Invokes a portrait macro on the applied impl block. 458 | /// 459 | /// # Usage 460 | /// ``` 461 | /// # /* 462 | /// #[portrait::fill(path::to::filler)] 463 | /// impl Trait for Type { 464 | /// // override filled items here 465 | /// } 466 | /// # */ 467 | /// ``` 468 | /// 469 | /// Pass the path to the filler macro in the attribute. 470 | /// Extra parameters can be specified in front of the path with the `@` syntax, e.g.: 471 | /// 472 | /// ``` 473 | /// # /* 474 | /// #[portrait::fill(@OPTION1(...) @OPTION2 path::to::filler(...))] 475 | /// # */ 476 | /// ``` 477 | /// 478 | /// The `(...)` parts are optional arguments passed for the option or the filler. 479 | /// If the option/filler does not expect any arguments, the entire parentheses may be omitted. 480 | /// 481 | /// ## Special options 482 | /// 483 | /// ### `DEBUG_PRINT_FILLER_OUTPUT` 484 | /// > Syntax: `@DEBUG_PRINT_FILLER_OUTPUT` 485 | /// 486 | /// Prints the output of the filler macro, used for filler macro developers to debug their code. 487 | /// 488 | /// ### `MOD_PATH` 489 | /// > Syntax: `@MOD_PATH(path::to::name)` 490 | /// 491 | /// Specifies the derived module path if it is imported differently 492 | /// or overridden with `name` in [`#[make]`](make). 493 | #[doc(inline)] 494 | pub use portrait_codegen::fill; 495 | // 496 | 497 | // 498 | /// **Impl filler**: 499 | /// Generates an implementation that simply logs the parameters and returns `()`. 500 | /// 501 | /// # Syntax 502 | /// ``` 503 | /// # /* 504 | /// #[portrait::fill(portrait::log($logger:path))] 505 | /// # */ 506 | /// ``` 507 | /// 508 | /// You can also specify leading parameters to the macro call: 509 | /// ``` 510 | /// # /* 511 | /// #[portrait::fill(portrait::log($logger:path, $($args:expr),*))] 512 | /// # */ 513 | /// ``` 514 | /// 515 | /// - `$logger` is the path to the macro for logging, e.g. `log::info` or [`println!`]. 516 | /// - `$args` are the arguments passed to the macro before the format template, 517 | /// e.g. the log level in `log::log` or the writer in [`writeln!`]. 518 | /// 519 | /// Associated constants are not supported. 520 | /// Associated types are always `()` 521 | /// (we assume to be the return likely type of `$logger`). 522 | /// 523 | /// Currently, this macro does not properly support `#[cfg]` on arguments yet. 524 | /// 525 | /// # Example 526 | /// ``` 527 | /// // Imports required for calling the `write!` macro 528 | /// use std::fmt::{self, Write}; 529 | /// 530 | /// #[portrait::make] 531 | /// trait Foo { 532 | /// type Bar; 533 | /// fn qux(&mut self, i: i64) -> Self::Bar; 534 | /// } 535 | /// 536 | /// #[derive(Default)] 537 | /// struct Receiver { 538 | /// buffer: String, 539 | /// } 540 | /// 541 | /// #[portrait::fill(portrait::log( 542 | /// write -> fmt::Result, 543 | /// &mut self.buffer, 544 | /// ))] 545 | /// impl Foo for Receiver {} 546 | /// 547 | /// let mut recv = Receiver::default(); 548 | /// recv.qux(3); 549 | /// assert_eq!(recv.buffer.as_str(), "qux(3)"); 550 | /// ``` 551 | #[doc(inline)] 552 | #[cfg(feature = "log-filler")] 553 | pub use portrait_codegen::log; 554 | // 555 | 556 | // 557 | /// Creates a portrait of a trait, allowing it to be used in [`fill`]. 558 | /// 559 | /// # Parameters 560 | /// Parameters are comma-delimited. 561 | /// 562 | /// ## `name` 563 | /// > Syntax: `name = $name:ident` 564 | /// 565 | /// Sets the derived module name to `$name`. 566 | /// Users for the [`#[fill]`] part have to import this name. 567 | /// 568 | /// ## `import` 569 | /// > Syntax: `import($($imports:UseTree)*)` 570 | /// 571 | /// Import the [use trees](https://docs.rs/syn/1/syn/enum.UseTree.html) in `$imports` 572 | /// in the scope of the `impl` block. 573 | /// 574 | /// ## `auto_imports` 575 | /// > Syntax: `auto_imports` 576 | /// 577 | /// An experimental feature for detecting imports automatically. 578 | /// Requires the imports to be `pub use` (or `pub(crate) use` if the trait is also `pub(crate)`) 579 | /// in order to re-export from the derived module. 580 | #[doc(inline)] 581 | pub use portrait_codegen::make; 582 | -------------------------------------------------------------------------------- /codegen/src/derive_fillers/derive_delegate.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | 3 | use portrait_framework::{DeriveContext, GenerateDerive, NoArgs}; 4 | use proc_macro2::Span; 5 | use syn::spanned::Spanned; 6 | 7 | use crate::util; 8 | 9 | pub(crate) struct Generator(pub(crate) NoArgs); 10 | 11 | impl GenerateDerive for Generator { 12 | fn generate_const( 13 | &mut self, 14 | _ctx: DeriveContext, 15 | item: &syn::TraitItemConst, 16 | ) -> syn::Result { 17 | Err(syn::Error::new_spanned(item, "derive_delegate does not support const items")) 18 | } 19 | 20 | fn generate_fn( 21 | &mut self, 22 | DeriveContext { input, trait_path, .. }: DeriveContext, 23 | item: &syn::TraitItemFn, 24 | ) -> syn::Result { 25 | let fn_args = util::parse_grouped_attr::(&item.attrs, "derive_delegate")?; 26 | 27 | let output_ty: syn::Type = if let syn::ReturnType::Type(_, ty) = &item.sig.output { 28 | if fn_args.with_try.0.is_some() { 29 | let make_err = || { 30 | syn::Error::new_spanned( 31 | ty, 32 | "`with_try` must be used with a type in the form `R` where `R` is \ 33 | a Try type e.g. `Result`/`Option`.", 34 | ) 35 | }; 36 | 37 | let syn::Type::Path(path) = &**ty else { 38 | return Err(make_err()); 39 | }; 40 | let last = path.path.segments.last().expect("path should not be empty"); 41 | let syn::PathArguments::AngleBracketed(args) = &last.arguments else { 42 | return Err(make_err()); 43 | }; 44 | let Some(syn::GenericArgument::Type(ok_ty)) = args.args.first() else { 45 | return Err(make_err()); 46 | }; 47 | ok_ty.clone() 48 | } else { 49 | (**ty).clone() 50 | } 51 | } else { 52 | syn::Type::Tuple(syn::parse_quote!(())) 53 | }; 54 | 55 | let mut stmts = match &input.data { 56 | syn::Data::Struct(data) => { 57 | transform_struct(item, trait_path, &fn_args, &output_ty, data)? 58 | } 59 | syn::Data::Enum(data) => transform_enum(item, trait_path, &fn_args, &output_ty, data)?, 60 | syn::Data::Union(data) => { 61 | return Err(syn::Error::new_spanned( 62 | data.union_token, 63 | "derive_delegate does not support unions", 64 | )) 65 | } 66 | }; 67 | 68 | if let &Some((with_try_span, ref with_try)) = &fn_args.with_try.0 { 69 | let try_fn = with_try 70 | .clone() 71 | .unwrap_or_else(|| syn::Expr::Path(syn::parse_quote_spanned!(with_try_span => Ok))); 72 | 73 | let old_stmt_block = syn::Block { 74 | brace_token: syn::token::Brace(with_try_span), 75 | stmts: mem::take(&mut stmts), 76 | }; 77 | 78 | let wrapped_stmt = syn::Expr::Call(syn::ExprCall { 79 | attrs: Vec::new(), 80 | func: Box::new(try_fn), 81 | paren_token: syn::token::Paren(with_try_span), 82 | args: [syn::Expr::Block(syn::ExprBlock { 83 | attrs: Vec::new(), 84 | label: None, 85 | block: old_stmt_block, 86 | })] 87 | .into_iter() 88 | .collect(), 89 | }); 90 | 91 | stmts.push(syn::Stmt::Expr(wrapped_stmt, None)); 92 | } 93 | 94 | Ok(syn::ImplItemFn { 95 | attrs: item 96 | .attrs 97 | .iter() 98 | .filter(|attr| attr.path().is_ident("cfg")) 99 | .cloned() 100 | .collect(), 101 | vis: syn::Visibility::Inherited, 102 | defaultness: None, 103 | sig: item.sig.clone(), 104 | block: syn::Block { brace_token: Default::default(), stmts }, 105 | }) 106 | } 107 | 108 | fn generate_type( 109 | &mut self, 110 | _ctx: DeriveContext, 111 | item: &syn::TraitItemType, 112 | ) -> syn::Result { 113 | Err(syn::Error::new_spanned(item, "derive_delegate does not support type items")) 114 | } 115 | 116 | fn extend_generics( 117 | &mut self, 118 | DeriveContext { trait_path, input, .. }: DeriveContext, 119 | _generics_params: &mut Vec, 120 | generics_where: &mut Vec, 121 | ) -> syn::Result<()> { 122 | fn add_generic_predicate( 123 | generics_where: &mut Vec, 124 | trait_path: &syn::Path, 125 | field: &syn::Field, 126 | ) { 127 | generics_where.push(syn::WherePredicate::Type(syn::PredicateType { 128 | lifetimes: None, 129 | bounded_ty: field.ty.clone(), 130 | colon_token: syn::Token![:](field.span()), 131 | bounds: [syn::TypeParamBound::Trait(syn::TraitBound { 132 | paren_token: None, 133 | modifier: syn::TraitBoundModifier::None, 134 | lifetimes: None, 135 | path: trait_path.clone(), 136 | })] 137 | .into_iter() 138 | .collect(), 139 | })); 140 | } 141 | 142 | match &input.data { 143 | syn::Data::Struct(data) => { 144 | for field in &data.fields { 145 | add_generic_predicate(generics_where, trait_path, field); 146 | } 147 | } 148 | syn::Data::Enum(data) => { 149 | for variant in &data.variants { 150 | for field in &variant.fields { 151 | add_generic_predicate(generics_where, trait_path, field); 152 | } 153 | } 154 | } 155 | _ => {} 156 | } 157 | 158 | Ok(()) 159 | } 160 | } 161 | 162 | fn transform_struct( 163 | item: &syn::TraitItemFn, 164 | trait_path: &syn::Path, 165 | fn_args: &FnArgs, 166 | output_ty: &syn::Type, 167 | data: &syn::DataStruct, 168 | ) -> syn::Result> { 169 | let mut stmts = Vec::new(); 170 | 171 | if let Some(receiver) = item.sig.receiver() { 172 | stmts.push(syn::Stmt::Local(syn::Local { 173 | attrs: Vec::new(), 174 | let_token: syn::Token![let](Span::call_site()), 175 | pat: syn::Pat::Struct(syn::PatStruct { 176 | attrs: Vec::new(), 177 | qself: None, 178 | path: syn::parse_quote!(Self), 179 | brace_token: syn::token::Brace(Span::call_site()), 180 | fields: data 181 | .fields 182 | .iter() 183 | .enumerate() 184 | .map(|(ord, field)| syn::FieldPat { 185 | attrs: cfg_attrs(&field.attrs), 186 | member: match &field.ident { 187 | Some(ident) => syn::Member::Named(ident.clone()), 188 | None => syn::Member::Unnamed(syn::Index { 189 | index: u32::try_from(ord).expect("too many fields"), 190 | span: field.span(), 191 | }), 192 | }, 193 | colon_token: Some(syn::Token![:](field.span())), 194 | pat: Box::new(syn::Pat::Path(syn::ExprPath { 195 | attrs: Vec::new(), 196 | qself: None, 197 | path: syn::Path::from(quote::format_ident!("__portrait_self_{ord}")), 198 | })), 199 | }) 200 | .collect(), 201 | rest: None, 202 | }), 203 | init: Some(syn::LocalInit { 204 | eq_token: syn::Token![=](Span::call_site()), 205 | expr: syn::parse_quote_spanned!(receiver.span() => self), 206 | diverge: None, 207 | }), 208 | semi_token: syn::Token![;](Span::call_site()), 209 | })); 210 | } 211 | stmts.extend(transform_return( 212 | item, 213 | fn_args, 214 | trait_path, 215 | output_ty, 216 | &data.fields, 217 | &syn::parse_quote!(Self), 218 | false, 219 | )?); 220 | Ok(stmts) 221 | } 222 | 223 | fn transform_enum( 224 | item: &syn::TraitItemFn, 225 | trait_path: &syn::Path, 226 | fn_args: &FnArgs, 227 | output_ty: &syn::Type, 228 | data: &syn::DataEnum, 229 | ) -> syn::Result> { 230 | let Some(receiver) = item.sig.receiver() else { 231 | return Err(syn::Error::new_spanned( 232 | &item.sig, 233 | "Cannot derive enum delegates for associated functions without receivers", 234 | )); 235 | }; 236 | 237 | let mut arms = Vec::new(); 238 | for (index, variant) in data.variants.iter().enumerate() { 239 | let variant_ident = &variant.ident; 240 | let arm_stmts = transform_return( 241 | item, 242 | fn_args, 243 | trait_path, 244 | output_ty, 245 | &variant.fields, 246 | &syn::parse_quote!(Self::#variant_ident), 247 | true, 248 | )?; 249 | 250 | let mut block = syn::Expr::Block(syn::ExprBlock { 251 | attrs: Vec::new(), 252 | label: None, 253 | block: syn::Block { 254 | brace_token: syn::token::Brace(variant.span()), 255 | stmts: arm_stmts, 256 | }, 257 | }); 258 | 259 | if let Some((_, either)) = &fn_args.enum_either.0 { 260 | if index + 1 == data.variants.len() { 261 | // if variants.len() == 4, 3 => Right(Right(Right)) 262 | for _ in 0..index { 263 | block = syn::Expr::Call(syn::ExprCall { 264 | attrs: Vec::new(), 265 | func: Box::new(either_right(either.as_ref())), 266 | args: [block].into_iter().collect(), 267 | paren_token: either_paren(either.as_ref()), 268 | }); 269 | } 270 | } else { 271 | // 0 => Left, 1 => Right(Left), 2 => Right(Right(Left)), ... 272 | block = syn::Expr::Call(syn::ExprCall { 273 | attrs: Vec::new(), 274 | func: Box::new(either_left(either.as_ref())), 275 | args: [block].into_iter().collect(), 276 | paren_token: either_paren(either.as_ref()), 277 | }); 278 | for _ in 0..index { 279 | block = syn::Expr::Call(syn::ExprCall { 280 | attrs: Vec::new(), 281 | func: Box::new(either_right(either.as_ref())), 282 | args: [block].into_iter().collect(), 283 | paren_token: either_paren(either.as_ref()), 284 | }); 285 | } 286 | } 287 | } 288 | 289 | let fields = variant 290 | .fields 291 | .iter() 292 | .enumerate() 293 | .map(|(ord, field)| syn::FieldPat { 294 | attrs: cfg_attrs(&field.attrs), 295 | member: match &field.ident { 296 | Some(ident) => syn::Member::Named(ident.clone()), 297 | None => syn::Member::Unnamed(syn::Index { 298 | index: u32::try_from(ord).expect("too many fields"), 299 | span: field.span(), 300 | }), 301 | }, 302 | colon_token: Some(syn::Token![:](field.span())), 303 | pat: Box::new(syn::Pat::Path(syn::ExprPath { 304 | attrs: Vec::new(), 305 | qself: None, 306 | path: syn::Path::from(quote::format_ident!("__portrait_self_{ord}")), 307 | })), 308 | }) 309 | .collect(); 310 | 311 | arms.push(syn::Arm { 312 | attrs: cfg_attrs(&variant.attrs), 313 | pat: syn::Pat::Struct(syn::PatStruct { 314 | attrs: Vec::new(), 315 | qself: None, 316 | path: syn::parse_quote!(Self::#variant_ident), 317 | brace_token: syn::token::Brace(variant.span()), 318 | fields, 319 | rest: Some(syn::PatRest { 320 | attrs: Vec::new(), 321 | dot2_token: syn::Token![..](variant.span()), 322 | }), 323 | }), 324 | guard: None, 325 | fat_arrow_token: syn::Token![=>](variant.span()), 326 | body: Box::new(block), 327 | comma: Some(syn::Token![,](variant.span())), 328 | }) 329 | } 330 | 331 | let match_stmt = syn::Stmt::Expr( 332 | syn::Expr::Match(syn::ExprMatch { 333 | attrs: Vec::new(), 334 | match_token: syn::Token![match](Span::call_site()), 335 | expr: Box::new(syn::parse_quote_spanned!(receiver.span() => self)), 336 | brace_token: syn::token::Brace(Span::call_site()), 337 | arms, 338 | }), 339 | None, 340 | ); 341 | Ok(vec![match_stmt]) 342 | } 343 | 344 | fn transform_return( 345 | item: &syn::TraitItemFn, 346 | fn_args: &FnArgs, 347 | trait_path: &syn::Path, 348 | output_ty: &syn::Type, 349 | fields: &syn::Fields, 350 | ctor_path: &syn::Path, 351 | is_refutable: bool, 352 | ) -> syn::Result> { 353 | let exprs = transform_arg_fields(item, fn_args, trait_path, fields, ctor_path, is_refutable)?; 354 | 355 | let exprs = match exprs.try_into() { 356 | Ok::<[_; 1], _>([(single, _, _)]) => return Ok(vec![syn::Stmt::Expr(single, None)]), 357 | Err(err) => err, 358 | }; 359 | 360 | Ok(match (&fn_args.reduce.0, output_ty) { 361 | (Some((_, reduce_fn)), _) => { 362 | let mut exprs_iter = exprs.into_iter(); 363 | 364 | let mut stack = if let Some((_, reduce_base)) = &fn_args.reduce_base.0 { 365 | reduce_base.clone() 366 | } else { 367 | let Some((first, _, _)) = exprs_iter.next() else { 368 | return Err(syn::Error::new( 369 | Span::call_site(), 370 | "derive_delegate(reduce) is not applicable for empty structs", 371 | )); 372 | }; 373 | first 374 | }; 375 | 376 | for (expr, _, field) in exprs_iter { 377 | stack = syn::parse_quote_spanned! { field.span() => 378 | (#reduce_fn)(#stack, #expr) 379 | }; 380 | } 381 | 382 | vec![syn::Stmt::Expr(stack, None)] 383 | } 384 | (_, syn::Type::Tuple(tuple)) if tuple.elems.is_empty() => exprs 385 | .into_iter() 386 | .map(|(delegate, _ord, field)| { 387 | syn::Stmt::Expr(delegate, Some(syn::Token![;](field.span()))) 388 | }) 389 | .collect(), 390 | (_, syn::Type::Path(ty_path)) if ty_path.path.is_ident("Self") => { 391 | let expr = syn::Expr::Struct(syn::ExprStruct { 392 | attrs: Vec::new(), 393 | qself: None, 394 | path: ctor_path.clone(), 395 | brace_token: syn::token::Brace(item.span()), 396 | fields: { 397 | exprs 398 | .into_iter() 399 | .map(|(delegate, ord, field)| syn::FieldValue { 400 | attrs: cfg_attrs(&field.attrs), 401 | member: match &field.ident { 402 | Some(ident) => syn::Member::Named(ident.clone()), 403 | None => syn::Member::Unnamed(syn::Index { 404 | index: u32::try_from(ord).expect("too many fields"), 405 | span: field.span(), 406 | }), 407 | }, 408 | colon_token: Some(syn::Token![:](field.span())), 409 | expr: delegate, 410 | }) 411 | .collect() 412 | }, 413 | dot2_token: None, 414 | rest: None, 415 | }); 416 | let stmt = syn::Stmt::Expr(expr, None); 417 | vec![stmt] 418 | } 419 | _ => { 420 | return Err(syn::Error::new_spanned( 421 | output_ty, 422 | "Cannot determine how to aggregate the return value. Supported return types are \ 423 | `()`, `Self` or arbitrary types with the `#[portrait(derive_delegate(reduce = \ 424 | _))]` attribute, or `Option<>`/`Result<>` wrapping them with \ 425 | `#[portrait(derive_delegate(with_try))]`.", 426 | )) 427 | } 428 | }) 429 | } 430 | 431 | fn transform_arg_fields<'t>( 432 | item: &syn::TraitItemFn, 433 | fn_args: &FnArgs, 434 | trait_path: &syn::Path, 435 | fields: &'t syn::Fields, 436 | ctor_path: &syn::Path, 437 | is_refutable: bool, 438 | ) -> syn::Result> { 439 | fields 440 | .iter() 441 | .enumerate() 442 | .map(|(ord, field)| { 443 | let mut expr = syn::Expr::Call(syn::ExprCall { 444 | attrs: Vec::new(), 445 | func: Box::new({ 446 | let mut func = trait_path.clone(); 447 | func.segments.push(item.sig.ident.clone().into()); 448 | syn::Expr::Path(syn::ExprPath { attrs: Vec::new(), qself: None, path: func }) 449 | }), 450 | paren_token: syn::token::Paren(field.span()), 451 | args: item 452 | .sig 453 | .inputs 454 | .iter() 455 | .map(|arg| transform_arg(arg, field, ord, ctor_path, is_refutable)) 456 | .collect::>()?, 457 | }); 458 | 459 | if let Some((with_try_span, _)) = fn_args.with_try.0 { 460 | expr = syn::Expr::Try(syn::ExprTry { 461 | attrs: Vec::new(), 462 | expr: Box::new(expr), 463 | question_token: syn::Token![?](with_try_span), 464 | }) 465 | } 466 | 467 | Ok((expr, ord, field)) 468 | }) 469 | .collect() 470 | } 471 | 472 | fn transform_arg( 473 | arg: &syn::FnArg, 474 | field: &syn::Field, 475 | ord: usize, 476 | ctor_path: &syn::Path, 477 | is_refutable: bool, 478 | ) -> syn::Result { 479 | let field_ident = quote::format_ident!("__portrait_self_{ord}"); 480 | 481 | let ret = match arg { 482 | syn::FnArg::Receiver(_) => syn::Expr::Path(syn::parse_quote!(#field_ident)), 483 | syn::FnArg::Typed(arg) if is_self_ty(&arg.ty) => { 484 | if is_refutable { 485 | return Err(syn::Error::new_spanned( 486 | arg, 487 | "Non-receiver Self parameters are only supported for structs", 488 | )); 489 | } 490 | 491 | let member = match &field.ident { 492 | Some(ident) => syn::Member::Named(ident.clone()), 493 | None => syn::Member::Unnamed(syn::Index { 494 | index: u32::try_from(ord).expect("too many fields"), 495 | span: field.span(), 496 | }), 497 | }; 498 | syn::Expr::Block(syn::parse_quote! {{ 499 | let #ctor_path { #member: __portrait_other, .. } = self; 500 | __portrait_other 501 | }}) 502 | } 503 | syn::FnArg::Typed(arg) => syn::Expr::Path(syn::ExprPath { 504 | attrs: Vec::new(), 505 | qself: None, 506 | path: { 507 | let syn::Pat::Ident(ident) = &*arg.pat else { 508 | return Err(syn::Error::new_spanned( 509 | &arg.pat, 510 | "Cannot derive delegate for traits with non-identifier-pattern parameters", 511 | )); 512 | }; 513 | ident.ident.clone().into() 514 | }, 515 | }), 516 | }; 517 | Ok(ret) 518 | } 519 | 520 | fn is_self_ty(ty: &syn::Type) -> bool { 521 | match ty { 522 | syn::Type::Path(ty) => ty.path.is_ident("Self"), 523 | syn::Type::Reference(ty) => is_self_ty(&ty.elem), 524 | _ => false, 525 | } 526 | } 527 | 528 | mod kw { 529 | syn::custom_keyword!(reduce); 530 | syn::custom_keyword!(reduce_base); 531 | syn::custom_keyword!(enum_either); 532 | } 533 | 534 | #[derive(Default)] 535 | struct FnArgs { 536 | reduce: util::Once, 537 | reduce_base: util::Once, 538 | with_try: util::Once>, 539 | enum_either: util::Once>, 540 | } 541 | 542 | impl util::ParseArgs for FnArgs { 543 | fn parse_once(&mut self, input: syn::parse::ParseStream) -> syn::Result<()> { 544 | let lh = input.lookahead1(); 545 | if lh.peek(kw::reduce) { 546 | let key: kw::reduce = input.parse()?; 547 | let _: syn::Token![=] = input.parse()?; 548 | self.reduce.set(input.parse()?, key.span())?; 549 | } else if lh.peek(kw::reduce_base) { 550 | let key: kw::reduce_base = input.parse()?; 551 | let _: syn::Token![=] = input.parse()?; 552 | self.reduce_base.set(input.parse()?, key.span())?; 553 | } else if lh.peek(syn::Token![try]) { 554 | let key: syn::Token![try] = input.parse()?; 555 | 556 | let ok_expr = if input.peek(syn::Token![=]) { 557 | let _: syn::Token![=] = input.parse()?; 558 | let expr: syn::Expr = input.parse()?; 559 | Some(expr) 560 | } else { 561 | None 562 | }; 563 | 564 | self.with_try.set(ok_expr, key.span())?; 565 | } else if lh.peek(kw::enum_either) { 566 | let key: kw::enum_either = input.parse()?; 567 | let value = input.peek(syn::Token![=]).then( ||{ 568 | let _: syn::Token![=] = input.parse()?; 569 | 570 | let inner; 571 | let paren = syn::parenthesized!(inner in input); 572 | 573 | Ok(EnumEither { paren, left: inner.parse()?, _comma: inner.parse()?, right: inner.parse()? }) 574 | }).transpose()?; 575 | self.enum_either.set(value, key.span())?; 576 | }else { 577 | return Err(lh.error()); 578 | } 579 | Ok(()) 580 | } 581 | } 582 | 583 | struct EnumEither { 584 | paren: syn::token::Paren, 585 | left: syn::Expr, 586 | _comma: syn::Token![,], 587 | right: syn::Expr, 588 | } 589 | 590 | fn either_left(option: Option<&EnumEither>) -> syn::Expr { 591 | match option { 592 | Some(either) => either.left.clone(), 593 | None => syn::parse_quote! { Either::Left }, 594 | } 595 | } 596 | 597 | fn either_right(option: Option<&EnumEither>) -> syn::Expr { 598 | match option { 599 | Some(either) => either.right.clone(), 600 | None => syn::parse_quote! { Either::Right }, 601 | } 602 | } 603 | 604 | fn either_paren(option: Option<&EnumEither>) -> syn::token::Paren { 605 | match option { 606 | Some(either) => either.paren, 607 | None => syn::token::Paren::default(), 608 | } 609 | } 610 | 611 | fn cfg_attrs<'t>(attrs: impl IntoIterator) -> Vec { 612 | attrs.into_iter().filter(|attr| attr.path().is_ident("cfg")).cloned().collect() 613 | } 614 | --------------------------------------------------------------------------------