如何实现一个实现通用枚举的通用特征的过程宏?

时间:2017-02-28 12:49:58

标签: generics enums macros rust

如何为这样的枚举实现程序宏?

#[derive(Copy, Clone, Debug, MyProcMacro)]
enum Enum<W, C, I, F> {
    A(W),
    B(C),
    C(I),
    D(F)
}

我曾尝试使用syn::Generics,但它无法编译并生成无效代码。这是我想要实现的特性:

pub trait MyTrait<S> {
    fn change(&mut self, new_obj: S) -> bool;
}

并实施:

#[proc_macro_derive(MyProcMacro)]
pub fn my_proc_macro(input: TokenStream) -> TokenStream {
    // Construct a string representation of the type definition
    let s = input.to_string();

    // Parse the string representation
    let ast = syn::parse_derive_input(&s).unwrap();

    // Build the impl
    let gen = impl_macro(&ast);

    // Return the generated impl
    gen.parse().unwrap()
}

fn impl_macro(ast: &syn::DeriveInput) -> Tokens {
    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

quote! {
    impl #impl_generics mycrate::MyTrait<#name #ty_generics> for #name #ty_generics #where_clause {
        fn change(&mut self, new_obj: #name #ty_generics) -> bool {
            true
        }
    }
}

它提供了这段代码:

impl < W , C , I , F > mycrate :: MyTrait < Enum < W , C , I , F > > for Enum < W , C , I , F > { 
    fn change ( & mut self , new_obj : Enum < W , C , I , F > ) -> bool {
        true 
    }
}

我认为应该是这样的:

impl MyTrait<Enum<u64, u64, u64, u64>> for Enum<u64, u64, u64, u64> {
    fn change(&mut self, new_obj: Enum<u64, u64, u64, u64>) {
        true
    }
}

据我所知,我们无法从程序宏观背景中获取有关所需类型的信息,我是否正确?我想这就是为什么我在syn箱子里找不到这样的信息。

如果我保留未写入的代码,我会收到此错误:

error[E0382]: use of moved value: `new_obj`
  --> src/main.rs:28:30
   |
28 | #[derive(Copy, Clone, Debug, MyProcMacro)]
   |                              ^^^^^^^^^^^ value moved here in previous iteration of loop
   |
   = note: move occurs because `new_obj` has type `Enum<W, C, I, F>`, which does not implement the `Copy` trait

这个错误对我来说很奇怪,因为这个enum肯定会得到Copy特征。

UPD:

基于@Matthieu M.的评论,我能够通过向每个枚举类型添加Copy要求来成功编译它:

enum CupState<W: Copy, C: Copy, I: Copy, F: Copy> { ... }

但是,我仍然在寻找一种不需要用户代码操作的更好的解决方案。

1 个答案:

答案 0 :(得分:0)

如果您需要实现自己的派生类型来实现Copy,则可以让自己的派生宏在生成的impl块中的每个类型参数上添加一个绑定的T: Copy

extern crate proc_macro;
use self::proc_macro::TokenStream;

use quote::quote;
use syn::{parse_macro_input, parse_quote, DeriveInput, GenericParam, Generics};

#[proc_macro_derive(MyProcMacro)]
pub fn my_proc_macro(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);

    let name = &ast.ident;
    let generics = add_trait_bounds(ast.generics);
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    TokenStream::from(quote! {
        impl #impl_generics MyTrait<Self> for #name #ty_generics #where_clause {
            fn change(&mut self, new_obj: Self) -> bool {
                true
            }
        }
    })
}

// Add a bound `T: Copy` to every type parameter T.
fn add_trait_bounds(mut generics: Generics) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(Copy));
        }
    }
    generics
}

调用宏:

use my_proc_macro::MyProcMacro;

pub trait MyTrait<S> {
    fn change(&mut self, new_obj: S) -> bool;
}

#[derive(Copy, Clone, Debug, MyProcMacro)]
enum Enum<W, C, I, F> {
    A(W),
    B(C),
    C(I),
    D(F),
}

使用cargo expand,我们可以确认生成的代码具有Copy范围:

impl<W: Copy, C: Copy, I: Copy, F: Copy> MyTrait<Self> for Enum<W, C, I, F> {
    fn change(&mut self, new_obj: Self) -> bool {
        true
    }
}
相关问题