Parsing – How to Implement Actions in Raku Based on Parse Success

parsingraku

Is there a way to configure Raku actions to only execute after a parse has completed successfully? For example, the program below outputs "Jane is telling us her age….", even with malformed input.

grammar Foo {
  rule TOP { <name> is \d+ }
  token name { [Anne | Jane] { say "$/ is telling us her age...."; } }
}

say so Foo.parse('Anne is 100');  # True
say so Foo.parse('Jane is Leaf'); # False

Best Answer

You could move the code block to the rule TOP;

grammar Foo {
    rule TOP { <name> is \d+ { say  "$/<name> is telling us her age...."  } }
    token name { [Anne | Jane]  }
}

say so Foo.parse('Anne is 100');
say so Foo.parse('Jane is Leaf');
Anne is telling us her age....
True
False

using the routines make and made;

grammar Foo {
    rule TOP { <name> is \d+ }
    token name { [Anne | Jane]  { make  "$/ is telling us her age...."  } }
}

say Foo.parse('Anne is 100').<name>.made;
say Foo.parse('Jane is Leaf').<name>.made;
Anne is telling us her age....
Nil

or their combination.

grammar Foo {
    rule TOP { <name> is \d+  { say  $/<name>.made } }
    token name { [Anne | Jane]  { make  "$/ is telling us her age...."  } }
}

say so Foo.parse('Anne is 100');
say so Foo.parse('Jane is Leaf');
Anne is telling us her age....
True
False

Remember that for more complex problems, you can explore using Actions.