Skip to content

Commit 642a51c

Browse files
feat(rustlang book): Advanced features(Derive Macros)
1 parent 0e4c6ad commit 642a51c

File tree

6 files changed

+69
-0
lines changed

6 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
workspace = { members = ["hello_macro_derive"] }
2+
[package]
3+
name = "hello_macro"
4+
version = "0.1.0"
5+
edition = "2021"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[package]
2+
name = "hello_macro_derive"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[lib]
7+
proc-macro = true
8+
9+
[dependencies]
10+
syn = "1.0"
11+
quote = "1.0"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
use proc_macro::TokenStream;
2+
use quote::quote;
3+
use syn;
4+
5+
#[proc_macro_derive(HelloMacro)]
6+
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
7+
// Construct a representation of Rust code as a syntax tree
8+
// that we can manipulate
9+
let ast = syn::parse(input).unwrap();
10+
11+
// Build the trait implementation
12+
impl_hello_macro(&ast)
13+
}
14+
15+
fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
16+
let name = &ast.ident;
17+
18+
let gen = quote! {
19+
impl HelloMacro for #name {
20+
fn hello_macro() {
21+
println!("Hello, Macro! My name is {}", stringify!(#name));
22+
}
23+
}
24+
};
25+
26+
gen.into()
27+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
pub trait HelloMacro {
2+
fn hello_macro();
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
name = "pancakes"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
hello_macro = { path = "../hello_macro" }
10+
hello_macro_derive = { path = "../hello_macro/hello_macro_derive/" }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
use hello_macro::HelloMacro;
2+
use hello_macro_derive::HelloMacro;
3+
4+
#[derive(HelloMacro)]
5+
struct Chapatis;
6+
7+
fn main() {
8+
Chapatis::hello_macro();
9+
}

0 commit comments

Comments
 (0)