]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # Domain Specific Languages (DSLs) |
2 | ||
3 | A DSL is a mini "language" embedded in a Rust macro. It is completely valid | |
4 | Rust because the macro system expands into normal Rust constructs, but it looks | |
5 | like a small language. This allows you to define concise or intuitive syntax for | |
6 | some special functionality (within bounds). | |
7 | ||
8 | Suppose that I want to define a little calculator API. I would like to supply | |
48663c56 | 9 | an expression and have the output printed to console. |
2c00a5a8 XL |
10 | |
11 | ```rust,editable | |
12 | macro_rules! calculate { | |
923072b8 | 13 | (eval $e:expr) => { |
2c00a5a8 | 14 | { |
4b012472 | 15 | let val: usize = $e; // Force types to be unsigned integers |
2c00a5a8 XL |
16 | println!("{} = {}", stringify!{$e}, val); |
17 | } | |
923072b8 | 18 | }; |
2c00a5a8 XL |
19 | } |
20 | ||
21 | fn main() { | |
22 | calculate! { | |
23 | eval 1 + 2 // hehehe `eval` is _not_ a Rust keyword! | |
24 | } | |
25 | ||
26 | calculate! { | |
27 | eval (1 + 2) * (3 / 4) | |
28 | } | |
29 | } | |
30 | ``` | |
31 | ||
32 | Output: | |
0531ce1d XL |
33 | |
34 | ```txt | |
2c00a5a8 XL |
35 | 1 + 2 = 3 |
36 | (1 + 2) * (3 / 4) = 0 | |
37 | ``` | |
38 | ||
39 | This was a very simple example, but much more complex interfaces have been | |
40 | developed, such as [`lazy_static`](https://crates.io/crates/lazy_static) or | |
41 | [`clap`](https://crates.io/crates/clap). | |
532ac7d7 XL |
42 | |
43 | Also, note the two pairs of braces in the macro. The outer ones are | |
44 | part of the syntax of `macro_rules!`, in addition to `()` or `[]`. |