sortle.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. #!/usr/bin/perl -w
  2. # Sortle interpreter - Implements the esoteric programming language "Sortle"
  3. # Written in 2012 by Scott Feeney aka Graue
  4. # Last modified Mar. 12, 2012 - Optimize regex matching for groups of just dots
  5. #
  6. # http://esolangs.org/wiki/Sortle
  7. # http://esolangs.org/wiki/User:Graue
  8. #
  9. # To the extent possible under law, the author(s) have dedicated all copyright
  10. # and related and neighboring rights to this software to the public domain
  11. # worldwide. This software is distributed without any warranty.
  12. #
  13. # You should have received a copy of the CC0 Public Domain Dedication along
  14. # with this software. If not, see:
  15. # http://creativecommons.org/publicdomain/zero/1.0/
  16. #
  17. # If this implementation disagrees with something explicitly stated in the
  18. # language spec, it is a bug in the implementation, not the spec. Please let
  19. # me know of any such bugs you find! You can email me via my user page on the
  20. # wiki (linked above). Thanks.
  21. use strict;
  22. #STILL TO DO:
  23. # maybe use bignums for integer calculations and conversions(?)
  24. # test some more
  25. # clean up debug msgs
  26. # $verbose can be:
  27. # 0: no debug info - only print the final expression's name (if program halts)
  28. # 1: show state after each evaluation - useful for non-halting programs
  29. # 2: show state AND show progress of stack during evals
  30. # 3: all that AND show progress of regex matches
  31. # 1000: all that AND random debugging crap
  32. my $verbose = 0;
  33. # Leave strings untouched, while converting integers to strings,
  34. # with the odd requirement that in Sortle, the integer 0
  35. # becomes the null string.
  36. #
  37. # All input strings should be prefixed with '"'.
  38. # Output string is also prefixed with '"'.
  39. #
  40. sub sortlestring($) {
  41. my $s = $_[0];
  42. return $s if substr($s, 0, 1) eq '"';
  43. return '"' if $s == 0;
  44. return "\"$s";
  45. }
  46. # Convert to integer without any annoying warning about the argument
  47. # not being numeric (just use 0 then).
  48. # If input is a string, and it is prefixed with ", this marker will be removed
  49. # prior to conversion.
  50. sub toint($) {
  51. my $s = "$_[0]";
  52. $s = substr($s, 1) if substr($s, 0, 1) eq '"';
  53. my $x;
  54. if (($x) = $s =~ /^([+-]?\d+)/) {
  55. $x = int $x;
  56. } else {
  57. $x = 0;
  58. }
  59. return $x;
  60. }
  61. # return 1 if both strings are equal, 0 otherwise,
  62. # considering the character "." in $a to be equivalent to any character in $b.
  63. sub stringequaldot($$) {
  64. my ($a, $b) = @_;
  65. return 0 if length $a != length $b;
  66. for (my $x = 0; $x < length $a; $x++) {
  67. my $ac = substr $a, $x, 1;
  68. next if $ac eq ".";
  69. my $bc = substr $b, $x, 1;
  70. return 0 if $ac ne $bc;
  71. }
  72. return 1;
  73. }
  74. sub matchregex($$;$);
  75. # match a verified well-formed regex against a specific string
  76. # (no substrings)
  77. # return: string containing captures, or undef if no match
  78. sub matchregex($$;$) {
  79. my ($regex, $s, $captureall) = @_;
  80. if ($verbose >= 3) {
  81. print " ";
  82. # print - if non-recursive
  83. print (defined($captureall) ? " " : "-");
  84. print "matchregex \"$regex\" \"$s\" ";
  85. print "capt:$captureall" if defined $captureall;
  86. print "\n";
  87. }
  88. # $captureall is only set when this is called recursively.
  89. # if not set, turn it off if regex contains () and on otherwise.
  90. if (!defined $captureall) {
  91. $captureall = $regex !~ /\(/ || 0;
  92. }
  93. # a null string is matched only by an empty regex,
  94. # which captures the empty string
  95. if ($s eq "") {
  96. if ($regex eq "") { return ""; }
  97. else { return undef; }
  98. }
  99. # otherwise, if regex is empty it's a non-match
  100. return undef if $regex eq "";
  101. # separate out any non-grouped characters at beginning of regex
  102. # not followed by a modifier (@ or !)
  103. my ($reghead) = $regex =~ /^([^([@!]+)(?![@!])/;
  104. if (defined $reghead) {
  105. my $stringhead = substr $s, 0, length $reghead;
  106. print " (found reghead: $reghead vs. $stringhead)\n" if $verbose >= 1000;
  107. return undef if !stringequaldot($reghead, $stringhead);
  108. print " (heads match)\n" if $verbose >= 1000;
  109. # head matches, see if the rest does
  110. my $tailmatch = matchregex((substr $regex, length $reghead),
  111. (substr $s, length $reghead), $captureall);
  112. return undef if !defined $tailmatch;
  113. # so it did match and captured $tailmatch. If capturing all,
  114. # prepend our part-match to that, otherwise leave it alone
  115. return ($captureall ? $stringhead . $tailmatch : $tailmatch);
  116. }
  117. # at the beginning of the regex,
  118. # we have either a group, or a single character with modifier
  119. # (which we can treat as a [] group with modifier).
  120. # first, get the group.
  121. my ($group) = $regex =~ /^(\[[^[]*\])/;
  122. ($group) = $regex =~ /^(\([^(]*\))/ if !defined $group;
  123. $group = "[" . substr($regex, 0, 1) . "]" if !defined $group;
  124. # now get its modifier, if any.
  125. my $mod;
  126. my $tailidx = length $group; # string offset in regex after group
  127. # if group was a single character, and we added [] around it,
  128. # account for that.
  129. print " group is >>>$group<<<\n" if $verbose >= 1000;
  130. print " length of group before adjusting is $tailidx\n" if $verbose >= 1000;
  131. $tailidx -= 2 if index("([", substr($regex, 0, 1)) == -1;
  132. print " length of group is $tailidx and length of regex is "
  133. . length($regex) . "\n" if $verbose >= 1000;
  134. if ($tailidx == length $regex) { $mod = ""; }
  135. elsif (substr($regex, $tailidx, 1) eq "@") {
  136. $mod = "@";
  137. $tailidx++;
  138. } elsif (substr($regex, $tailidx, 1) eq "!") {
  139. $mod = "!";
  140. $tailidx++;
  141. } else { $mod = ""; }
  142. # min and max number of times the group must repeat
  143. my $minrepeat = (($mod eq "@") ? 0 : 1);
  144. my $maxrepeat = (($mod eq "!") ? -999 : 1);
  145. # content of group:
  146. # if $group is "(foo)" or "[foo]", $content is "foo"
  147. my $content = substr $group, 1, -1;
  148. # match group with fewest number of repetitions that allows
  149. # rest of string to match (minimal munch)
  150. my $tailmatch = undef; # set to partial capture when tail matched
  151. my $matchcount; # num chars matched in the string
  152. if ($content =~ /^\.+$/ && $maxrepeat < 0) {
  153. # optimize: group is entirely dots, like the common (.)! pattern
  154. # with no maximum repetition count
  155. my $dotstep = length $content; # step size, e.g. (..)! can only
  156. # match an even number of chars
  157. my $dots;
  158. for ($dots = $minrepeat*$dotstep; $dots <= length $s; $dots += $dotstep) {
  159. # guaranteed the dots match... does the tail match?
  160. $tailmatch = matchregex(substr($regex, $tailidx),
  161. substr($s, $dots), $captureall);
  162. last if defined $tailmatch;
  163. }
  164. $matchcount = $dots if defined $tailmatch;
  165. } else {
  166. # general case
  167. my ($acc, $reps);
  168. for ($acc = "", $reps = 0;
  169. $reps-1 != $maxrepeat;
  170. $acc .= $content, $reps += 1) {
  171. print " ACC is >>>$acc<<< REPS is $reps NEED [$minrepeat, $maxrepeat]\n" if $verbose >= 1000;
  172. # do we have enough repetitions yet?
  173. next if $reps < $minrepeat; # nope, build up $acc first
  174. # does the repeated group match?
  175. last if !stringequaldot($acc, substr($s, 0, length $acc));
  176. # does the tail match?
  177. $tailmatch = matchregex(substr($regex, $tailidx),
  178. substr($s, length $acc), $captureall);
  179. last if defined $tailmatch;
  180. }
  181. $matchcount = length $acc if defined $tailmatch;
  182. }
  183. # if tail not matched for any allowed number of repetitions,
  184. # then the whole regex doesn't match
  185. return undef if !defined $tailmatch;
  186. # 1. If capturing all, return what we matched here, plus the tail.
  187. if ($captureall) {
  188. return substr($s, 0, $matchcount) . $tailmatch;
  189. }
  190. # 2. Otherwise, if this group was (), return what we matched here.
  191. elsif (substr($group, 0, 1) eq "(") {
  192. return substr($s, 0, $matchcount);
  193. }
  194. # 3. Group [] and not capturing all, so return (possibly empty) tail
  195. # only.
  196. else { return $tailmatch; }
  197. }
  198. # evaluate a regex (against $s OR all other expression names)
  199. # and return string result: capture if matched, "" otherwise
  200. # if () are not used in regex, the capture is the whole string
  201. sub evalregex($$$$) {
  202. my ($regex, $s, $ip, $exprref) = @_;
  203. # check regex for nested groups
  204. die "Nested groups not allowed in regex \"$regex\""
  205. if $regex =~ /\([^)]*[([]/
  206. || $regex =~ /\[[^\]]*[([]/;
  207. # or unclosed []s
  208. my $opencount = 0;
  209. $opencount++ while $regex =~ /\[/g;
  210. $opencount-- while $regex =~ /\]/g;
  211. die "Unclosed [] group in regex \"$regex\"" if $opencount != 0;
  212. # or unclosed or multiple ()s
  213. $opencount = 0;
  214. $opencount++ while $regex =~ /\(/g;
  215. die "Multiple () groups not allowed in regex \"$regex\""
  216. if $opencount > 1;
  217. $opencount-- while $regex =~ /\)/g;
  218. die "Unclosed () group in regex \"$regex\"" if $opencount != 0;
  219. if ($s ne "") {
  220. # Test every substring of $s, starting with one-byte
  221. # substrings from left to right.
  222. my $match = undef; # set to captured string when matched
  223. for (my $len = 1; $len <= length $s && !defined $match;
  224. $len++) {
  225. for (my $start = 0; length $s - $len >= $start
  226. && !defined $match; $start++) {
  227. $match = matchregex($regex,
  228. (substr $s, $start, $len));
  229. }
  230. }
  231. return $match || "";
  232. }
  233. # op1 is "", so search all expression names other than the current
  234. # expression ($ip).
  235. # The .pdf spec doesn't specify an order, but the earlier sortle.txt
  236. # spec says expression names are searched in reverse order, starting
  237. # with the one before the current expression.
  238. # So we'll do that. To start, find the index of the current ip.
  239. my @expnames = reverse sort keys %{ $exprref };
  240. my $idx;
  241. for ($idx = 0; $expnames[$idx] ne $ip; $idx++) {
  242. die "Internal error" if $idx == $#expnames;
  243. }
  244. $idx = ($idx + 1) % (scalar @expnames);
  245. my $match = undef; # set to captured string when matched
  246. while ($expnames[$idx] ne $ip && !defined $match) {
  247. $match = matchregex($regex, $expnames[$idx]);
  248. $idx = ($idx + 1) % (scalar @expnames);
  249. }
  250. return $match || "";
  251. }
  252. # evaluate an expression (array reference)
  253. # and return string result. 2nd arg - ip; 3rd - reference to exprs hash
  254. sub evalexpr($$$) {
  255. my @expr = @{ $_[0] };
  256. my $ip = $_[1];
  257. my $exprref = $_[2];
  258. my @stack = ();
  259. foreach my $tok (@expr) {
  260. if ($verbose >= 2) {
  261. # print stack and token
  262. print " -stack:";
  263. foreach my $elmt (@stack) {
  264. print " [$elmt]";
  265. }
  266. print "\n";
  267. print " token: $tok\n";
  268. }
  269. # literal string
  270. # Note: This preserves the " at the beginning (not end)
  271. # when pushing on stack. This is done because there is
  272. # seemingly no way to distinguish string "0" from number 0
  273. # in Perl (it's too eager to convert one to the other).
  274. # We need this because in Sortle, the number 0 coerced to a
  275. # string becomes not "0" but "".
  276. # Thus, on the stack, we would store "0" as ["0]
  277. # and 0 as [0], without the [].
  278. # toint() will remove the leading " if needed
  279. # (but does not require it), and sortlestring() adds the "
  280. # if not present.
  281. if (my ($s) = $tok =~ /^(".*)"$/) {
  282. # handle escape sequences: \ab => character 0xab
  283. $s =~ s/\\([[:xdigit:]]{2})/chr hex $1/ge;
  284. # (To be pedantic, we could check for uses of \
  285. # outside a valid escape sequence, and report an
  286. # error - but I'm too lazy, so that can just be
  287. # considered undefined behavior.)
  288. push @stack, $s;
  289. next;
  290. }
  291. # literal number
  292. if ($tok =~ /^[+-]?\d+$/) {
  293. push @stack, toint($tok);
  294. next;
  295. }
  296. # must be an operator... all of which take 2 operands
  297. die "Stack empty" if 1+$#stack < 2;
  298. my $op1 = pop @stack;
  299. my $op2 = pop @stack;
  300. if (index("+*/%", $tok) != -1) {
  301. # operator requires and produces numbers
  302. $op1 = toint($op1);
  303. $op2 = toint($op2);
  304. push(@stack, $op1 + $op2) if $tok eq "+";
  305. push(@stack, $op1 * $op2) if $tok eq "*";
  306. push(@stack, int($op1 / $op2)) if $tok eq "/";
  307. push(@stack, $op1 % $op2) if $tok eq "%";
  308. } else {
  309. # operator requires and produces strings
  310. $op1 = substr sortlestring($op1), 1;
  311. $op2 = substr sortlestring($op2), 1;
  312. push(@stack, '"' . $op2 . $op1) if $tok eq "~";
  313. if ($tok eq "^" || $tok eq "\$") {
  314. if ($op1 gt $op2) { push(@stack, '"' . $op1); }
  315. else { push(@stack, '"' . $op2); }
  316. }
  317. push(@stack, '"' . evalregex($op2, $op1, $ip, $exprref))
  318. if $tok eq "?";
  319. }
  320. }
  321. # Need exactly one expression on stack
  322. if (scalar @stack != 1) {
  323. die "Expression left " . (scalar @stack) . " values on stack";
  324. }
  325. print " -final stack: [$stack[0]]\n\n" if $verbose >= 2;
  326. # Convert the one expression to a string, if needed
  327. my $final = $stack[0];
  328. $final = sortlestring($final) if $final !~ /^"/;
  329. # Remove the " prefix when returning the string
  330. return substr($final, 1);
  331. }
  332. # print current state
  333. # usage: printstate($ip, \%exprs)
  334. sub printstate($$) {
  335. my $ip = $_[0];
  336. my %exprs = %{$_[1]};
  337. foreach my $key (sort keys %exprs) {
  338. print "*" if $ip eq $key; # expression to evaluate next
  339. print "$key :=";
  340. foreach my $x (@{ $exprs{$key} }) {
  341. print " $x";
  342. }
  343. print "\n";
  344. }
  345. }
  346. # run one step of the program
  347. # usage: advancestate(\$ip, \%exprs)
  348. sub advancestate($$) {
  349. my $ipref = $_[0];
  350. my $oldname = $$ipref; # needed in case the expression suicides
  351. my $exprref = $_[1];
  352. my $newname = evalexpr([@{ $exprref->{$$ipref} }], $$ipref,
  353. $_[1]);
  354. # store expression under new name, unless new name is blank (suicide)
  355. $exprref->{$newname} = $exprref->{$$ipref}
  356. unless $newname eq "";
  357. # delete old name, unless it's the same as the new name
  358. delete $exprref->{$$ipref}
  359. unless $$ipref eq $newname;
  360. # find next expression in sorted order, wrapping, after $newname.
  361. # exception: if $newname is blank (expression has committed suicide),
  362. # we want the one after where the suicided expression WAS.
  363. my $isnext = 0;
  364. undef $$ipref;
  365. foreach my $x (sort keys %$exprref) {
  366. if ($newname eq "" && $x gt $oldname) {
  367. # expression suicided, but would have been before
  368. # this one.
  369. $$ipref = $x;
  370. last;
  371. }
  372. if ($x eq $newname) {
  373. $isnext = 1;
  374. next;
  375. }
  376. if ($isnext == 1) {
  377. $$ipref = $x;
  378. $isnext = 0;
  379. last;
  380. }
  381. }
  382. if (!defined $$ipref) { # means we need to wrap around
  383. $$ipref = (sort keys %$exprref)[0];
  384. }
  385. }
  386. # Top-level interpreter
  387. my %exprs = (); # code expressions
  388. # for concatenating multiple lines when a line ends with a \
  389. my $partialline;
  390. # read source code from stdin or named input files
  391. while (my $line = <>) {
  392. chomp $line;
  393. if (defined $partialline) {
  394. $line = $partialline . " " . $line;
  395. undef $partialline;
  396. }
  397. next if $line =~ /^\s*#/ || $line =~ /^\s*$/; # skip blank lines
  398. # if the line ends with a \, but the \ is NOT within a comment,
  399. # delete the \ and prepend this line to what's on the next line
  400. # ($tmp stores $line with quoted strings removed, to test if a
  401. # comment is present)
  402. my $tmp = $line;
  403. $tmp =~ s/"[^"]*"//g; # remove closed quoted strings from $tmp
  404. $tmp =~ s/"[^"]*$//; # remove an unclosed string, if present
  405. if ($tmp !~ /#/ && $line =~ /\\$/) { # no comment, but a \ on end
  406. $partialline = substr $line, 0, -1;
  407. next;
  408. # rest of line will be read, and line parsed, on next loop
  409. }
  410. # split expression name and value
  411. my ($name, $contents) = $line =~
  412. /^\s*([A-Za-z][A-Za-z0-9]*)\s*:=(.+)$/;
  413. die "Sortle syntax error" if !defined $name || !defined $contents;
  414. $contents =~ s/^(\s*)//;
  415. $contents =~ s/(\s*)$//;
  416. # split tokens at whitespace (except inside quoted strings)
  417. # Note: this code will allow strings to contain escaped double-quotes
  418. # e.g "this is a \"string\"", which technically isn't how Sortle
  419. # works. But it is undefined behavior because backslashes are
  420. # only supposed to be used in Sortle strings when followed by
  421. # two hex digits, e.g. \0a for newline. Backslashes should be
  422. # escaped in the same manner, i.e. "this is a \5c\22string\22\5c"
  423. my @tokens = $contents =~ m/\s* ("(?:(?!(?<!\\)").)*" | '(?:(?!(?<!\\)').)*' | \S+)/gx;
  424. die "Empty expression" if (scalar @tokens) <= 0;
  425. # check that tokens are valid, and remove comments
  426. my @terms = ();
  427. foreach my $tok (@tokens) {
  428. last if $tok =~ /^#/; # comment: ignore further tokens on line
  429. push @terms, $tok;
  430. next if $tok =~ /^[+-]?\d+$/; # number
  431. next if $tok =~ /^".*"$/; # string
  432. next if length $tok == 1
  433. && index("+*/%^~?\$", $tok) != -1; # operator
  434. die "Invalid token: $tok";
  435. }
  436. @{ $exprs{$name} } = @terms;
  437. }
  438. die "Last line cannot end with \\" if defined $partialline;
  439. die "No expressions defined" if scalar keys %exprs == 0;
  440. my $ip = (sort keys %exprs)[0];
  441. my $evalcount = 0;
  442. while (scalar keys %exprs > 1) {
  443. if ($verbose >= 1) {
  444. printstate($ip, \%exprs);
  445. print "$evalcount expressions evaluated\n\n";
  446. }
  447. advancestate(\$ip, \%exprs);
  448. ++$evalcount;
  449. }
  450. if ($verbose >= 1) {
  451. printstate($ip, \%exprs);
  452. print "$evalcount expressions evaluated\n\n";
  453. }
  454. print((keys %exprs)[0] . "\n");