]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/macros/dsl.md
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / macros / dsl.md
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
9 an expression and have the output printed to console.
10
11 ```rust,editable
12 macro_rules! calculate {
13 (eval $e:expr) => {
14 {
15 let val: usize = $e; // Force types to be integers
16 println!("{} = {}", stringify!{$e}, val);
17 }
18 };
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:
33
34 ```txt
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).
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 `[]`.