Skip to content

Commit

Permalink
add derive order test
Browse files Browse the repository at this point in the history
  • Loading branch information
maksym-arutyunyan committed Sep 1, 2024
1 parent e1a97f6 commit 377becd
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 0 deletions.
5 changes: 5 additions & 0 deletions research/derive_order/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[workspace]
members = [
"derive_macros",
"use_macros",
]
12 changes: 12 additions & 0 deletions research/derive_order/derive_macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "derive_macros"
version = "0.1.0"
edition = "2021"

[lib]
proc-macro = true

[dependencies]
syn = "2.0"
quote = "1.0"
proc-macro2 = "1.0"
42 changes: 42 additions & 0 deletions research/derive_order/derive_macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(First)]
pub fn derive_first(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let name = &ast.ident;

let expanded = quote! {
impl First for #name {
fn is_first_implemented() -> bool {
true
}
}
};

TokenStream::from(expanded)
}

#[proc_macro_derive(Second)]
pub fn derive_second(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let name = &ast.ident;

let expanded = quote! {
impl Second for #name {
fn check_first_is_implemented() -> bool {
if <#name as First>::is_first_implemented() {
println!("First is implemented, so Second works!");
true
} else {
println!("First is NOT implemented, so Second fails!");
false
}
}
}
};

TokenStream::from(expanded)
}
7 changes: 7 additions & 0 deletions research/derive_order/use_macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "use_macros"
version = "0.1.0"
edition = "2021"

[dependencies]
derive_macros = { path = "../derive_macros" }
28 changes: 28 additions & 0 deletions research/derive_order/use_macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#[cfg(test)]
mod tests {
use derive_macros::{First, Second};

trait First {
fn is_first_implemented() -> bool;
}

trait Second {
fn check_first_is_implemented() -> bool;
}

#[test]
fn test_first_second() {
#[derive(First, Second)] // <-- This should work correctly.
struct MyStruct;

assert!(<MyStruct as Second>::check_first_is_implemented());
}

#[test]
fn test_second_first() {
#[derive(Second, First)] // <-- Clarify if this should work or fail.
struct MyStruct;

assert!(<MyStruct as Second>::check_first_is_implemented());
}
}

0 comments on commit 377becd

Please sign in to comment.