]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/macros/dsl.md
New upstream version 1.76.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / macros / dsl.md
CommitLineData
2c00a5a8
XL
1# Domain Specific Languages (DSLs)
2
3A DSL is a mini "language" embedded in a Rust macro. It is completely valid
4Rust because the macro system expands into normal Rust constructs, but it looks
5like a small language. This allows you to define concise or intuitive syntax for
6some special functionality (within bounds).
7
8Suppose that I want to define a little calculator API. I would like to supply
48663c56 9an expression and have the output printed to console.
2c00a5a8
XL
10
11```rust,editable
12macro_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
21fn 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
32Output:
0531ce1d
XL
33
34```txt
2c00a5a8
XL
351 + 2 = 3
36(1 + 2) * (3 / 4) = 0
37```
38
39This was a very simple example, but much more complex interfaces have been
40developed, such as [`lazy_static`](https://crates.io/crates/lazy_static) or
41[`clap`](https://crates.io/crates/clap).
532ac7d7
XL
42
43Also, note the two pairs of braces in the macro. The outer ones are
44part of the syntax of `macro_rules!`, in addition to `()` or `[]`.