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?
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
>