Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compiler and process for my own language
<?php
$cpu_00 = [
'set' => [
0,
['var', 'value']
],
'set_a' => [
1,
['var']
],
'set_b' => [
2,
['var']
],
'set_c' => [
3,
['var']
],
'ret' => [
4,
['var']
],
'write' => [
5,
[],
"device, position, target"
],
'get_from_file' => [
6,
[],
"file, position"
],
'jeq' => [
7,
['value', 'label']
],
'jmp' => [
8,
['label']
],
'inc' => [
9,
['value']
],
'exit' => [
10,
[]
],
'get_device' => [
11,
[]
]
];
$ins = $cpu_00;
$file = 'program.txt';
$f = fopen($file, 'r');
$current_byte = 0;
$labels = [];
$vars = [];
$bytes = [];
while ( $line = fgets($f) ) {
$line = trim($line);
if ( empty($line) ) continue;
if ( $line[0] == '/' ) continue;
$tokens = explode(' ', $line);
$instruction = $tokens[0];
echo $instruction, "\n";
if ( substr($instruction, -1) == ':' ) {
$labels[substr($instruction, 0, -1)] = $current_byte;
} else {
$bytes[] = $ins[$instruction][0];
$current_byte++;
$params = $ins[$instruction][1];
for ( $i = 0 ; $i < count($params) ; $i++ ) {
if ( $params[$i] == 'value' ) {
$bytes[] = $tokens[$i + 1];
$current_byte++;
} else if ( $params[$i] == 'var' ) {
$bytes[] = $tokens[$i + 1];
$current_byte++;
$vars[$tokens[$i + 1]] = 1;
} else if ( $params[$i] == 'label' ) {
$bytes[] = $tokens[$i + 1];
$current_byte++;
}
}
}
}
foreach ( $vars as $var => $info ) {
$vars[$var] = $current_byte;
$current_byte++;
}
function to_bin($int) {
$int = (int)$int;
$str = '';
for ( $i = 0 ; $i < 8; $i++ ) {
$str = strval($int % 2) . $str;
$int /= 2;
}
return $str;
}
$compiled = '';
//print_r($vars);
//print_r($labels);
foreach ( $bytes as $i => $byte ) {
//echo "[$byte]\n";
if ( !is_numeric($byte) ) {
if ( $byte[0] == '$' ) {
$byte = $vars[$byte];
} else {
$byte = $labels[$byte];
}
}
$compiled .= to_bin($byte);
}
function to_file($total) {
$lines = str_split($total, 8 * 4);
foreach ( $lines as $line )
echo implode("\t", str_split($line)), "\n";
}
to_file($compiled);
<?php
$file = 'hola3.txt';
$f = fopen($file, 'r');
function xor_lines($a, $b) {
$r = '';
for ( $i = 0 ; $i < 8 ; $i++ ) {
$aa = $a[$i] == '1';
$bb = $b[$i] == '1';
$r .= ($aa xor $bb) ? '1' : '0';
}
return $r;
}
$mask = '10101010';
$total = '00000001';
$total .= $mask;
while ( $line = fgets($f) ) {
$line = str_replace("\n", "", $line);
$line = str_pad($line, 8, ' ');
$line = str_replace(' ', '0', $line);
$line = str_replace('#', '1', $line);
$line = xor_lines($line, $mask);
$total .= $line;
}
function to_file($total) {
$lines = str_split($total, 8 * 4);
foreach ( $lines as $line )
echo implode("\t", str_split($line)), "\n";
}
to_file($total);
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.