Perl6: convert a Match object to a JSON serializable hash

I am currently getting dirty hands on some Perl6. In particular, I'm trying to write a grammar-based Fortran parser ( Fortran module :: Grammar )

For testing purposes, I would like to be able to convert the object Matchto JSON-serializable Hash.

Googling / Perl6 official documentation did not help. We apologize if I missed something.

My attempts:

  • I know that you can convert a Match $mto Hashthrough $m.hash. But it stores nested objects Match.
  • Since it just has to resolve through recursion, I tried, but refused to first ask about the existence of a simpler / existing solution here.
  • Working with the contents of Matchobjects is obviously best achieved with make/ made. I would really like to have a super simple object Actionsto pass .parseusing the default method for all matches, which basically just does make $/.hashor something like that. I just don't know how to specify the default method.
+4
source share
2 answers

Perl 6, , .

, , , ( , ):

#| Fallback action method that produces a Hash tree from named captures.
method FALLBACK ($name, $/) {

    # Unless an embedded { } block in the grammar already called make()...
    unless $/.made.defined {

        # If the Match has named captures, produce a hash with one entry
        # per capture:
        if $/.hash -> %captures {
            make hash do for %captures.kv -> $k, $v {

                # The key of the hash entry is the capture name.
                $k => $v ~~ Array 

                    # If the capture was repeated by a quantifier, the
                    # value becomes a list of what each repetition of the
                    # sub-rule produced:
                    ?? $v.map(*.made).cache 

                    # If the capture wasn't quantified, the value becomes
                    # what the sub-rule produced:
                    !! $v.made
            }
        }

        # If the Match has no named captures, produce the string it matched:
        else { make ~$/ }
    }
}

:

  • (.. ( ) ) - (, <foo> <foo=bar>). , , , . , :
    • $/.hash , Map.
    • $/.list , List.
    • $/.caps ( $/.pairs) , name=>submatch / index=>submatch.
  • AST { make ... } ( , make undefined), .
+5

, .

FALLBACK.

-

method FALLBACK($name, $/) {
    make $/.pairs.map(-> (:key($k), :value($v)) {
        $k => $v ~~ Match ?? $v.made !! $v>>.made
    }).hash || ~$/;
}

.

make , ( , ), "" .

+3

Source: https://habr.com/ru/post/1668752/


All Articles