1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//! Finite Field Computation.

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(BinaryArithmetic)]
pub fn derive_mod2_arithmetic(input: TokenStream) -> TokenStream {
    //Parse the input tokens into a syntax tree
    let ast = parse_macro_input!(input as DeriveInput);
    let name = &ast.ident;

    // Build the output, possibly using quasi-quotation
    let expanded = quote! {
        impl Add for #name {
            type Output = Self;
            fn add(self, rhs: Self) -> Self::Output {
                #name(self.0 ^ rhs.0)
            }
        }
        impl Sub for #name {
            type Output = Self;
            fn sub(self, rhs: Self) -> Self::Output {
                #name(self.0 ^ rhs.0)
            }
        }
        impl Mul for #name {
            type Output = Self;
            fn mul(self, rhs: Self) -> Self::Output {
                #name(self.0 & rhs.0)
            }
        }
    };

    // Hand the output tokens back to the compiler
    TokenStream::from(expanded)
}