How to extract data from RakuAST 's

144 views Asked by At

How best is it to extract a hash from the config portion of a RakuAST::Doc::Block ? Here is the program:

use v6.d;
use experimental :rakuast;

my $ast = Q:to/CONF/.AST;
=for rakudoc :category("Language") :kind<sub> :subkind<operator>
Stuff
CONF
my $block = $ast.rakudoc[0];
my %config = $block.config.pairs.map( { .key  =>  .value.DEPARSE } );
say %config.raku

Here is the result.

{:category("(\"Language\")"), :kind("<sub>"), :subkind("<operator>")}

But .DEPARSE is producing the quotation markers, viz, ("...") and <...>. How can I just extract the string?

2

There are 2 answers

0
Elizabeth Mattijsen On BEST ANSWER

The .DEPARSE method attempts to re-create the original Raku code. For strings this means quotes are included.

If you want to get to the actual values, you can call the .literalize method on any RakuAST object. This will either return Nil if it cannot be literalized, or the actual value if it can.

UPDATE: It was a while when I worked last on this. While the above will work, there is actually already a method that will DWIM: .resolved-config. So:

my %config := $block.resolved-config;
say %config;

will produce:

Map.new((category => Language, foo => (a => 42 b => 666), kind => sub, subkind => operator))

Note the use of := instead of =. While the = will also work, the := will be much more efficient as it wouldn't need to copy anything.

4
raiph On

s/DEPARSE/EVAL/

Change the first line below (copied from your code) to the line below it:

my %config = $block.config.pairs.map( { .key  => .value.DEPARSE} );
my %config = $block.config.pairs.map( { .key  => .value.EVAL} );

I had prepared a much longer answer. But for now it's just in a private gist I'm not yet ready to share. Hopefully one day I will have time to do so!