mindTree
mindTree

Reputation: 946

Is it possible to "namespace" Rust macros?

I've been writing a lot of macros in a recent project. I was just thinking about how incredibly useful Rust's module system is for managing "namespaces", and I began to wonder:

  1. Why was it decided that macros shouldn't also abide by the module system? Is it because of the general rarity of macro use? Or because of some other fundamental compilation process that restricts it?

  2. Is it at all possible to "namespace" Rust macros?

This question doesn't arise from a dire need, but more from a general curiosity :-)

Upvotes: 16

Views: 3370

Answers (1)

huon
huon

Reputation: 102066

Macro expansion runs before "the module system", and so name resolution/searching isn't really set up at that point. Also, macros can actually create whole modules, so it's not necessarily possible to have the entire resolution system working. This is also part of the reason that macros are run in declaration order (the only place in Rust where this really matters), so that there's a predictable ordering for names and macros to be defined.

So, there's some technical problems. However it would be really nice to at least have some form of namespaced macros.

It would definitely be possible (and is essentially necessary) to have namespacing between crates, that is, if crates a and b both define foo!, then the following should be able to be made legal

#![feature(phase)]

#[phase(plugin)] extern crate a;
#[phase(plugin)] extern crate b;

fn main() {
    a::foo!();
    b::foo!();
}

This isn't implemented yet, but we will hopefully have something of this form eventually.

Is it at all possible to "namespace" Rust macros?

In summary: no, except via C-namespacing: mylib_mymodule_mymacro!().

Upvotes: 14

Related Questions