This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

macro expansion within macro

6 posts · 5255 views

I would like to know how get a macro to be expanded/evaluated within another macro when passed in as an argument.

e.g. if i define the macro:

(defmacro cond-clause (expr res)
`(,expr (push ,res res)))

Then (macroexpand-1 '(cond-clause (= c 8) 1))
returns ((= C 8) (PUSH 1 RES))

if i define another macro

(defmacro test (expr)
`(cond ,(',expr)))


and call (macroexpand-1 '(test (cond-clause (= c 8) 1))) it returns
(COND (COND-CLAUSE (= C 8) 1))

it seems like the macro i pass in as argument isn't being expanded in the test macro call


what i want the test macro to return is (COND ((= C 8) (PUSH 1 RES)))

is there away to do this? Help is greatly appreciated.

Re: macro expansion within macro

Your code did not work in my implementation. But here is my solution of what you probably wanted:
(defmacro cond-clause (expr res)      
    `(,expr (push ,res res) )  )

(defmacro test (cond-expr)
    `(cond  ,(macroexpand-1 cond-expr) ) )
Then the command
  (macroexpand-1 '(test (cond-clause (equalp c 8) 1) ) ) 
results what you wanted: (COND ((EQUALP C 8) (PUSH 1 RES))).
Final executing of the command
 (test (cond-clause (equalp c 8) 1) )  
works as expected.

Let someone else explain this behaviour of macro inside macro, such combinations of evaluation and macroexpansion operations are a bit outside of possibilities of a human brain.....
To understand LISP, you must first understand LISP.

Re: macro expansion within macro

Why do you (think you) want the inner macro to be expanded? It'll be expanded anyway when the processor (compiler, interpreter) gets to it; is it really necessary to have the expansion appear in your macro-expansion? Possibly you're just asking for a "macroexpand-all" function (in which case, try apropos...there may already be one lurking around).

Re: macro expansion within macro

What is the higher level goal here?

Re: macro expansion within macro

Macro forms are expanded only at places where a function call may be placed. Since (COND (COND-CLAUSE (= C 8) 1)) didn't work if COND-CLAUSE was a function it also doesn't work if its a macro.

Re: macro expansion within macro

Konfusius wrote:Macro forms are expanded only at places where a function call may be placed. Since (COND (COND-CLAUSE (= C 8) 1)) didn't work if COND-CLAUSE was a function it also doesn't work if its a macro.
That is not really the problem. The problem in this case is that the interpreter/compiler macroexpands COND before COND-CLAUSE. Because of the way that COND is macroexpanded, COND-CLAUSE isn't macroexpanded at all.