Skip to content

Instantly share code, notes, and snippets.

@nikic
Created June 13, 2011 12:49
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 nikic/1022717 to your computer and use it in GitHub Desktop.
Save nikic/1022717 to your computer and use it in GitHub Desktop.
HQ9 interpreter
<?php
define('SAFE_MODE', 42);
echo '<pre>';
function throw_exception($error) {
die('--- EXCEPTION: ' . $error);
}
if (!isset($_GET['source'])) {
$_GET['source'] = '';
}
$source = str_replace(' ', '+', $_GET['source']);
$length = strlen($source);
function s($position) {
global $source, $length;
if ($position < 0 || $position >= $length) {
return '';
}
return strtolower($source[$position]);
}
$COUNTER = 0;
class Superclass {}
class Subclass extends Superclass { public function throwException() {} }
for ($i = 0; $i < $length; ++$i) {
if (s($i) == 'h') {
echo 'Hallo World', "\n";
}
elseif (s($i) == 'q') {
echo $source, "\n";
}
elseif (s($i) == '9') {
$j = 100;
while (--$j != 1) {
echo $j, ' bottles of beer', "\n",
'you take one down, pass it around,', "\n",
$j-1, ' bottles of beer on the wall.', "\n\n";
}
echo '1 bottle of beer', "\n",
'you take it down, pass it around,', "\n",
'no more bottles of beer on the wall.', "\n\n";
}
elseif (s($i) == '+') {
++$COUNTER;
if (s($i-1) == '+') {
new Subclass();
}
}
elseif (s($i) == '-') {
if (s($i-1) == '') {
throw_exception('syntax error');
}
elseif (s($i-1) == 'h') {
throw_exception('I/O error');
}
elseif (s($i-1) == 'q') {
function infinite_recursion() {
infinite_recursion();
}
if (!defined('SAFE_MODE')) {
infinite_recursion();
}
else {
throw_exception('infinite recursion detected');
}
}
elseif (s($i-1) == '9') {
if (!defined('SAFE_MODE')) {
while (1) {};
}
else {
throw_exception('infinite loop detected');
}
}
elseif (s($i-1) == '+') {
ob_start();
1/0;
ob_end_clean();
throw_exception('devision by zero');
}
elseif (s($i-1) == '+' && s($i-2) == '+') {
$obj = new Subclass();
$obj->throwException();
throw_exception('uncaught exception');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment