0

我在 Rust 的派生宏中做了以下尝试:

extern crate proc_macro;

use crate::proc_macro::TokenStream;
use quote::quote;
use syn;

#[proc_macro_derive(DeserializeConfigurable)]
pub fn deserialize_configurable_derive(input: TokenStream) -> TokenStream {
    let ast: syn::DeriveInput = syn::parse(input).unwrap();
    let name = &ast.ident;
    let gen = quote! {
        impl<'de> Deserialize<'de> for #name {
            fn deserialize<D>(deserializer: D) -> Result<#name, D::Error>
            where
                D: Deserializer<'de>,
            {
                let config = <#name as Configurable>::Config::deserialize(deserializer)?;
                Ok(#name::from_config(config))
            }
        }
    };
    gen.into()
}

目标是deserialize基于另一个特征为Configurable.

但是,编译器对我的报价声明有以下抱怨:

扩展宏时达到递归限制stringify

我在这里看不到递归。我什至没有使用stringify!什么叫什么在这里无限?

4

1 回答 1

1

尝试在本地编译它会给出完整的错误消息:

error: recursion limit reached while expanding the macro `stringify`
  --> src/lib.rs:13:15
   |
13 |       let gen = quote! {
   |  _______________^
14 | |         impl<'de> Deserialize<'de> for #name {
15 | |             fn deserialize<D>(deserializer: D) -> Result<#name, D::Error>
16 | |             where
...  |
22 | |         }
23 | |     };
   | |_____^
   |
   = help: consider adding a `#![recursion_limit="128"]` attribute to your crate
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)                                                                                                                                 

error: aborting due to previous error

将以下内容作为 crate 的第一行会使错误消失。我的猜测是,对于如此复杂的宏(IMO 并不那么复杂),默认的 recursion_limit 太低了。我确信有充分的理由,我很高兴错误消息包含解决方案:

#![recursion_limit="128"]
于 2019-01-04T19:52:40.443 回答