Skip to content

Instantly share code, notes, and snippets.

@ajs
Created December 7, 2018 19:57
Show Gist options
  • Save ajs/ca9940a71d096743e08a3a36cdcc6f39 to your computer and use it in GitHub Desktop.
Save ajs/ca9940a71d096743e08a3a36cdcc6f39 to your computer and use it in GitHub Desktop.
Perl 6 Simple String Parser Example
# Perl 6 Example from: https://examples.perl6.org/categories/parsers/SimpleStrings.html
# 6pad-ified
# Note: Until this issue is fixed:
# https://github.com/perl6/6pad/issues/2
# You must reload this 6pad between runs, otherwise the
# grammar conflicts with itself as a redefinition.
use v6;
grammar String::Simple::Grammar {
rule TOP {^ <string> $}
# Note for now, {} gets around a rakudo binding issue
token string { <quote> {} <quotebody($<quote>)> $<quote> }
token quote { '"' | "'" }
token quotebody($quote) { ( <escaped($quote)> | <!before $quote> . )* }
token escaped($quote) { '\\' ( $quote | '\\' ) }
}
# The parse-tree builder ultimately returns the string itself.
class String::Simple::Actions {
method TOP($/) { make $<string>.made }
method string($/) { make $<quotebody>.made }
method quotebody($/) { make [~] $0.map: {.<escaped>.made or ~$_} }
method escaped($/) { make ~$0 }
}
# Here is a sample string:
my $sample = q{"This is a quote"};
my $result = String::Simple::Grammar.parse: $sample; # parse it
say $result.gist;
# A more complicated sample: '\''
$sample = "'\\\''";
$result = String::Simple::Grammar.parse: $sample; # parse it
say $result.gist;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment