#macro-rules #crate #macro #proc-macro

proc-macro-crate

Replacement for crate (macro_rules keyword) in proc-macros

6 releases

0.1.5 Jul 10, 2020
0.1.4 May 9, 2019
0.1.3 Feb 11, 2019

#7 in Procedural macros

Download history 30405/week @ 2020-04-18 30428/week @ 2020-04-25 31538/week @ 2020-05-02 35232/week @ 2020-05-09 30175/week @ 2020-05-16 32233/week @ 2020-05-23 33024/week @ 2020-05-30 35599/week @ 2020-06-06 34903/week @ 2020-06-13 29443/week @ 2020-06-20 31625/week @ 2020-06-27 35858/week @ 2020-07-04 38043/week @ 2020-07-11 35640/week @ 2020-07-18 37131/week @ 2020-07-25 37033/week @ 2020-08-01

136,769 downloads per month
Used in 586 crates (40 directly)

Apache-2.0/MIT

12KB
164 lines

proc-macro-crate

Build Status

Providing support for $crate in procedural macros.

Introduction

In macro_rules! $crate is used to get the path of the crate where a macro is declared in. In procedural macros there is currently no easy way to get this path. A common hack is to import the desired crate with a know name and use this. However, with rust edition 2018 and dropping extern crate declarations from lib.rs, people start to rename crates in Cargo.toml directly. However, this breaks importing the crate, as the proc-macro developer does not know the renamed name of the crate that should be imported.

This crate provides a way to get the name of a crate, even if it renamed in Cargo.toml. For this purpose a single function crate_name is provided. This function needs to be called in the context of a proc-macro with the name of the desired crate. CARGO_MANIFEST_DIR will be used to find the current active Cargo.toml and this Cargo.toml is searched for the desired crate. The returned name of crate_name is either the given original rename (crate not renamed) or the renamed name.

Example

use quote::quote;
use syn::Ident;
use proc_macro2::Span;
use proc_macro_crate::crate_name;

fn import_my_crate() {
    let name = crate_name("my-crate").expect("my-crate is present in `Cargo.toml`");
    let ident = Ident::new(&name, Span::call_site());
    quote!( extern crate #ident as my_crate_known_name );
}

License

Licensed under either of

at your option.

License: Apache-2.0/MIT

Dependencies

~380–510KB
~11K SLoC