twitu
twitu

Reputation: 625

Exporting declarative macro that uses functions defined in crate

I'm trying to export a macro that uses from some functions defined in the crate. Something like this for e.g in a crate named a_macro_a_day

// lib.rs

pub fn a() {}

#[macro_export]
macro_rules! impl_helper_funcs {
  use crate::a; // error unresolved import
  use a_macro_a_day::a; // error unresolved import
  fn b() {
    ...
    a() // call imported a here
  }
}

I've tried using various combinations of use to import a but the error always shows up the macro definition saying unresolved import crate or unresolved import a_macro_a_day.

I would prefer not to go with the procedural macro way as this is simply trying to reduce code duplication. Is there any way to export a macro that imports local (but public) functions?

Upvotes: 4

Views: 1197

Answers (1)

Sprite
Sprite

Reputation: 3763

In declarative macros, you should use $crate to access items in the current crate. And your macro declaration is missing a match and a body.

Try this:

// lib.rs

pub fn a() {}

#[macro_export]
macro_rules! impl_helper_funcs {
 // vvvvvvv add this
    () => {
        use $crate::a;
        //  ^ add this
        fn b() {
            // ...
            a() // call imported a here
        }
    };
 // ^^ add this
}

Upvotes: 7

Related Questions