Skip to content

Instantly share code, notes, and snippets.

@jonathanstowe
Last active August 29, 2015 14:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jonathanstowe/31c8e72d86d889489f0f to your computer and use it in GitHub Desktop.
Termcap string value grammar attempt
#!perl6
use v6;
=begin code
Original perl 5
s/\\E/\033/g;
s/\\(\d\d\d)/pack('c',oct($1) & 0177)/eg;
s/\\n/\n/g;
s/\\r/\r/g;
s/\\t/\t/g;
s/\\b/\b/g;
s/\\f/\f/g;
s/\\\^/\377/g;
s/\^\?/\177/g;
s/\^(.)/pack('c',ord($1) & 31)/eg;
s/\\(.)/$1/g;
s/\377/^/g;
=end code
my $cap = "\\E[30;1H\\E[K\\E[24;0;0;24p^R\\165";
# Try with a grammar;
grammar StrVal {
token esc { \\E }
token oct_val { \d\d\d }
token oct_chr { \\<oct_val> }
token nl { \\n }
token ret { \\r }
token tab { \\t }
token ff { \\f }
token caret { \\\^ }
token ctrl_char { <:Lu> }
token ctrl { \^<ctrl_char> }
token del { \^\? }
token char { . }
token esc_char { \\<char> }
regex special {
<value=esc> ||
<value=oct_chr> ||
<value=nl> ||
<value=ret> ||
<value=tab> ||
<value=ff> ||
<value=caret> ||
<value=ctrl> ||
<value=del> ||
<value=esc_char>
}
token literal { . }
token str_val { [ <value=special> || <value=literal> ]+ }
token TOP { <str_val> }
}
class StrValActions {
method esc($/) {
$/.make("\o[033]");
}
method oct_chr($/) {
my $val = $/<oct_val>;
my $oct_val = pack('C',( '0o' ~ $val).Int +& 177).decode;
$/.make($oct_val);
}
method nl($/) {
$/.make("\n");
}
method ret($/) {
$/.make("\r");
}
method tab($/) {
$/.make("\t");
}
method ff($/) {
$/.make("\f");
}
method caret($/) {
$/.make('^');
}
method del($/) {
$/.make("\o[177]");
}
method ctrl($/) {
my $char = $/<ctrl_char>;
my $ctrl_char = pack('C',ord($char) +& 31).decode ;
$/.make($ctrl_char);
}
method esc_char($/) {
$/.make($/<char>);
}
method literal($/) {
$/.make(~$/);
}
method special($/) {
my $val = $/<value>.made;
$/.make($val);
}
method str_val($/) {
my $val = $/<value>.list.map( { .made }).join('');
$/.make($val);
}
method TOP($/) {
$/.make($/<str_val>.made);
}
}
say StrVal.parse($cap, actions => StrValActions).made;
# Try with p6 regex - works
given $cap {
s:g/\\E/\o[033]/;
s:g/\\(\d\d\d)/{ pack('C',( '0o' ~ $/[0]).Int +& 177).decode }/;
s:g/\\n/\n/;
s:g/\\r/\r/;
s:g/\\t/\t/;
s:g/\\b/\b/;
s:g/\\f/\f/;
s:g/\\\^/\o[377]/;
s:g/\^\?/\o[177]/;
s:g/\^(.)/{ pack('C',ord($/[0]) +& 31).decode }/;
s:g/\\(.)/$1/;
s:g/\o[377]/^/;
}
say $cap;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment