Chapter 10

Macros

Rewrite Rules

The grammar of a macro definition is define macro macro-definition. For details see Appendix A, BNF.

If the optional name at the end of a macro-definition is present, it must be the same name that appears at the beginning of the macro-definition.

The kind of macro being defined, and thus the Dylan grammar production that this macro extends, is determined by which kind of rules appear in the macro's main-rule-set.

The name preceding the main-rule-set is the name of the binding whose value is this macro. It must be consistent with each left-hand side of the main-rule-set. It can be any name, even a reserved word or backslash followed by an operator. For statement and function macros this name must be the same as the name that appears as the first token in each main-rule-set pattern. For definition macros this name must be the same as the name in the xxx-style-definition-rule with the suffix -definer added.

A name can belong to more than one of the lexical categories begin-word, function-word, define-body-word, and define-list-word. A name cannot belong to both begin-word and function-word. A name cannot belong to both define-body-word and define-list-word.

For simplicity of documentation, the xxx-style-definition-rule productions are written ambiguously. The name in the left-hand side of the rule must be the name immediately following define macro with the -definer suffix removed, not an arbitrary name, which would be ambiguous with modifier.

The general idea is that the main-rule-set is an ordered sequence of rewrite rules. Macro expansion tests the macro call against each left-hand side in turn until one matches. The corresponding right-hand side supplies the new construct to replace the macro call. The left- and right-hand sides can contain pattern variables. The portion of the macro call that matches a particular pattern variable on the left replaces each occurrence of that pattern variable on the right. It is an error for the right-hand side of a rule to contain a pattern variable that does not appear on the left-hand side of the same rule.

If none of the left-hand sides match, the macro call is invalid. If more than one left-hand side matches, the first matching rule is used. Note that (as described in the next section) a pattern variable with a wildcard constraint can match an empty portion of the macro call. A comma or a semicolon followed by a pattern variable with a wildcard constraint also can match an empty portion of the macro call. Do not assume that only an empty pattern can match an empty input. In general when writing recursive rewrite rules it is better to put the base case first, before the inductive cases, in case an inductive case rewrite rule might match a base case input.

The punctuation marks ?, ??, and ?= used in patterns and templates are customarily written without any whitespace following them.