abstract-syntax-treerakurakudonqp

Obtaining the QAST of a Perl 6 file from another program


This is related to this question on accesing the POD, but it goes further than that. You can easily access the Abstract Syntax Tree of a Perl 6 program using:

perl6 --target=ast -e '"Þor is mighty!".say'

This will print the whole Q abstract syntax tree. It's not too clear how to make this from your own program, or I haven't found how to do it. In fact, the CoreHackers::Q module runs that as an external script. But being able to access it from your own program, like

use QAST; # It does not exist
my $this-qast = QAST::Load("some-external-file.p6") # Would want something like this

would be great. I'm pretty sure it should be possible, at the NQP level and probably in a Rakudo-dependent way. Does someone know hot it goes?


Solution

  • Since QAST is not a part of the Perl 6 language specification, but an internal implementation detail of Rakudo, there's no official way to do this. Eventually there will be an AST form that is part of the language specification, but that doesn't yet exist (the 007 project which is working on exploring this area).

    It is, however, possible to obtain the QAST tree by using:

    use nqp;
    my $ast = nqp::getcomp("perl6").eval("say 42", :target<ast>);
    say $ast.dump();