Skip to content

Instantly share code, notes, and snippets.

@sanxiyn sanxiyn/stupid.php
Created Jul 22, 2012

Embed
What would you like to do?
Plain Simple Stupid Language
<?php if ($_SERVER["REQUEST_METHOD"] == "GET") { ?>
<form action="stupid.php" method="post">
<textarea name="source" cols="80" rows="15">
input n
i = 1;loopi;if i &gt; n fini
j = 1;loopj;if j &gt; n finj
product = i * j
output i * j = product
if j == n last
output /
last
j = j + 1;goto loopj;finj
newline
i = i + 1;goto loopi;fini
</textarea>
Source<br>
<textarea name="input" cols="80" rows="15">
5
</textarea>
Input<br>
<input type="submit">
</form>
<?php exit(); } ?>
<?php
$input = $_POST["input"];
$data = explode(" ", $input);
$datai = 0;
$source = $_POST["source"];
$source = str_replace(";", "\n", $source);
$source = str_replace("\r\n", "\n", $source);
$lines = explode("\n", $source);
$labels = array();
for ($i = 0; $i < count($lines); $i++) {
$line = $lines[$i];
$words = explode(" ", $line);
if (count($words) == 1) {
$label = $words[0];
$labels[$label] = $i;
}
$lines[$i] = $words;
}
$memory = array();
function get($value) {
global $memory;
if (ctype_digit($value)) {
$value = intval($value);
}
if (ctype_alpha($value)) {
if (array_key_exists($value, $memory)) {
$value = $memory[$value];
}
}
return $value;
}
$output = array();
$outline = array();
for ($i = 0; $i < count($lines); $i++) {
$line = $lines[$i];
if ($line[1] == "=") {
if (count($line) == 3) {
$name = $line[0];
$value = get($line[2]);
} else {
$name = $line[0];
$left = get($line[2]);
$op = $line[3];
$right = get($line[4]);
switch ($op) {
case "+": $value = $left + $right; break;
case "-": $value = $left - $right; break;
case "*": $value = $left * $right; break;
case "/": $value = intval($left / $right); break;
case "%": $value = $left % $right; break;
}
}
$memory[$name] = $value;
}
$command = $line[0];
switch ($command) {
case "input":
$name = $line[1];
$memory[$name] = get($data[$datai]);
$datai++;
break;
case "output":
for ($j = 1; $j < count($line); $j++) {
$value = get($line[$j]);
array_push($outline, strval($value));
}
break;
case "newline":
array_push($output, implode(" ", $outline));
$outline = array();
break;
case "if":
$left = get($line[1]);
$op = $line[2];
$right = get($line[3]);
switch ($op) {
case "==": $value = $left == $right; break;
case "!=": $value = $left != $right; break;
case "<": $value = $left < $right; break;
case "<=": $value = $left <= $right; break;
case ">": $value = $left > $right; break;
case ">=": $value = $left >= $right; break;
}
if ($value) {
$label = $line[4];
$i = $labels[$label];
}
break;
case "goto":
$label = $line[1];
$i = $labels[$label];
break;
}
}
array_push($output, implode(" ", $outline));
echo implode("<br>", $output);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.