One of the nice results of syntax-rules
dealing with the subtle points
of identifiers and scope is that things works fine even when we “go up a
level”. For example, the short define-syntax-rule
form that we’ve seen
is itself a defined as a simple macro:
In fact, this is very similar to something that we have already seen:
the rewrite
form that we have used in Schlac is implemented in just
this way. The only difference is that rewrite
requires an actual =>
token to separate the input pattern from the output template. If we just
use it in a syntax rule:
it won’t work. Racket treats the above =>
just like any identifier,
which in this case acts as a pattern variable which matches anything.
The solution to this is to list the =>
as a keyword which is expected
to appear in the macro use as-is — and that’s what the mysterious ()
of syntax-rules
is used for: any identifier listed there is taken to
be such a keyword. This makes the following version
do what we want and throw a syntax error unless rewrite
is used with
an actual =>
in the proper place.
PLAI §37 (has some examples)
This is not really lazy evaluation, but it gets close, and provides the core useful property of easy-to-use infinite lists.
Using it:
Actually, all Scheme implementations come with a generalized tool for
(local) laziness: a delay
form that delays computation of its body
expression, and a force
function that forces such promises. Here is a
naive implementation of this:
Proper definitions of delay
/force
cache the result — and practical
ones can get pretty complex, for example, in order to allow tail calls
via promises.
Syntax transformations can be recursive. For example, we have seen how
let*
can be implemented by a transformation that uses two rules, one
of which expands to another use of let*
:
When Racket expands a let*
expression, the result may contain a new
let*
which needs extending as well. An important implication of this
is that recursive macros are fine, as long as the recursive case is
using a smaller expression. This is just like any form of recursion
(or loop), where you need to be looping over a well-founded
set of
values — where each iteration uses a new value that is closer to some
base case.
For example, consider the following macro:
It seems like this is a good implementation of a while
loop — after
all, if you were to implement it as a function using thunks, you’d write
very similar code:
But if you look at the nested while
form in the transformation rule,
you’ll see that it is exactly the same as the input form. This means
that this macro can never be completely expanded — it specifies
infinite code! In practice, this makes the (Racket) compiler loop
forever, consuming more and more memory. This is unlike, for example,
the recursive let*
rule which uses one less binding-value pair than
specified as its input.
The reason that the function version of while
is fine is that it
iterates using the same code, and the condition thunk will depend on
some state that converges to a base case (usually the body thunk will
perform some side-effects that makes the loop converge). But in the
macro case there is no evaluation happening, if the transformed syntax
contains the same input pattern, we end up having a macro that expands
infinitely.
The correct solution for a while
macro is therefore to use plain
recursion using a local recursive function:
A popular way to deal with macros like this that revolve around a specific control flow is to separate them into a function that uses thunks, and a macro that does nothing except wrap input expressions as thunks. In this case, we get this solution:
Here is an implementation of a macro that does a simple arithmetic loop:
(Note that this is not complete code: it suffers from the usual problem
of multiple evaluations of the n
expression. We’ll deal with it soon.)
This macro combines both control flow and lexical scope. Control flow is
specified by the loop (done, as usual in Racket, as a tail-recursive
function) — for example, it determines how code is iterated, and it
also determines what the for
form will evaluate to (it evaluates to
whatever when
evaluates to, the void value in this case). Scope is
also specified here, by translating the code to a function — this code
makes x
have a scope that covers the body so this is valid:
but it also makes the boundary expression n
be in this scope, making
this:
valid. In addition, while evaluating the condition on each iteration might be desirable, in most cases it’s not — consider this example:
This is easily solved by using a let
to make the expression evaluate
just once:
which makes the previous use result in a “reference to undefined identifier: i
” error.
Furthermore, the fact that we have a hygienic macro system means that it
is perfectly fine to use nested for
expressions:
The transformation is, therefore, completely specifying the semantics of this new form.
Extending this syntax is easy using multiple transformation rules —
for example, say that we want to extend it to have a step
optional
keyword. The standard idiom is to have the step-less pattern translated
into one that uses step 1
:
Usually, you should remember that syntax-rules
tries the patterns one
by one until a match is found, but in this case there is no problems
because the keywords make the choice unambiguous:
We can even extend it to do a different kind of iteration, for example, iterate over list:
At this point it’s clear that macros are a powerful language feature
that makes it relatively easy to implement new features, making it a
language that is easy to use as a tool for quick experimentation with
new language features. As an example of a practical feature rather than
a toy, let’s see how we can implement Python’s list comprehenions.
These are expressions that conveniently combine map
, filter
, and
nested uses of both.
First, a simple implementation that uses only the map
feature:
It is a good exercise to see how everything that we’ve seen above plays
a role here. For example, how we get the ID
to be bound in EXPR
.
Next, add a condition expression with an if
keyword, and implemented
using a filter
:
Again, go over it and see how the binding structure makes the identifier
available in both expressions. Note that since we’re just playing around
we’re not paying too much attention to performance etc. (For example, if
we cared, we could have implemented the if
-less case by not using
filter
at all, or we could implement a filter
that accepts #t
as a
predicate and in that case just returns the list, or even implementing
it as a macro that identifies a (lambda (_) #t)
pattern and expands to
just the list (a bad idea in general).)
The last step: Python’s comprehension accepts multiple for
-in
s for
nested loops, possibly with if
filters at each level:
A collection of examples that I found in the Python docs and elsewhere, demonstrating all of these:
syntax-rules
MacrosAs we’ve seen, using syntax-rules
solves many of the problems of
macros, but it comes with a high price tag: the macros are “just”
rewrite rules. As rewrite rules they’re pretty sophisticated, but it
still loses a huge advantage of what we had with define-macro
— the
macro code is no longer Racket code but a simple language of rewrite
rules.
There are two big problems with this which we will look into now.
(DrRacket’s macro stepper tool can be very useful in clarifying these
examples.) The first problem is that in some cases we want to perform
computations at the macro level — for example, consider a repeat
macro that needs to expand like this:
With a syntax-rules
macro we can match over specific integers, but we
just cannot do this with any integer. Note that this specific case can
be done better via a function — better by not replicating the
expression:
or even better, assuming the above for
is already implemented:
But still, we want to have the ability to do such computation. A
similar, and perhaps better example, is better error reporting. For
example, the above for
implementation blindly expands its input, so:
we get a bad error message in terms of lambda
, which is breaking
abstraction (it comes from the expansion of for
, which is an
implementation detail), and worse — it is an error about something
that the user didn’t write.
Yet another aspect of this problem is that sometimes we need to get
creative solutions where it would be very simple to write the
corresponding Racket code. For example, consider the problem of writing
a rev-app
macro — (rev-app F E …) should evaluate to a function
similar to (F E …), except that we want the evaluation to go from
right to left instead of the usual left-to-right that Racket does. This
code is obviously very broken:
because it generates a malformed let
form — there is no way for
the macro expander to somehow know that the reverse
should happen at
the transformation level. In this case, we can actually solve this using
a helper macro to do the reversing:
There are still problems with this — it complains about x ...
because there is a single x
there rather than a sequence of them; and
even if it did somehow work, we also need the x
s in that last line in
the original order rather than the reversed one. So the solution is
complicated by collecting new x
s while reversing — and since we need
them in both orders, we’re going to collect both orders:
So, this worked, but in this case the simplicity of the syntax-rules
rewrite language worked against us, and made a very inconvenient
solution. This could have been much easier if we could just write a
“meta-level” reverse, and a use of map
to generate the names.
… And all of that was just the first problem. The second one is even
harder: syntax-rules
is designed to avoid all name captures, but
what if we want to break hygiene? There are some cases where you want
a macro that “injects” a user-visible identifier into its result. The
most common (and therefore the classic) example of this is an anaphoric
if
macro, that binds it
to the result of the test (which can be any
value, not just a boolean):
which we want to turn to:
The obvious definition of `if-it’ doesn’t work:
The reason it doesn’t work should be obvious now — it is designed to
avoid the it
that the macro introduced from interfering with the it
that the user code uses.
Next, we’ll see Racket’s “low level” macro system, which can later be used to solve these problems.