Skip to content

Instantly share code, notes, and snippets.

@cognominal
Created June 12, 2014 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cognominal/e8cd38a610a735a503ec to your computer and use it in GitHub Desktop.
Save cognominal/e8cd38a610a735a503ec to your computer and use it in GitHub Desktop.
A grammar that supports podish formatting directives
=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/ & < > / => < &amp; &lt; &gt; > }
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