I am trying to work my way through Perl grammars and, more specifically, actions objects.
I have written this grammar for a subset of JSON (as a shorter example of my larger problem):
Used with the following JSON subset string and parsing call:grammar My-Grammar { token TOP { \s* <object> \s* } rule object { '{' \s* <pairlist> '}' \s* } rule pairlist { <pair> * % \, } rule pair { <string>':' <value> } token string { \" <[ \w \s \- ' ]>+ \" } token number { [ \d+ [ \. \d+ ]? ] | [ \. \d+ ] } token value { <object> | <string> | <number> | true | false | null } }
I get the following stringified match object:my $source-string = q/{ "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "spouse": null }/; my $match = My-Grammar.parse($source-string); say ~$match if $match; # say $match.made if $match;
So parsing the string with the grammar seems to work correctly.{ "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "spouse": null }
I have a problem when I try to add an actions object.
This is about the best actions class I could come up with so far:
With this actions class, I get the following AST:class My-actions { method TOP($/) { make $/.values.[0].made; }; method object ($/) { make $<pairlist>.made.hash.item; } method pairlist($/) { make $<pair>>>.made.flat; } method pair($/) { make $<string>.made => $<value>.made ; } method string($/) { make ~$/; } method number($/) { make +$/.Str; } method value($/) { given ~$/ { when "true" {make Bool::True;} when "false" {make Bool::False;} when "null" {make Any;} default { make ~$/;} } } }
Except for the address component, the AST seems correct.{"address" => { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "age" => 25, "firstName" => "John", "isAlive" => True, "lastName" + => "Smith", "spouse" => (Any)}
The address component is not transformed into AST nodes obviously because of this line:
in the value method of the actions class, which just stringifies the address sub-object. I have put that line so far as a temporary workaround just to get the overall shebang sort of working, but I have no idea how to get further. Specifically, I have tried many things, but I just can't figure out how to identify that the value is itself (recursively) an object and, even if I knew how to identify that, I still probably wouldn't know how to process it to produce a proper AST subtree for it.default { make ~$/;}
Would a nice monk around here be kind enough to enlighten me on this last part?
In reply to Perl 6 grammars - setting the actions object by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |