Skip to content

Commit

Permalink
replace proc macros with matching macros use macro_metavar_expr feature
Browse files Browse the repository at this point in the history
  • Loading branch information
cartercanedy committed Sep 7, 2024
1 parent c4e0365 commit aead38e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 44 deletions.
8 changes: 0 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,3 @@ edition = "2021"
authors = ["Carter Canedy <[email protected]>"]
repository = "https://github.com/cartercanedy/zips"
license = "MIT"

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1.0.86"
quote = "1.0.36"
syn = { version = "~2.0.77", features = ["parsing", "derive", "proc-macro", "printing"], default-features = false }
69 changes: 33 additions & 36 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
// Copyright (c) 2024 Carter Canedy <[email protected]>

use {
proc_macro::TokenStream,
syn::{parse_macro_input, Expr, Token},
syn::parse::{Parse, ParseStream},
syn::punctuated::Punctuated,
quote::quote,
};
#![feature(macro_metavar_expr)]

type ZipToken = Punctuated<Expr, Token![,]>;

Expand Down Expand Up @@ -39,7 +33,8 @@ impl Parse for ZipArgs {
///
/// ## Usage:
/// ```
/// use zips::zip;
/// let zipped_some = zip!(Some(1), Some(2));
/// assert_eq!(zipped_some, Some((1, 2)));
///
/// let i: Option<i32> = Some(0);
/// let j: Option<usize> = Some(1usize);
Expand All @@ -53,22 +48,23 @@ impl Parse for ZipArgs {
/// let zipped_none = zip!(i, j, k);
/// assert_eq!(zipped_none, None);
/// ```
#[proc_macro]
pub fn zip(input: TokenStream) -> TokenStream {
let (ZipArgs { args }, arg_names) = extract_args!(input as ZipArgs);

let args = args.into_iter();

quote! {
{
#(let #arg_names = #args;)*
if #(#arg_names.is_some() &&)* true {
Some((#(#arg_names.unwrap()),*))
} else {
None
#[macro_export]
macro_rules! zip {
($($args:expr),+) => ({
let mut ok = true;
$(
let arg${index()} = $args;
if arg${index()}.is_none() {
ok = false;
}
)+

if ok {
Some(($(arg${index()}.unwrap(),)+))
} else {
None
}
}.into()
});
}

/// Expands into a single `Some((T1 [, T2...]))` instance if all arguments
Expand All @@ -90,20 +86,21 @@ pub fn zip(input: TokenStream) -> TokenStream {
/// let zipped_err = zip_result!(i, j, k);
/// assert_eq!(zipped_err, None);
/// ```
#[proc_macro]
pub fn zip_result(input: TokenStream) -> TokenStream {
let (ZipArgs { args }, arg_names) = extract_args!(input as ZipArgs);

let args = args.into_iter();

quote! {
{
#(let #arg_names = #args;)*
if #(#arg_names.is_ok() &&)* true {
Some((#(#arg_names.ok().unwrap()),*))
} else {
None
#[macro_export]
macro_rules! zip_result {
($($args:expr),+) => ({
let mut ok = true;
$(
if $args.is_err() {
ok = false;
}
)+

if ok {
Some(($($args.ok().unwrap(),)+))
} else {
None
}
}.into()
});
}

0 comments on commit aead38e

Please sign in to comment.