From: Kaz Kylheku
Subject: Re: Question about the lexical environment
Date: 
Message-ID: <20090403092808.572@gmail.com>
On 2009-03-25, Anticomuna <············@uol.com.br> wrote:
> I am a bit confused about the &environment keyword in defmacro.
>
> 1 - How do I create an instance of an environment object to pass to
> macro calls?

You don't. This is passed to your macro by the macroexpander.

> 2 - What do I do with it? Can I install it in the place of the current
> one for the expansion of the macro?

You pass it to functions that take a macro environment, like MACROEXPAND.

MACROEXPAND requires an environment when called from within a macro, because
the form you are expanding may be a local macro ratehr than a global macro.

Example:

  ;; Your macro
  (defmacro yourmacro (user-form &environment env)

    ...)

  ;; User's macro call to your macro
  (macrolet ((usermacro (...)) ...)
    (yourmacro (usermacro ...)))

Suppose that inside YOURMACRO you want expand USER-FORM. But USER-FORM is bound
to the form (USERMACRO ...) and USERMACRO is a local macro; i.e. its macro
function has to be found in the local macroexpansion environment.

> I understand how lexical environments work, I just don't understand
> why it is explicitly handled by the developer

It has to be explicitly handled because automatic handling would be a mess.
Your macro and the user's form are in completely separate lexical scopes. 

Moreover, your macro can be called from any number of places in the program,
and each of those places has a different lexical scope with different local
macros that are active in it.

So this is actually more like a dynamic scope: to do the expansion, the macro
needs to have access to whichever scope is in the caller.

This is closely analogous to the passing of an explicit environment among the
functions of a Lisp evaluator.

If this were to be automated, the automation would likely involve the use of a
special variable.  I.e. suppose there was a special variable called
*MACROEXPAND-ENV*, bound during macro-expansion. Suppose that this variable was
used to supply a default value for the optional environment parameter of
MACROEXPAND and MACROEXPAND-1.

But this is basically equivalent to having an environment parameter, except
that it doesn't appear as a function argument. Special variables are like extra
arguments that travel with all function calls.