Raku Programming Language

make empty

2018-11-15  本文已影响0人  焉知非鱼
my $str = q :to/EOF/;
Perl6,Rust
-- this is a comment
Rakudo,Raku
-- this is another comment
Camelia,Camel
EOF

grammar MakeEmpty {
    token TOP      { ^ <sentence>+ % <comment>  $}
    token sentence { <words>+ % ',' \n   }
    token comment  { '-- ' <words>+ % ' ' \n  }
    token words    { \w+ }
}

class Action {
    method TOP($/)      { make $/.values».ast }
    method sentence($/) { make ~$/.trim   }
    method comment($/)  { make Empty }
    method words($/)    { make ~$/   }
}

my $parsed = MakeEmpty.parse($str, :actions(Action)).ast;
.say for @$parsed;

# Perl6,Rust
# Rakudo,Raku
# Camelia,Camel

say '-' x 25;
# ----------------------------------------------------------

my $string = q :to/EOF/;
Perl6,Rust
-- this is a comment
Rakudo,Raku
-- this is another comment
Camelia,Camel
/* this is inline comments */
Java,Nim

Python,PHP
EOF

grammar WhiteSpace {
    rule TOP       { ^ <sentence>+ % <.ws> $ }
    token sentence { <words>+ % ',' \n       }
    token comment  { '-- ' <words>+ % ' ' \n }
    token words    { \w+ }
    token ws { \s* | <comment> | <slash-star-comment> }
    token slash-star-comment { \s* '/*' .*? '*/' \s* }
}

class SpaceAction {
    method TOP($/)      { make $/.values».ast  }
    method sentence($/) { make ~$/.trim        }
    method comment($/)  { make ~$/             }
    method words($/)    { make ~$/             }
    method slash-star-comment($/) { make ~$/   }
    method ws($/)                 { make Empty }
}

my $em = WhiteSpace.parse($string, :actions(SpaceAction)).ast;
.say for @$em;

# Perl6,Rust
# Rakudo,Raku
# Camelia,Camel
# Java,Nim
# Python,PHP

参考 https://stackoverflow.com/questions/42254754/how-to-skip-unrelated-lines-when-using-perl-6-grammar-to-parse-structurized-text

上一篇 下一篇

猜你喜欢

热点阅读