Lodin
Lodin

Reputation: 2068

How to use constructs defined in module in exporting macro implicitly

Trying to export a macro from module. Macro generates structure implementing some traits defined in module. Is there a way to get macro without importing that traits manually?

// src/lib.rs
#![crate_name="macro_test"]
#![crate_type="lib"]
#![crate_type="rlib"]

pub trait B<T> where T: Copy {
    fn new(x: T) -> Self;
}

#[macro_export]
macro_rules! test {
    ( $n:ident ) => {
        struct $n<T> where T: Copy {
            x: T
        }

        impl<T> B<T> for $n<T> where T: Copy {
            fn new(x: T) -> Self {
                $n { x: x }
            }
        }
    } 
}

// tests/test_simple.rs
#[macro_use]
extern crate macro_test;

test!(Test);

#[test]
fn test_macro() {
    let a = Test::<i32>::new(1);
}

In that case I get an error:

<macro_test macros>:2:54: 2:61 error: use of undeclared trait name `B` [E0405]
<macro_test macros>:2 struct $ n < T > where T : Copy { x : T } impl < T > B < T > for $ n < T >

If I rewrite the trait implementation with $crate variable:

impl<T> $crate::B<T> for $n<T> where T: Copy {

error message changes to next:

tests\test_simple.rs:8:13: 8:29 error: no associated item named `new` found for type `Test<i32>` in the current scope
tests\test_simple.rs:8     let a = Test::<i32>::new(1);
                               ^~~~~~~~~~~~~~~~
tests\test_simple.rs:8:13: 8:29 help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
tests\test_simple.rs:8:13: 8:29 help: candidate #1: use `macro_test::B`

Why does it happen?

Upvotes: 0

Views: 275

Answers (1)

DK.
DK.

Reputation: 59005

Because you can't call trait methods without useing the trait. That's got nothing to do with macros—it's just a standard rule in Rust.

Maybe you want the macro to generate an inherent impl instead? i.e.

impl<T> $n<T> where T: Copy {
    pub fn new(x: T) -> Self {
        $n { x: x }
    }
}

instead of what you have currently.

Upvotes: 2

Related Questions