File tree 6 files changed +69
-0
lines changed
rustlang_book/advanced_features/macros
6 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
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 number Diff line number Diff line change
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 number Diff line number Diff line change
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 number Diff line number Diff line change
1
+ pub trait HelloMacro {
2
+ fn hello_macro ( ) ;
3
+ }
Original file line number Diff line number Diff line change
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 number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments