Scheme: Passing defines inside macro definition to submacro?

303 views Asked by At

Consider the following macro definition in R7RS scheme:

(define-syntax foo
  (syntax-rules ()
    ((_ bar)
      (begin
        (define baz 42)
        (define-syntax bar
          (syntax-rules ()
            ((_) baz)))))))

I have loaded this file into the repl of chibi-scheme and entered:

> (foo bar)

> (bar)

Instead of the expected output 42, I got:

ERROR: undefined variable: baz

Why is this so and how can I pass the defined value of baz in the outer macro to the inner macro?

2

There are 2 answers

1
GoZoner On BEST ANSWER

This is an error in chibi-scheme. A macro definition needs to capture its environment; for bar the environment consists of bar itself and baz. Then when you expand bar in another environment, the macro expansion needs to recognize that baz is bound in the env-of-definition. chibi-scheme apparently doesn't recognize that baz is actually defined.

Additionally, another related problem, which you haven't seen in your post, is that even if the expansion of bar recognizes baz as bound, the loading/running of the code needs to find the value of baz.

Here is R6RS Ikarus Scheme:

> (define-syntax foo
  (syntax-rules ()
    ((_ bar)
      (begin
        (define baz 42)
        (define-syntax bar
          (syntax-rules ()
            ((_) baz)))))))
> (foo bar)
> (bar)
42
> 
0
John Cowan On

I've run this on all the Schemes in my test suite that support syntax-rules, and it fails only on Chibi and MIT. I don't see any reason why it shouldn't work, but I confess that macrology is still something of a black art to me. In particular, it works in Foment, which is an R7RS system. I haven't been able to build Sagittarius, so I can't test it there.