Created
June 12, 2014 19:20
-
-
Save cognominal/e8cd38a610a735a503ec to your computer and use it in GitHub Desktop.
A grammar that supports podish formatting directives
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin comment | |
rx/stuff/ | |
you're really declaring an anonymous method, something like: | |
my $internal = anon regex :: ($¢: ) { stuff } | |
=end comment | |
sub esc(str $s) { $s.trans: q:w/ & < > / => < & < > > } | |
sub element(str $tag, str $s) { "<$tag>$s\</$tag>" } | |
# obfuscated cuz no support for $<opener>='<'+ ... '>' ** {$opener.chars} | |
grammar G { | |
regex podish { | |
[ <styled> || $<char>=. ]+? | |
} | |
regex styled { | |
:my $closer; | |
$<style> = <[ICB]> | |
$<opener> = '<'+ | |
<podish> | |
{ $closer = $<opener>.trans: '<' => '>' } | |
$closer | |
} | |
} | |
my $data := q:to<DATA>; | |
a | |
C<a> | |
B<a> | |
I<a> | |
C<< aa >> | |
C<< a>b >> | |
C<< a<b> >> | |
C<< < a I<i> >> | |
DATA | |
G.parse: $_, :rule<podish> for $data.lines; | |
die 'no match' unless $/; | |
# say deep-view $_ for $/.chunks; | |
sub deep-view(Pair \p, $indent is copy = 0) { | |
sub flat-view(Pair $p, $indent) { ' ' x $indent ~ "$p.key() => {(~$p.value).perl}\n" ; } | |
my $s = flat-view p, $indent; | |
my @chunks := p.value.chunks; | |
return $s if @chunks == 1 and @chunks[0].key eq '~'; | |
$indent++; | |
$s ~= (.value ~~ Str ?? &flat-view !! &deep-view)($_, $indent) for p.value.chunks; | |
$s; | |
} | |
my %style-to-tag = < C code B b I i >; | |
sub test($_) { | |
say $_; | |
G.parse: $_, :rule<podish>; | |
die "incorrect podish" unless $/; | |
return recurse($/); | |
sub recurse($/) { | |
my $s = ''; | |
for $/.chunks -> $pair { | |
# say $pair.key ~ '=>' ~ $pair.value ; | |
my $ms := $pair.value; | |
given $pair.key { | |
when 'char' { $s ~= esc ~$ms } | |
when 'styled' { | |
$s ~= element %style-to-tag{$ms<style>}, &?ROUTINE($ms<podish>) | |
} | |
} | |
} | |
$s; | |
} | |
} | |
say test($_) for $data.lines | |
=begin comment | |
styled => "C<<a>>" | |
style => "C" | |
opener => "<<" | |
char => "a" | |
~ => ">>" | |
char => "C" | |
char => "<" | |
char => "<" | |
char => "a" | |
char => ">" | |
char => ">" | |
=end comment | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment