Acme-AsciiArtinator
view release on metacpan or search on metacpan
lib/Acme/AsciiArtinator.pm view on Meta::CPAN
#
# find position of a scalar in an array.
#
sub STRPOS {
my ($word, @array) = @_;
my $pos = -1;
for (my $i=0; $i<@array; $i++) {
$pos = $i if $array[$i] =~ /$word/;
}
return $pos;
}
#
# what does the "/" token that we just encountered mean?
# this is a hard game to play.
# see http://www.perlmonks.org/index.pl?node_id=44722
#
sub regex_or_divide {
my ($tokenref, $contextref) = @_;
my @tokens = @$tokenref;
my @contexts = @$contextref;
# regex is expected following an operator,
# at the beginning of a statement
# divide is expected following a scalar,
# or any token that could complete an expression
my $c = $#contexts;
$c-- while $contexts[$c] eq "whitespace";
return "regex" if $contexts[$c] eq "operator";
return "regex" if $tokens[$c] eq ";" && $tokens[$c-1] ne "SIGIL";
return "divide";
}
sub tokenize_code {
my ($INPUT) = @_;
local $" = '';
my @INPUT = grep { /[^\n]/ } split //, $INPUT;
# tokens are:
# quotes strings
# numeric literals
# regular expression specifications
# except with //x and s///x
# alphanumeric strings
# punctuation strings from @token_keywords
#
my ($i, $j, $Q, @tokens, $token, $sigil, @contexts, @blocks);
$sigil = 0;
for ($i = 0; $i < @INPUT; $i++) {
$_ = $INPUT[$i];
$Q = "@INPUT[$i..$#INPUT]";
print STDERR "\$Q = ", substr($Q,0,8), "... SIGIL=$sigil\n" if $_ eq "q" && $DEBUG;
# $# could be "the output format of printed numbers"
# or it could be the start of an expression like $#X or $#{@$X}
# in the latter case we need $# + one more token to be contiguous
if ($Q =~ /^\$\#\{/ || $Q =~ /^\$\#\w+/) {
$token = $&;
push @tokens, $token;
push @contexts, "\$# operator";
$i = $i - 1 + length $token;
$sigil = 0;
next;
}
if ($sigil{$_} && $Q !~ /^\$\#/) {
$sigil = $sigil{$_};
push @tokens, $_;
push @contexts, "SIGIL";
next;
}
if (!$sigil && ($_ eq "'" || $_ eq '"' ||
$_ eq "/" && regex_or_divide(\@tokens,\@contexts) eq "regex")) {
# walk through @INPUT looking for the end of the string
# manage a boolean $escaped variable handy to allow
# escaped strings inside strings.
my $escaped = 0;
my $terminator = $_;
for($j = $i + 1; $j <= $#INPUT; $j++) {
if ($INPUT[$j] eq "\\") {
$escaped = !$escaped;
next;
}
last if $INPUT[$j] eq $terminator && !$escaped;
$escaped = 0;
}
my $token = "@INPUT[$i..$j]";
if ($_ eq "/" && (length $token > 30 || $j >= $#INPUT)) {
# this regex is pretty long. Maybe we made a mistake.
my $toke2 = find_token_keyword($Q) || "/";
$token = $toke2;
$_ = "/!";
}
push @tokens, $token;
if ($_ eq "/!") {
push @contexts, "misanalyzed regex or operator";
} elsif ($_ eq "/") {
push @contexts, "regular expression C ///";
} else {
push @contexts, "quoted string";
}
$i = $j;
} elsif (!$sigil && $Q =~ /^[0-9]*\.{0,1}[0-9]+([eE][-+]?[0-9]+)?/) {
# if first char starts a numeric literal, include all characters
# from the number in the token
$token = $&;
push @tokens, $token;
push @contexts, "numeric literal A";
$i = $i - 1 + length $token;
} elsif (!$sigil && $Q =~ /^[0-9]+\.{0,1}[0-9]*([eE][-+]?[0-9]+)?/) {
$token = $&;
push @tokens, $token;
push @contexts, "numeric literal B";
$i += length $token;
} elsif (!$sigil && ($Q =~ /^m\W/ || $Q =~ /^qr\W/ || $Q =~ /^q[^\w\s]/ || $Q =~ /^qq\W/)) {
$j = $Q =~ /^q[rq]\W/ ? $i + 3 : $i + 2;
my $terminator = $INPUT[$j - 1];
$terminator =~ tr!{}<>[]{}()!}{><][}{)(!;
my $escaped = 0;
for(; $j <= $#INPUT; $j++) {
if ($INPUT[$j] eq "\\") {
$escaped = !$escaped;
next;
}
last if $INPUT[$j] eq $terminator && !$escaped;
# XXX - if regex has 'x' modifier,
# then
$escaped = 0;
}
push @tokens, "@INPUT[$i..$j]";
push @contexts, "regular expression A /$terminator/";
$i = $j;
} elsif (!$sigil && ($Q =~ /^s\W/ || $Q =~ /^y\W/ || $Q =~ /^tr\W/)) {
$j = $_ eq "t" ? $i + 3 : $i + 2;
my $terminator = $INPUT[$j-1];
$terminator =~ tr!{}<>[]{}()!}{><][}{)(!;
my $escaped = 0;
my $terminators_found = 0;
for (; $j <= $#INPUT; $j++) {
if ($INPUT[$j] eq "\\") {
$escaped = !$escaped;
next;
}
if ($INPUT[$j] eq $terminator && !$escaped) {
if ($terminators_found++) {
last;
}
}
$escaped = 0;
}
push @tokens, "@INPUT[$i..$j]";
push @contexts, "regular expression B /$terminator/";
$i = $j;
} elsif ($Q =~ /^[a-zA-Z_]\w*/) {
$token = $&;
# "T"x90 should be ["T",x,90] not ["T",x90]
# x90 should be x,90 when previous token is a scalar
if ($token =~ /^x\d+$/) {
if ($tokens[-1] =~ /^[\'\"]/ || $tokens[-1] eq ")"
|| $contexts[-1] =~ /name/) {
$token = "x";
}
}
push @tokens, $token;
if ($sigil) {
push @contexts, "name";
} elsif ($contexts[-1] =~ /regular expression ([ABC]) \/(.)\//) {
push @contexts, "regular expression modifier";
my $regex_type = $1;
my $terminator = $2;
# with some modifiers we can be more flexible with the earlier tokens ...
# e - second pattern is an expression that can be flexible
# x - first and/or second pattern can contain whitespace
if (0 && $token =~ /e/ && $token =~ /x/ && $tokens[-2] =~ /^s/) {
$DB::single=1;
pop @tokens;
pop @contexts;
my $regex = pop @tokens;
my $regex_context = pop @contexts;
my $terminator2 = $terminator;
$terminator2 =~ tr/])}>/[({</; # >})]
my $t1 = index($regex,$terminator2);
my $t2 = index($regex,$terminator,$t1+1);
push @tokens, substr($regex,0,$t1+1);
push @contexts, "regular expression x /$terminator/";
for (my $t=$t1+1; $t<=$t2; $t++) {
if (substr($regex,$t,1) =~ /\S/) {
push @tokens, substr($regex,$t,1);
push @contexts, "content of regex/x";
}
}
$i -= length($token) + length($regex) - $t2 - 1;
# positions $i to the start of the 2nd pattern,
# which can be tokenized as a perl expression.
# Hopefully the terminator can be recognized
} elsif ($token =~ /x/) {
pop @tokens;
pop @contexts;
my $regex = pop @tokens;
my $regex_context = pop @contexts;
my $terminator2 = $terminator;
$terminator2 =~ tr/])}>/[({</;
my $t1 = index($regex,$terminator2);
my $t2 = index($regex,$terminator,$t1+1);
push @tokens, substr($regex,0,$t1+1);
push @contexts, "regular expression x /$terminator/";
for (my $t=$t1+1; $t<=$t2; $t++) {
if (substr($regex,$t,1) =~ /\S/) {
push @tokens, substr($regex,$t,1);
push @contexts, "content of regex/x";
}
}
$i -= length($token) + length($regex) - $t2 - 1;
} elsif ($token =~ /e/ && $tokens[-2] =~ /^s/) {
if ($regex_type eq "B") { # s///, tr///, y///
pop @tokens;
pop @contexts;
my $regex = pop @tokens;
my $regex_context = pop @contexts;
my $terminator2 = $terminator;
$terminator2 =~ tr/])}>/[({</;
my $t1 = index($regex,$terminator2);
my $t2 = index($regex,$terminator,$t1+1);
push @tokens, substr($regex,0,$t2+1);
push @contexts, "regular expression b /$terminator/";
$i -= length($token) + length($regex) - $t2 - 1;
}
}
} else {
push @contexts, "alphanumeric literal"; # bareword? name? label? keyword?
}
$i = $i -1 + length $token;
} elsif (($token = find_token_keyword($Q)) && !$sigil) {
push @tokens, $token;
push @contexts, "operator";
$i = $i - 1 + length $token;
} else {
push @tokens, $_;
if ($sigil) {
push @contexts, "name";
} elsif (/\s/) {
push @contexts, "whitespace";
lib/Acme/AsciiArtinator.pm view on Meta::CPAN
compile or to behave differently.
The ASCII Artinator tokenizes the code and
does its best to identify
=over 4
=item 1. Character strings that must not be divided
These include alphanumeric literals, quoted strings,
and most regular expressions.
=item 2. Places in the code where it is OK to insert padding.
=item 3. Places in the ASCII artwork where there are multiple
consecutive darkspace characters
=back
The next step is to try to align the tokens from the code
with enough contiguous blocks of darkspace in the art. When
a token is misaligned, we attempt to align it by inserting
some padding at some point in the code before that token.
There are currently two ways that we pad the code. Each
time there is a need to pad the code, we randomly choose
a padding method and randomly choose an eligible position
for padding.
=over 4
=item 1. Inserting semi-colons at the beginning or end of a statement
In general, we can put as many semi-colons as we like at the beginning
or end of statements. The following lines of code should all do the
same thing:
$a=$b+$c;$d=4
$a=$b+$c;;;;;;$d=4;;;;;;
;;;;;;;;;$a=$b+$c;;;;;;;;$d=4;
=item 2. Putting braces around a variable name.
In general, we can replace C<$name> with C<${name}> and the code
will run the same.
=back
There are several other interesting ways to pad code (putting parentheses
around expressions, adding and or-ing zeros to expressions, using quoted
strings in a void context) that may be put to use in future versions
of this module.
When all tokens from the code are successfully aligned with the
blocks of darkspace from the artwork, we can paste the code on top
of the art and write the output file.
Sometimes we insert too many characters without successfully
aligning the tokens and darkspace blocks (and actually in the
spider example, this happens about 90% of the time). If this
happens, we will start over and retry up to 100 times.
=head1 BEST PRACTICES
Certain coding practices will increase the chance that
C<Acme::AsciiArtinator> will be able to embed your code
in the artwork of your choice. In no particular order,
here are some suggestions:
=over 4
=item * Make sure the original code works
Make sure the code compiles and test it to see if it
works like you expect it to
before running the ASCII Artinator. It would be frustrating to
try to debug an artinated script only to later realize that
there was some bug in the original input.
=item * Get rid of comments
This module won't handle comments very well. There's no way
to stop the ASCII Artinator from splitting your comment across
two lines and breaking the code.
=item * Reduce whitespace
In addition to making the code longer and thus more difficult
to align, any whitespace in your code will be printed out as
space over a darkspace in the art and put a "hole" in your
picture. It would be nice if there was a way to align the
whitespace in the code with the whitespace in the art, but that
is probably something for a far future version.
=item * Avoid significant newlines
Newlines are stripped from the code before the code is tokenized.
If there are any significant newlines (I mean the literal 0x0a char.
It should still be OK to say C<print"\n">), then the artinated
code will run differently.
=item * Consider workarounds for quoted strings
Quoted strings are parsed as a single token. Consider ways to break
them up so that can be split into multiple tokens. For example, instead
of saying C<$h="Hello, world!";>, we could actually say something like:
&I;($c,$e)=qw(, !);$h=H.e.l.l.o.$c.$".W.o.r.l.d.$e;
The modified code is a lot longer, but this code can be split at any
point except in the middle of C<qw>, so it is much more flexible code
from the perspective of the Artinator.
=item * Perform some smart reordering
In the spider example, we see that the largest contiguous blocks of
darkspace are in the center of the spider, and at the beginning and
end of the spider art, there are many smaller blocks of darkspace.
In this case, code that has large tokens in the middle or near the
end of the code will be more flexible than code with large tokens in
the beginning of the code. So for example, we are better off
( run in 2.277 seconds using v1.01-cache-2.11-cpan-5e09290becf )