On Sat, Aug 02, 2003 at 01:18:01PM -0600, Luke Palmer wrote:
: While we seem to be on the subject of hashing out macro semantics,
: here's a question I've had awhile.
: 
: What do macros do about being passed variables?
: 
: Let's say I make a C<square> macro:
: 
:     macro square ($x) {
:         { $x * $x }
:     }
: 
: And then I have code.
: 
:     my $var = 10;
:     print square $var;
: 
: Does that turn that into (at compile time):
: 
:     print($var * $var);
: 
: Or does it use the compile time value of $x, turning it into:
: 
:     print(undef * undef);
: 
: I would hope the former.

It's the former.  The block is essentially inlined.

: However, what about this compile-time
: integral power macro[1]?
: 
:     macro power ($x, $p) {
:         if $p > 0 {
:             { $x * power($x, $p-1) }
:         }
:         else {
:             { 1 }
:         }
:     }
: 
: That would hopefully turn:
: 
:     my $var = 10;
:     print power $var, 4;
: 
: Into
: 
:     print($var * $var * $var * $var * 1);

Nope.  $x and $p are syntax trees.  If you want compile-time evaluation
you'd have to do something explicit in there to evaluate $p:

    macro power ($x, $p) {
        my $count = $p.run();
        if $count > 0 {
            $count--;
            { $x * power($x, $count) }
        }
        else {
            { 1 }
        }
    }

That might be reducable to:

    macro power ($x, $p is run) {
        if $p > 0 {
            $p--;
            { $x * power($x, $p) }
        }
        else {
            { 1 }
        }
    }

But you can't decrement $p inside the block, or it just becomes part of
the inlined code.

: But what about
: 
:     my $var = 10;
:     my $ex = 4;
:     print power $var, $ex;

Depends on how power is written.  Can't have it both ways unless power is
written to finesse it somehow.

: [1] That one's kind of interesting actually.  If the macro is called
: right upon parsing it, it will be called before it's done compiling
: it.  Which is a problem.  Is there a way to get around this, because
: recusive macros are useful (as demonstrated above).

I suppose one could defer the expansion of a nested macro till it's
called for real.  That might mean that we need an explicit keyword
on the block though to suppress immediate expansion:

    macro power ($x, $p is run) {
        if $p > 0 {
            $p--;
            template { $x * power($x, $p) }
        }
        else {
            template { 1 }
        }
    }

Alternately, we just defer the expansion of any declared but undefined
macro till it is defined somehow.  That would presumably handle
mutually recursive macros even.

Those are both hard.  Unless someone volunteers to implement it,
we could just say that you have to write a helper sub if you want
recursion.

Larry

Reply via email to