Last active
June 4, 2022 13:08
-
-
Save abiriadev/a56a4c88af929ae9e514c8745649957d to your computer and use it in GitHub Desktop.
star! macro. this simply prints a pyramid of stars without... any loop ;)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "star-macro" | |
version = "0.1.0" | |
edition = "2021" | |
[lib] | |
proc-macro = true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[proc_macro] | |
pub fn star( | |
input: proc_macro::TokenStream | |
) -> proc_macro::TokenStream { | |
let mut it = input.into_iter(); | |
let star = it | |
.next() | |
.unwrap() | |
.to_string(); | |
proc_macro::TokenStream::from_iter([ | |
proc_macro::TokenTree::Ident( | |
proc_macro::Ident::new( | |
"println", | |
proc_macro::Span::call_site(), | |
) | |
), | |
proc_macro::TokenTree::Punct( | |
proc_macro::Punct::new( | |
'!', | |
proc_macro::Spacing::Alone | |
) | |
), | |
proc_macro::TokenTree::Group( | |
proc_macro::Group::new( | |
proc_macro::Delimiter::Parenthesis, | |
proc_macro::TokenStream::from( | |
proc_macro::TokenTree::Literal( | |
proc_macro::Literal::string( | |
&(1..=it | |
.skip(1) | |
.next() | |
.unwrap() | |
.to_string() | |
.parse::<usize>() | |
.unwrap() | |
) | |
.into_iter() | |
.map(|n| | |
std::iter::repeat( | |
star.clone() | |
) | |
.take(n) | |
.collect::<String>() | |
) | |
.collect::<Vec<_>>() | |
.join("\n"), | |
) | |
) | |
), | |
) | |
), | |
]) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use star_macro::star; | |
fn main() { | |
star!(*;5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment