2 Declarative macros

 

This chapter covers

  • Writing declarative macros
  • Avoiding boilerplate and duplication, implementing newtypes, writing simple domain specific languages, and composing functions
  • Understanding the lazy_static crate

We will start this book in easy mode with declarative macros. These macros have a syntax that will immediately remind you of pattern matching, with a combination of matchers and transcribers. The matchers contain what you want to match against; the transcriber has the code you will generate when you find that match. It’s just that simple.

2.1 Creating vectors

But wait, this is an example-driven book! That means we should drag a first example into this. vec! is used in several beginner’s explanations of declarative macros. We will go through a simplified implementation that shows how the aforementioned matchers and transcribers work together to generate the correct kind of code output for any given situation.

2.1.1 Syntax basics

2.1.2 Declaring and exporting declarative macros

2.1.3 The first matcher explained

2.1.4 Nonemtpy matchers

2.2 Use cases

2.2.1 Varargs and default arguments

2.2.2 More than one way to expand code

2.2.3 Newtypes

2.2.4 DSLs

2.2.5 Composing is easy

2.2.6 Currying, on the other hand . . .

2.2.7 Hygiene is something to consider as well

2.3 From the real world

2.4 Exercises

Summary