gpt4 book ai didi

rust - 在其他proc宏内调用proc宏

转载 作者:行者123 更新时间:2023-12-03 11:45:33 28 4
gpt4 key购买 nike

我有一个小型的复制项目,无法编译。该项目可以在这里下载:https://github.com/Jasperav/proc_macro_collision。错误是:

error[E0659]: `proc_macro_call` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)

我在项目中有3个库和1个可执行文件:
  • Lib 1-解析器-解析proc宏调用
  • Lib 2-proc_two-将文字字符串作为proc宏调用
  • 返回
  • 库3-proc_one-将宏转发到proc_two(尽管它对proc_two没有依赖性)。这就像proc_two也是proc宏。

  • proc_one的相关代码:
    #[proc_macro_hack]
    pub fn one(input: TokenStream) -> TokenStream {
    let parse = parse_macro_input!(input as Parser);
    let r = parse.lit;

    let x = quote! {
    two!(#r) // This is the problem I guess...
    };

    x.into()
    }
  • 可执行文件:调用proc_one(产生编译错误)。

  • 相关代码:
    use proc_macro_hack::proc_macro_hack;
    extern crate proc_one;
    extern crate proc_two;

    #[proc_macro_hack]
    use proc_one::one;
    #[proc_macro_hack]
    use proc_two::two;

    fn main() {
    let hi: &'static str = one!("hi");

    assert_eq!("hi", hi);
    }

    我不明白为什么可执行文件中的调用是模棱两可的,lib 2和3不相互依赖。这是完整的错误:
    error[E0659]: `proc_macro_call` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)
    --> src\main.rs:10:1
    |
    10 | #[proc_macro_hack]
    | ^^^^^^^^^^^^^^^^^^ ambiguous name
    ...
    14 | let hi: &'static str = one!("hi");
    | ---------- in this macro invocation
    |
    note: `proc_macro_call` could refer to the macro defined here
    --> src\main.rs:11:15
    |
    11 | use proc_two::two;
    | ^^^
    ...
    14 | let hi: &'static str = one!("hi");
    | ---------- in this macro invocation
    note: `proc_macro_call` could also refer to the macro defined here
    --> src\main.rs:9:15
    |
    9 | use proc_one::one;
    | ^^^
    ...
    14 | let hi: &'static str = one!("hi");
    | ---------- in this macro invocation
    = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

    最佳答案

    根据proc_macro_hack documentation 不支持嵌套调用:

    By default, nested invocations are not supported i.e. the code emitted by a proc-macro-hack macro invocation cannot contain recursive calls to the same proc-macro-hack macro nor calls to any other proc-macro-hack macros. Use proc-macro-nested if you require support for nested invocations.



    因此,您标记的代码才是真正的问题:
    let x = quote! {
    two!(#r) // This is the problem
    };

    建议您查看 proc-macro-nested“如果您需要对嵌套调用的支持”。

    关于rust - 在其他proc宏内调用proc宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61866669/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com