David Tolnay | ad8c862 | 2018-01-04 11:47:09 -0800 | [diff] [blame] | 1 | An example of parsing a custom syntax within a `functionlike!(...)` procedural |
| 2 | macro. Demonstrates how to trigger custom warnings and error messages on |
| 3 | individual tokens of the input. |
| 4 | |
| 5 | - [`lazy-static/src/lib.rs`](lazy-static/src/lib.rs) |
| 6 | - [`example/src/main.rs`](example/src/main.rs) |
| 7 | |
| 8 | The library implements a `lazy_static!` macro similar to the one from the real |
| 9 | [`lazy_static`](https://docs.rs/lazy_static/1.0.0/lazy_static/) crate on |
| 10 | crates.io. |
| 11 | |
| 12 | ```rust |
David Tolnay | 636afa1 | 2018-01-04 11:48:32 -0800 | [diff] [blame] | 13 | lazy_static! { |
David Tolnay | ad8c862 | 2018-01-04 11:47:09 -0800 | [diff] [blame] | 14 | static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); |
| 15 | } |
| 16 | ``` |
| 17 | |
| 18 | Compile and run the example by doing `cargo run` in the directory of the |
| 19 | `example` crate. |
| 20 | |
| 21 | The implementation shows how to trigger custom warnings and error messages on |
| 22 | the macro input. For example if you try adding an uncreatively named `FOO` lazy |
| 23 | static, the macro will scold you with the following warning. |
| 24 | |
| 25 | ``` |
| 26 | warning: come on, pick a more creative name |
| 27 | --> src/main.rs:10:16 |
| 28 | | |
| 29 | 10 | static ref FOO: String = "lazy_static".to_owned(); |
| 30 | | ^^^ |
| 31 | ``` |
| 32 | |
David Tolnay | 636afa1 | 2018-01-04 11:48:32 -0800 | [diff] [blame] | 33 | And if you try to lazily initialize `() = ()`, the macro will outright refuse to |
| 34 | compile it for you. |
David Tolnay | ad8c862 | 2018-01-04 11:47:09 -0800 | [diff] [blame] | 35 | |
| 36 | ``` |
| 37 | error: I can't think of a legitimate use for lazily initializing the value `()` |
| 38 | --> src/main.rs:10:27 |
| 39 | | |
| 40 | 10 | static ref UNIT: () = (); |
| 41 | | ^^ |
| 42 | ``` |