Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macros do not allow definition of lexical variables

Tags:

macros

raku

This code that uses (experimental) macros:

use experimental :macros; 
macro new-var() { 
  quasi { 
    my $a = 42
  }
};
new-var; 
say $a

Fails with Variable '$a' is not declared, although the macro passes through without an error. If that's a correct macro declaration, what does it do? If it's not, is there a way to define new variables from within a macro?

like image 868
jjmerelo Avatar asked Dec 23 '18 08:12

jjmerelo


2 Answers

The answer from moritz is correct about the state of macros, though from what I know of the work being done in 007, I don't think the program as written would be correct even with a working implementation of Perl 6 macros.

Perl 6 macros will not be textual in nature (C macros are an example of textual ones). A quasi is a quote construct, much like we have quotes for strings and regexes, except that it quotes Perl 6 code, representing it as something AST-ish. (I once would have said that it produces AST, but it's been realized that if an infix were to be interpolated inside of a quasi, then it comes with a precedence and associativity, and we we can't actually form the correct tree for the expression until after interpolation.)

There's a macro concept of "hygiene", whereby symbols declared in the macro body should not, by default, leak out to the place that the macro is applied, since they may well just be implementation details. One would have to explicitly ask to put a symbol into the compiling context where the macro is applied. So I expect the program would have to look like this:

macro new-var() { 
    quasi { 
        my COMPILING::<$a> = 42
    }
};
new-var; 
say $a

Note that this won't work today in Rakudo, although you might find something like it can be made to work in 007.

like image 57
Jonathan Worthington Avatar answered Oct 17 '22 05:10

Jonathan Worthington


This might not be the answer you are looking for, but macros in Rakudo are currently really broken. At this point in time I can't even remember if it's supposed to work, or if it's a bug in Rakudo -- it's mostly not worth it figuring it out, because most macro things barely work at all.

This is why Carl Mäsak created 007 to experiment with Macro design outside of Rakudo core, with the goal of eventually bringing the lessons learned back to Rakudo and the Perl 6 language design.

like image 7
moritz Avatar answered Oct 17 '22 05:10

moritz