Domain Specific Languages (DSLs)

A DSL is a mini “language” embedded in a Rust macro. It is completely valid
Rust because the macro system expands into normal Rust constructs, but it looks
like a small language. This allows you to define concise or intuitive syntax for
some special functionality (within bounds).

Suppose that I want to define a little calculator API. I would like to supply
an expression an have the output printed to console.

  1. macro_rules! calculate {
  2. (eval $e:expr) => {{
  3. {
  4. let val: usize = $e; // Force types to be integers
  5. println!("{} = {}", stringify!{$e}, val);
  6. }
  7. }};
  8. }
  9. fn main() {
  10. calculate! {
  11. eval 1 + 2 // hehehe `eval` is _not_ a Rust keyword!
  12. }
  13. calculate! {
  14. eval (1 + 2) * (3 / 4)
  15. }
  16. }

Output:

  1. 1 + 2 = 3
  2. (1 + 2) * (3 / 4) = 0

This was a very simple example, but much more complex interfaces have been
developed, such as lazy_static or
clap.