Page 1 of 1
macro expansion within macro
Posted: Wed Nov 28, 2012 6:07 am
by ndm42
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
Posted: Thu Nov 29, 2012 2:15 am
by abvgdeika
Your code did not work in my implementation. But here is my solution of what you probably wanted:
Code: Select all
(defmacro cond-clause (expr res)
`(,expr (push ,res res) ) )
(defmacro test (cond-expr)
`(cond ,(macroexpand-1 cond-expr) ) )
Then the command
Code: Select all
(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
Code: Select all
(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.....
Re: macro expansion within macro
Posted: Thu Nov 29, 2012 3:26 pm
by Paul
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
Posted: Thu Nov 29, 2012 5:47 pm
by pjstirling
What is the higher level goal here?
Re: macro expansion within macro
Posted: Fri Nov 30, 2012 5:27 am
by Konfusius
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
Posted: Fri Nov 30, 2012 12:29 pm
by gugamilare
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.