Вызвать `stringify!` Внутри макроса - PullRequest
1 голос
/ 09 апреля 2019

Этот макрос компилируется при вызове:

macro_rules! remote_optional {
    ($remote:ident with=$def:ident $def_str:expr) => {
        impl $def {
            fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<$remote>, D::Error>
            where
                D: Deserializer<'de>,
            {
                #[derive(Deserialize)]
                struct Wrapper(#[serde(with = $def_str)] $remote);

                let v: Option<Wrapper> = Option::deserialize(deserializer)?;
                Ok(v.map(|Wrapper(a)| a))
            }
        }
    }
}

Этот не:

macro_rules! remote_optional {
    ($remote:ident with=$def:ident) => {
        impl $def {
            fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<$remote>, D::Error>
            where
                D: Deserializer<'de>,
            {
                #[derive(Deserialize)]
                struct Wrapper(#[serde(with = stringify!($def))] $remote);

                let v: Option<Wrapper> = Option::deserialize(deserializer)?;
                Ok(v.map(|Wrapper(a)| a))
            }
        }
    }
}

Это потому, что stringify!($def) передается в атрибут #[serde(...)] без оценки.

Есть ли практический обходной путь?

1 Ответ

2 голосов
/ 09 апреля 2019

Может ли макрос из двух аргументов переслать макрос из трех аргументов, раскрыв идентификатор def?

macro_rules! remote_optional {
    // The one that doesn't work (two arguments)
    // forwards to the one that *does* work, expanding the
    // string.
    ($remote:ident with=$def:ident) => {
        remote_optional!($remote, with=$def, stringify!($def));
    };

    // The macro that *does* work
    ($remote:ident with=$def:ident $def_str:expr) => {
        impl $def {
            fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<$remote>, D::Error>
            where
                D: Deserializer<'de>,
            {
                #[derive(Deserialize)]
                struct Wrapper(#[serde(with = $def_str)] $remote);

                let v: Option<Wrapper> = Option::deserialize(deserializer)?;
                Ok(v.map(|Wrapper(a)| a))
            }
        }
    };
}

Мы также могли бы рассмотреть вопрос о том, чтобы сделать макрос из трех аргументов деталью реализации.

Маленькое изолированное доказательство концепции:

macro_rules! my_macro {
    ($x:expr, $y:expr) => {
        my_macro!($x, $y, stringify!($x + $y));
    };

    ($x:expr, $y:expr, $msg:expr) => {
        println!("{} + {} = {}", $x, $y, $msg);
    };
}


fn main() {
    my_macro!(3, 2); // 3 + 2 = 3 + 2
}
...