macro_const/
lib.rs

1#![no_std]
2
3/*!
4Creates corresponding macro definitions for constants, allowing the value of the constants
5to be used in the context of other macros.
6
7# Examples
8
9```ignore
10macro_const! {
11    const FILE: &str = "message.txt";
12}
13
14println!("Contents: {}", include_str!(FILE!()));
15println!("File: {}", FILE);
16```
17
18Doc comments can be added as well. The documentation for the constant will be added to the
19generated macro verbatim. To export the generated macro, simply add the `#[macro_export]`
20attribute to the constant definition. 
21
22```
23# #[macro_use]
24# extern crate macro_const;
25# fn main() {
26macro_const! {
27    /// The API base URL.
28    #[macro_export]
29    pub const BASE_URL: &str = "https://myapi.io/";
30
31    /// The current supported API version.
32    pub const API_VERSION: &str = "v1";
33}
34
35assert_eq!("https://myapi.io/v1", concat!(BASE_URL!(), API_VERSION!()));
36# }
37```
38*/
39
40/// Generates corresponding macros for constants that evaluate to the same values as the constants.
41#[macro_export]
42macro_rules! macro_const {
43    ($($(#[$attr:meta])* $vis:vis const $name:ident : $type:ty = $value:expr ;)+) => {
44        $(
45            #[allow(unused_attributes)]
46            $( #[$attr] )* $vis const $name : $type = $value;
47
48            #[allow(unused_attributes)]
49            $( #[$attr] )*
50            macro_rules! $name {
51                () => {
52                    $value
53                }
54            }
55        )+
56    };
57}