Rust, practiced: DSLs as Macros

What is a DSL?

DSL is an acronym for Domain-Specific Language. A DSL is any language that is packaged as part of another language. An example of a common DSL is SQL. SQL is a language for constructing queries into a relational database. Most popular programming languages have packages for connecting to databases and for constructing SQL queries onto those databases.

What does Rust offer for DSLs?

Rust offers a macro system that checks and compiles near-arbitrary syntax. Code sent to a Rust Macro must pass the Rust lexer, but the DSL code is not required to pass the Rust parser. This means that as long as code has closing brackets and parentheses for every opening bracket or parenthese, then most syntax will be accepted. This means that with very little work, most DSL languages can be parsed as part of the Rust compilation process. Syntax Error reporting can be included as a first-class Rust Syntax Error.

What does a Rust DSL look like?

Below we use a Rust library that implements a SQL query planner as a macro.

let mut rows = sql::query!(SELECT * FROM users WHERE email = ?)
    .fetch(&mut conn);