Macros
======

At its best, programming in Lisp is an iterative process of building up a language appropriate to the problem at hand, and then solving the problem in that language. Defining new procedures is part of that, but Lisp also allows the user to extend its syntax, with its famous macros.

Macros are syntactic extensions which cause the expression that they appear in to be transformed in some way before being evaluated. In expressions that are intended for macro transformation, the identifier that names the relevant macro must appear as the first element, like this:

     (MACRO-NAME MACRO-ARGS ...)

Macro expansion is a separate phase of evaluation, run before code is interpreted or compiled. A macro is a program that runs on programs, translating an embedded language into core Scheme (These days such embedded languages are often referred to as embedded domain-specific languages, or EDSLs.).

Defining Macros
---------------

A macro is a binding between a keyword and a syntax transformer. Since it's difficult to discuss define-syntax without discussing the format of transformers, consider the following example macro definition:

     (define-syntax when
       (syntax-rules ()
         ((when condition exp ...)
          (if condition
              (begin exp ...)))))

     (when #t
       (display "hey ho\n")
       (display "let's go\n"))
     -| hey ho
     -| let's go

In this example, the when binding is bound with define-syntax. Syntax transformers are discussed in more depth in Syntax Rules and Syntax Case.

 -- Syntax: define-syntax keyword transformer
     Bind KEYWORD to the syntax transformer obtained by evaluating TRANSFORMER.

     After a macro has been defined, further instances of KEYWORD in Scheme source code will invoke the syntax transformer defined by TRANSFORMER.

One can also establish local syntactic bindings with let-syntax.

 -- Syntax: let-syntax ((keyword transformer) ...) exp1 exp2 ...
     Bind each KEYWORD to its corresponding TRANSFORMER while expanding EXP1 EXP2 ....

     A let-syntax binding only exists at expansion-time.

          (let-syntax ((unless
                        (syntax-rules ()
                          ((unless condition exp ...)
                           (if (not condition)
                               (begin exp ...))))))
            (unless #t
              (primitive-exit 1))
            "rock rock rock")
          => "rock rock rock"

A define-syntax form is valid anywhere a definition may appear: at the top-level, or locally. Just as a local define expands out to an instance of letrec, a local define-syntax expands out to letrec-syntax.

 -- Syntax: letrec-syntax ((keyword transformer) ...) exp1 exp2 ...
     Bind each KEYWORD to its corresponding TRANSFORMER while expanding EXP1 EXP2 ....

     In the spirit of letrec versus let, an expansion produced by TRANSFORMER may reference a KEYWORD bound by the same LETREC-SYNTAX.

          (letrec-syntax ((my-or
                           (syntax-rules ()
                             ((my-or)
                              #t)
                             ((my-or exp)
                              exp)
                             ((my-or exp rest ...)
                              (let ((t exp))
                                (if exp
                                    exp
                                    (my-or rest ...)))))))
            (my-or #f "rockaway beach"))
          => "rockaway beach"

Syntax-rules Macros
-------------------

syntax-rules macros are simple, pattern-driven syntax transformers, with a beauty worthy of Scheme.

 -- Syntax: syntax-rules literals (pattern template)...
     Create a syntax transformer that will rewrite an expression using the rules embodied in the PATTERN and TEMPLATE clauses.

A syntax-rules macro consists of three parts: the literals (if any), the patterns, and as many templates as there are patterns.

When the syntax expander sees the invocation of a syntax-rules macro, it matches the expression against the patterns, in order, and rewrites the expression using the template from the first matching pattern. If no pattern matches, a syntax error is signalled.

Patterns
........

We have already seen some examples of patterns in the previous section: (unless condition exp ...), (my-or exp), and so on. A pattern is structured like the expression that it is to match. It can have nested structure as well, like (let ((var val) ...) exp exp* ...). Broadly speaking, patterns are made of lists, improper lists, vectors, identifiers, and datums. Users can match a sequence of patterns using the ellipsis (...).

Identifiers in a pattern are called literals if they are present in the syntax-rules literals list, and pattern variables otherwise. When building up the macro output, the expander replaces instances of a pattern variable in the template with the matched subexpression.

     (define-syntax kwote
       (syntax-rules ()
         ((kwote exp)
          (quote exp))))
     (kwote (foo . bar))
     => (foo . bar)

An improper list of patterns matches as rest arguments do:

     (define-syntax let1
       (syntax-rules ()
         ((_ (var val) . exps)
          (let ((var val)) . exps))))

However this definition of let1 probably isn't what you want, as the tail pattern EXPS will match non-lists, like (let1 (foo 'bar) . baz). So often instead of using improper lists as patterns, ellipsized patterns are better. Instances of a pattern variable in the template must be followed by an ellipsis.

     (define-syntax let1
       (syntax-rules ()
         ((_ (var val) exp ...)
          (let ((var val)) exp ...))))

This let1 probably still doesn't do what we want, because the body matches sequences of zero expressions, like (let1 (foo 'bar)). In this case we need to assert we have at least one body expression. A common idiom for this is to name the ellipsized pattern variable with an asterisk:

     (define-syntax let1
       (syntax-rules ()
         ((_ (var val) exp exp* ...)
          (let ((var val)) exp exp* ...))))

A vector of patterns matches a vector whose contents match the patterns, including ellipsizing and tail patterns.

     (define-syntax letv
       (syntax-rules ()
         ((_ #((var val) ...) exp exp* ...)
          (let ((var val) ...) exp exp* ...))))
     (letv #((foo 'bar)) foo)
     => foo

Literals are used to match specific datums in an expression, like the use of => and else in cond expressions.

     (define-syntax cond1
       (syntax-rules (=> else)
         ((cond1 test => fun)
          (let ((exp test))
            (if exp (fun exp) #f)))
         ((cond1 test exp exp* ...)
          (if test (begin exp exp* ...)))
         ((cond1 else exp exp* ...)
          (begin exp exp* ...))))

     (define (square x) (* x x))
     (cond1 10 => square)
     => 100
     (let ((=> #t))
       (cond1 10 => square))
     => #<procedure square (x)>

A literal matches an input expression if the input expression is an identifier with the same name as the literal, and both are unbound (Language lawyers probably see the need here for use of literal-identifier=? rather than free-identifier=?, and would probably be correct. Patches accepted.).

If a pattern is not a list, vector, or an identifier, it matches as a literal, with equal?.

     (define-syntax define-matcher-macro
       (syntax-rules ()
         ((_ name lit)
          (define-syntax name
            (syntax-rules ()
             ((_ lit) #t)
             ((_ else) #f))))))

     (define-matcher-macro is-literal-foo? "foo")

     (is-literal-foo? "foo")
     => #t
     (is-literal-foo? "bar")
     => #f
     (let ((foo "foo"))
       (is-literal-foo? foo))
     => #f

The last example indicates that matching happens at expansion-time, not at run-time.

Syntax-rules macros are always used as (MACRO . ARGS), and the MACRO will always be a symbol. Correspondingly, a syntax-rules pattern must be a list (proper or improper), and the first pattern in that list must be an identifier. Incidentally it can be any identifier -- it doesn't have to actually be the name of the macro. Thus the following three are equivalent:

     (define-syntax when
       (syntax-rules ()
         ((when c e ...)
          (if c (begin e ...)))))

     (define-syntax when
       (syntax-rules ()
         ((_ c e ...)
          (if c (begin e ...)))))

     (define-syntax when
       (syntax-rules ()
         ((something-else-entirely c e ...)
          (if c (begin e ...)))))

For clarity, use one of the first two variants. Also note that since the pattern variable will always match the macro itself (e.g., cond1), it is actually left unbound in the template.

Hygiene
.......

syntax-rules macros have a magical property: they preserve referential transparency. When you read a macro definition, any free bindings in that macro are resolved relative to the macro definition; and when you read a macro instantiation, all free bindings in that expression are resolved relative to the expression.

This property is sometimes known as hygiene, and it does aid in code cleanliness. In your macro definitions, you can feel free to introduce temporary variables, without worrying about inadvertently introducing bindings into the macro expansion.

Consider the definition of my-or from the previous section:

     (define-syntax my-or
       (syntax-rules ()
         ((my-or)
          #t)
         ((my-or exp)
          exp)
         ((my-or exp rest ...)
          (let ((t exp))
            (if exp
                exp
                (my-or rest ...))))))

A naive expansion of (let ((t #t)) (my-or #f t)) would yield:

     (let ((t #t))
       (let ((t #f))
         (if t t t)))
     => #f

Which clearly is not what we want. Somehow the t in the definition is distinct from the t at the site of use; and it is indeed this distinction that is maintained by the syntax expander, when expanding hygienic macros.

This discussion is mostly relevant in the context of traditional Lisp macros (see Defmacros), which do not preserve referential transparency. Hygiene adds to the expressive power of Scheme.

Shorthands
..........

One often ends up writing simple one-clause syntax-rules macros. There is a convenient shorthand for this idiom, in the form of define-syntax-rule.

 -- Syntax: define-syntax-rule (keyword . pattern) [docstring] template
     Define KEYWORD as a new syntax-rules macro with one clause.

Cast into this form, our when example is significantly shorter:

     (define-syntax-rule (when c e ...)
       (if c (begin e ...)))

Further Information
...................

For a formal definition of syntax-rules and its pattern language, see Macros (Revised(5) Report on the Algorithmic Language Scheme).

syntax-rules macros are simple and clean, but do they have limitations. They do not lend themselves to expressive error messages: patterns either match or they don't. Their ability to generate code is limited to template-driven expansion; often one needs to define a number of helper macros to get real work done. Sometimes one wants to introduce a binding into the lexical context of the generated code; this is impossible with syntax-rules. Relatedly, they cannot programmatically generate identifiers.

The solution to all of these problems is to use syntax-case if you need its features. But if for some reason you're stuck with syntax-rules, you might enjoy Joe Marshall's syntax-rules Primer for the Merely Eccentric (http://sites.google.com/site/evalapply/eccentric.txt).

Support for the syntax-case System
----------------------------------

syntax-case macros are procedural syntax transformers, with a power worthy of Scheme.

 -- Syntax: syntax-case syntax literals (pattern [guard] exp)...
     Match the syntax object SYNTAX against the given patterns, in order. If a PATTERN matches, return the result of evaluating the associated EXP.

Compare the following definitions of when:

     (define-syntax when
       (syntax-rules ()
         ((_ test e e* ...)
          (if test (begin e e* ...)))))

     (define-syntax when
       (lambda (x)
         (syntax-case x ()
           ((_ test e e* ...)
            #'(if test (begin e e* ...))))))

Clearly, the syntax-case definition is similar to its syntax-rules counterpart, and equally clearly there are some differences. The syntax-case definition is wrapped in a lambda, a function of one argument; that argument is passed to the syntax-case invocation; and the ``return value'' of the macro has a #' prefix.

All of these differences stem from the fact that syntax-case does not define a syntax transformer itself -- instead, syntax-case expressions provide a way to destructure a syntax object, and to rebuild syntax objects as output.

So the lambda wrapper is simply a leaky implementation detail, that syntax transformers are just functions that transform syntax to syntax. This should not be surprising, given that we have already described macros as ``programs that write programs''. syntax-case is simply a way to take apart and put together program text, and to be a valid syntax transformer it needs to be wrapped in a procedure.

Unlike traditional Lisp macros (see Defmacros), syntax-case macros transform syntax objects, not raw Scheme forms. Recall the naive expansion of my-or given in the previous section:

     (let ((t #t))
       (my-or #f t))
     ;; naive expansion:
     (let ((t #t))
       (let ((t #f))
         (if t t t)))

Raw Scheme forms simply don't have enough information to distinguish the first two t instances in (if t t t) from the third t. So instead of representing identifiers as symbols, the syntax expander represents identifiers as annotated syntax objects, attaching such information to those syntax objects as is needed to maintain referential transparency.

 -- Syntax: syntax form
     Create a syntax object wrapping FORM within the current lexical context.

Syntax objects are typically created internally to the process of expansion, but it is possible to create them outside of syntax expansion:

     (syntax (foo bar baz))
     => #<some representation of that syntax>

However it is more common, and useful, to create syntax objects when building output from a syntax-case expression.

     (define-syntax add1
       (lambda (x)
         (syntax-case x ()
           ((_ exp)
            (syntax (+ exp 1))))))

It is not strictly necessary for a syntax-case expression to return a syntax object, because syntax-case expressions can be used in helper functions, or otherwise used outside of syntax expansion itself. However a syntax transformer procedure must return a syntax object, so most uses of syntax-case do end up returning syntax objects.

Here in this case, the form that built the return value was (syntax (+ exp 1)). The interesting thing about this is that within a syntax expression, any appearance of a pattern variable is substituted into the resulting syntax object, carrying with it all relevant metadata from the source expression, such as lexical identity and source location.

Indeed, a pattern variable may only be referenced from inside a syntax form. The syntax expander would raise an error when defining add1 if it found EXP referenced outside a syntax form.

Since syntax appears frequently in macro-heavy code, it has a special reader macro: #'. #'foo is transformed by the reader into (syntax foo), just as 'foo is transformed into (quote foo).

The pattern language used by syntax-case is conveniently the same language used by syntax-rules. Given this, Guile actually defines syntax-rules in terms of syntax-case:

     (define-syntax syntax-rules
       (lambda (x)
         (syntax-case x ()
           ((_ (k ...) ((keyword . pattern) template) ...)
            #'(lambda (x)
                (syntax-case x (k ...)
                  ((dummy . pattern) #'template)
                  ...))))))

And that's that.

Why syntax-case?
................

The examples we have shown thus far could just as well have been expressed with syntax-rules, and have just shown that syntax-case is more verbose, which is true. But there is a difference: syntax-case creates procedural macros, giving the full power of Scheme to the macro expander. This has many practical applications.

A common desire is to be able to match a form only if it is an identifier. This is impossible with syntax-rules, given the datum matching forms. But with syntax-case it is easy:

 -- Scheme Procedure: identifier? syntax-object
     Returns #t iff SYNTAX-OBJECT is an identifier.

     ;; relying on previous add1 definition
     (define-syntax add1!
       (lambda (x)
         (syntax-case x ()
           ((_ var) (identifier? #'var)
            #'(set! var (add1 var))))))

     (define foo 0)
     (add1! foo)
     foo => 1
     (add1! "not-an-identifier") => error

With syntax-rules, the error for (add1! "not-an-identifier") would be something like ``invalid set!''. With syntax-case, it will say something like ``invalid add1!'', because we attach the guard clause to the pattern: (identifier? #'var). This becomes more important with more complicated macros. It is necessary to use identifier?, because to the expander, an identifier is more than a bare symbol.

Note that even in the guard clause, we reference the VAR pattern variable within a syntax form, via #'var.

Another common desire is to introduce bindings into the lexical context of the output expression. One example would be in the so-called ``anaphoric macros'', like aif. Anaphoric macros bind some expression to a well-known identifier, often it, within their bodies. For example, in (aif (foo) (bar it)), it would be bound to the result of (foo).

To begin with, we should mention a solution that doesn't work:

     ;; doesn't work
     (define-syntax aif
       (lambda (x)
         (syntax-case x ()
           ((_ test then else)
            #'(let ((it test))
                (if it then else))))))

The reason that this doesn't work is that, by default, the expander will preserve referential transparency; the THEN and ELSE expressions won't have access to the binding of it.

But they can, if we explicitly introduce a binding via datum->syntax.

 -- Scheme Procedure: datum->syntax for-syntax datum
     Create a syntax object that wraps DATUM, within the lexical context corresponding to the syntax object FOR-SYNTAX.

For completeness, we should mention that it is possible to strip the metadata from a syntax object, returning a raw Scheme datum:

 -- Scheme Procedure: syntax->datum syntax-object
     Strip the metadata from SYNTAX-OBJECT, returning its contents as a raw Scheme datum.

In this case we want to introduce it in the context of the whole expression, so we can create a syntax object as (datum->syntax x 'it), where x is the whole expression, as passed to the transformer procedure.

Here's another solution that doesn't work:

     ;; doesn't work either
     (define-syntax aif
       (lambda (x)
         (syntax-case x ()
           ((_ test then else)
            (let ((it (datum->syntax x 'it)))
              #'(let ((it test))
                  (if it then else)))))))

The reason that this one doesn't work is that there are really two environments at work here -- the environment of pattern variables, as bound by syntax-case, and the environment of lexical variables, as bound by normal Scheme. The outer let form establishes a binding in the environment of lexical variables, but the inner let form is inside a syntax form, where only pattern variables will be substituted. Here we need to introduce a piece of the lexical environment into the pattern variable environment, and we can do so using syntax-case itself:

     ;; works, but is obtuse
     (define-syntax aif
       (lambda (x)
         (syntax-case x ()
           ((_ test then else)
            ;; invoking syntax-case on the generated
            ;; syntax object to expose it to `syntax'
            (syntax-case (datum->syntax x 'it) ()
              (it
                #'(let ((it test))
                    (if it then else))))))))

     (aif (getuid) (display it) (display "none")) (newline)
     -| 500

However there are easier ways to write this. with-syntax is often convenient:

 -- Syntax: with-syntax ((pat val)...) exp...
     Bind patterns PAT from their corresponding values VAL, within the lexical context of EXP....

          ;; better
          (define-syntax aif
            (lambda (x)
              (syntax-case x ()
                ((_ test then else)
                 (with-syntax ((it (datum->syntax x 'it)))
                   #'(let ((it test))
                       (if it then else)))))))

As you might imagine, with-syntax is defined in terms of syntax-case. But even that might be off-putting to you if you are an old Lisp macro hacker, used to building macro output with quasiquote. The issue is that with-syntax creates a separation between the point of definition of a value and its point of substitution.

So for cases in which a quasiquote style makes more sense, syntax-case also defines quasisyntax, and the related unsyntax and unsyntax-splicing, abbreviated by the reader as #`, #,, and #,@, respectively.

For example, to define a macro that inserts a compile-time timestamp into a source file, one may write:

     (define-syntax display-compile-timestamp
       (lambda (x)
         (syntax-case x ()
           ((_)
            #`(begin
               (display "The compile timestamp was: ")
               (display #,(current-time))
               (newline))))))

Readers interested in further information on syntax-case macros should see R. Kent Dybvig's excellent The Scheme Programming Language, either edition 3 or 4, in the chapter on syntax. Dybvig was the primary author of the syntax-case system. The book itself is available online at http://scheme.com/tspl4/.

Syntax Transformer Helpers
--------------------------

As noted in the previous section, Guile's syntax expander operates on syntax objects.  Procedural macros consume and produce syntax objects. This section describes some of the auxiliary helpers that procedural macros can use to compare, generate, and query objects of this data type.

 -- Scheme Procedure: bound-identifier=? a b
     Return #t iff the syntax objects A and B refer to the same lexically-bound identifier.

 -- Scheme Procedure: free-identifier=? a b
     Return #t iff the syntax objects A and B refer to the same free identifier.

 -- Scheme Procedure: generate-temporaries ls
     Return a list of temporary identifiers as long as LS is long.

 -- Scheme Procedure: syntax-source x
     Return the source properties that correspond to the syntax object X.  See Source Properties, for more information.

Guile also offers some more experimental interfaces in a separate module.  As was the case with the Large Hadron Collider, it is unclear to our senior macrologists whether adding these interfaces will result in awesomeness or in the destruction of Guile via the creation of a singularity.  We will preserve their functionality through the 2.0 series, but we reserve the right to modify them in a future stable series, to a more than usual degree.

     (use-modules (system syntax))

 -- Scheme Procedure: syntax-module id
     Return the name of the module whose source contains the identifier ID.

 -- Scheme Procedure: syntax-local-binding id
     Resolve the identifer ID, a syntax object, within the current lexical environment, and return two values, the binding type and a binding value.  The binding type is a symbol, which may be one of the following:

     lexical
          A lexically-bound variable.  The value is a unique token (in the sense of eq?) identifying this binding.

     macro
          A syntax transformer, either local or global.  The value is the transformer procedure.

     pattern-variable
          A pattern variable, bound via syntax-case.  The value is an opaque object, internal to the expander.

     displaced-lexical
          A lexical variable that has gone out of scope.  This can happen if a badly-written procedural macro saves a syntax object, then attempts to introduce it in a context in which it is unbound.  The value is #f.

     global
          A global binding.  The value is a pair, whose head is the symbol, and whose tail is the name of the module in which to resolve the symbol.

     other
          Some other binding, like lambda or other core bindings.  The value is #f.

     This is a very low-level procedure, with limited uses.  One case in which it is useful is to build abstractions that associate auxiliary information with macros:

          (define aux-property (make-object-property))
          (define-syntax-rule (with-aux aux value)
            (let ((trans value))
              (set! (aux-property trans) aux)
              trans))
          (define-syntax retrieve-aux
            (lambda (x)
              (syntax-case x ()
                ((x id)
                 (call-with-values (lambda () (syntax-local-binding #'id))
                   (lambda (type val)
                     (with-syntax ((aux (datum->syntax #'here
                                                       (and (eq? type 'macro)
                                                            (aux-property val)))))
                       #''aux)))))))
          (define-syntax foo
            (with-aux 'bar
              (syntax-rules () ((_) 'foo))))
          (foo)
          => foo
          (retrieve-aux foo)
          => bar

     syntax-local-binding must be called within the dynamic extent of a syntax transformer; to call it otherwise will signal an error.

 -- Scheme Procedure: syntax-locally-bound-identifiers id
     Return a list of identifiers that were visible lexically when the identifier ID was created, in order from outermost to innermost.

     This procedure is intended to be used in specialized procedural macros, to provide a macro with the set of bound identifiers that the macro can reference.

     As a technical implementation detail, the identifiers returned by syntax-locally-bound-identifiers will be anti-marked, like the syntax object that is given as input to a macro.  This is to signal to the macro expander that these bindings were present in the original source, and do not need to be hygienically renamed, as would be the case with other introduced identifiers.  See the discussion of hygiene in section 12.1 of the R6RS, for more information on marks.

          (define (local-lexicals id)
            (filter (lambda (x)
                      (eq? (syntax-local-binding x) 'lexical))
                    (syntax-locally-bound-identifiers id)))
          (define-syntax lexicals
            (lambda (x)
              (syntax-case x ()
                ((lexicals) #'(lexicals lexicals))
                ((lexicals scope)
                 (with-syntax (((id ...) (local-lexicals #'scope)))
                   #'(list (cons 'id id) ...))))))

          (let* ((x 10) (x 20)) (lexicals))
          => ((x . 10) (x . 20))

Lisp-style Macro Definitions
----------------------------

The traditional way to define macros in Lisp is very similar to procedure definitions. The key differences are that the macro definition body should return a list that describes the transformed expression, and that the definition is marked as a macro definition (rather than a procedure definition) by the use of a different definition keyword: in Lisp, defmacro rather than defun, and in Scheme, define-macro rather than define.

Guile supports this style of macro definition using both defmacro and define-macro.  The only difference between them is how the macro name and arguments are grouped together in the definition:

     (defmacro NAME (ARGS ...) BODY ...)

is the same as

     (define-macro (NAME ARGS ...) BODY ...)

The difference is analogous to the corresponding difference between Lisp's defun and Scheme's define.

Having read the previous section on syntax-case, it's probably clear that Guile actually implements defmacros in terms of syntax-case, applying the transformer on the expression between invocations of syntax->datum and datum->syntax. This realization leads us to the problem with defmacros, that they do not preserve referential transparency. One can be careful to not introduce bindings into expanded code, via liberal use of gensym, but there is no getting around the lack of referential transparency for free bindings in the macro itself.

Even a macro as simple as our when from before is difficult to get right:

     (define-macro (when cond exp . rest)
       `(if ,cond
            (begin ,exp . ,rest)))

     (when #f (display "Launching missiles!\n"))
     => #f

     (let ((if list))
       (when #f (display "Launching missiles!\n")))
     -| Launching missiles!
     => (#f #<unspecified>)

Guile's perspective is that defmacros have had a good run, but that modern macros should be written with syntax-rules or syntax-case. There are still many uses of defmacros within Guile itself, but we will be phasing them out over time. Of course we won't take away defmacro or define-macro themselves, as there is lots of code out there that uses them.

Identifier Macros
-----------------

When the syntax expander sees a form in which the first element is a macro, the whole form gets passed to the macro's syntax transformer. One may visualize this as:

     (define-syntax foo foo-transformer)
     (foo ARG...)
     ;; expands via
     (foo-transformer #'(foo ARG...))

If, on the other hand, a macro is referenced in some other part of a form, the syntax transformer is invoked with only the macro reference, not the whole form.

     (define-syntax foo foo-transformer)
     foo
     ;; expands via
     (foo-transformer #'foo)

This allows bare identifier references to be replaced programmatically via a macro. syntax-rules provides some syntax to effect this transformation more easily.

 -- Syntax: identifier-syntax exp
     Returns a macro transformer that will replace occurrences of the macro with EXP.

For example, if you are importing external code written in terms of fx+, the fixnum addition operator, but Guile doesn't have fx+, you may use the following to replace fx+ with +:

     (define-syntax fx+ (identifier-syntax +))

There is also special support for recognizing identifiers on the left-hand side of a set! expression, as in the following:

     (define-syntax foo foo-transformer)
     (set! foo VAL)
     ;; expands via
     (foo-transformer #'(set! foo VAL))
     ;; iff foo-transformer is a "variable transformer"

As the example notes, the transformer procedure must be explicitly marked as being a ``variable transformer'', as most macros aren't written to discriminate on the form in the operator position.

 -- Scheme Procedure: make-variable-transformer transformer
     Mark the TRANSFORMER procedure as being a ``variable transformer''. In practice this means that, when bound to a syntactic keyword, it may detect references to that keyword on the left-hand-side of a set!.

          (define bar 10)
          (define-syntax bar-alias
            (make-variable-transformer
             (lambda (x)
               (syntax-case x (set!)
                 ((set! var val) #'(set! bar val))
                 ((var arg ...) #'(bar arg ...))
                 (var (identifier? #'var) #'bar)))))

          bar-alias => 10
          (set! bar-alias 20)
          bar => 20
          (set! bar 30)
          bar-alias => 30

There is an extension to identifier-syntax which allows it to handle the set! case as well:

 -- Syntax: identifier-syntax (var exp1) ((set! var val) exp2)
     Create a variable transformer. The first clause is used for references to the variable in operator or operand position, and the second for appearances of the variable on the left-hand-side of an assignment.

     For example, the previous bar-alias example could be expressed more succinctly like this:

          (define-syntax bar-alias
            (identifier-syntax
              (var bar)
              ((set! var val) (set! bar val))))

     As before, the templates in identifier-syntax forms do not need wrapping in #' syntax forms.

Syntax Parameters
-----------------

Syntax parameters (Described in the paper Keeping it Clean with Syntax Parameters by Barzilay, Culpepper and Flatt.) are a mechanism for rebinding a macro definition within the dynamic extent of a macro expansion.  This provides a convenient solution to one of the most common types of unhygienic macro: those that introduce a unhygienic binding each time the macro is used.  Examples include a lambda form with a return keyword, or class macros that introduce a special self binding.

With syntax parameters, instead of introducing the binding unhygienically each time, we instead create one binding for the keyword, which we can then adjust later when we want the keyword to have a different meaning.  As no new bindings are introduced, hygiene is preserved. This is similar to the dynamic binding mechanisms we have at run-time (see parameters), except that the dynamic binding only occurs during macro expansion.  The code after macro expansion remains lexically scoped.

 -- Syntax: define-syntax-parameter keyword transformer
     Binds KEYWORD to the value obtained by evaluating TRANSFORMER.  The TRANSFORMER provides the default expansion for the syntax parameter, and in the absence of syntax-parameterize, is functionally equivalent to define-syntax.  Usually, you will just want to have the TRANSFORMER throw a syntax error indicating that the KEYWORD is supposed to be used in conjunction with another macro, for example:

          (define-syntax-parameter return
            (lambda (stx)
              (syntax-violation 'return "return used outside of a lambda^" stx)))

 -- Syntax: syntax-parameterize ((keyword transformer) ...) exp ...
     Adjusts KEYWORD ... to use the values obtained by evaluating their TRANSFORMER ..., in the expansion of the EXP ... forms.  Each KEYWORD must be bound to a syntax-parameter. syntax-parameterize differs from let-syntax, in that the binding is not shadowed, but adjusted, and so uses of the keyword in the expansion of EXP ... use the new transformers. This is somewhat similar to how parameterize adjusts the values of regular parameters, rather than creating new bindings.

          (define-syntax lambda^
            (syntax-rules ()
              [(lambda^ argument-list body body* ...)
               (lambda argument-list
                 (call-with-current-continuation
                  (lambda (escape)
                    ;; In the body we adjust the 'return' keyword so that calls
                    ;; to 'return' are replaced with calls to the escape
                    ;; continuation.
                    (syntax-parameterize ([return (syntax-rules ()
                                                    [(return vals (... ...))
                                                     (escape vals (... ...))])])
                      body body* ...))))]))

          ;; Now we can write functions that return early.  Here, 'product' will
          ;; return immediately if it sees any 0 element.
          (define product
            (lambda^ (list)
                     (fold (lambda (n o)
                             (if (zero? n)
                                 (return 0)
                                 (* n o)))
                           1
                           list)))

Eval-when
---------

As syntax-case macros have the whole power of Scheme available to them, they present a problem regarding time: when a macro runs, what parts of the program are available for the macro to use?

The default answer to this question is that when you import a module (via define-module or use-modules), that module will be loaded up at expansion-time, as well as at run-time. Additionally, top-level syntactic definitions within one compilation unit made by define-syntax are also evaluated at expansion time, in the order that they appear in the compilation unit (file).

But if a syntactic definition needs to call out to a normal procedure at expansion-time, it might well need need special declarations to indicate that the procedure should be made available at expansion-time.

For example, the following code will work at a REPL, but not in a file:

     ;; incorrect
     (use-modules (srfi srfi-19))
     (define (date) (date->string (current-date)))
     (define-syntax %date (identifier-syntax (date)))
     (define *compilation-date* %date)

It works at a REPL because the expressions are evaluated one-by-one, in order, but if placed in a file, the expressions are expanded one-by-one, but not evaluated until the compiled file is loaded.

The fix is to use eval-when.

     ;; correct: using eval-when
     (use-modules (srfi srfi-19))
     (eval-when (compile load eval)
       (define (date) (date->string (current-date))))
     (define-syntax %date (identifier-syntax (date)))
     (define *compilation-date* %date)

 -- Syntax: eval-when conditions exp...
     Evaluate EXP... under the given CONDITIONS. Valid conditions include eval, load, and compile. If you need to use eval-when, use it with all three conditions, as in the above example. Other uses of eval-when may void your warranty or poison your cat.

Internal Macros
---------------

 -- Scheme Procedure: make-syntax-transformer name type binding
     Construct a syntax transformer object. This is part of Guile's low-level support for syntax-case.

 -- Scheme Procedure: macro? obj
 -- C Function: scm_macro_p (obj)
     Return #t iff OBJ is a syntax transformer.

     Note that it's a bit difficult to actually get a macro as a first-class object; simply naming it (like case) will produce a syntax error. But it is possible to get these objects using module-ref:

          (macro? (module-ref (current-module) 'case))
          => #t

 -- Scheme Procedure: macro-type m
 -- C Function: scm_macro_type (m)
     Return the TYPE that was given when M was constructed, via make-syntax-transformer.

 -- Scheme Procedure: macro-name m
 -- C Function: scm_macro_name (m)
     Return the name of the macro M.

 -- Scheme Procedure: macro-binding m
 -- C Function: scm_macro_binding (m)
     Return the binding of the macro M.

 -- Scheme Procedure: macro-transformer m
 -- C Function: scm_macro_transformer (m)
     Return the transformer of the macro M. This will return a procedure, for which one may ask the docstring. That's the whole reason this section is documented. Actually a part of the result of macro-binding.