- preg_match: documentation ( source)
- preg_replace: documentation ( source)
<?php
class interpreter {
private $_code;
public function __construct($code) {
if(!is_string($code)) exit('Error while parsing code; Code not conformal.');
$this->_code = $code;
$this->parser();
}
public function parser($code = null) {
if($code === null) $code = $this->_code;
$calls = [];
$variables = [];
$conditions = [];
preg_match('#(.*)\((.*)\)#', $code, $calls);
preg_match('#if\((.*)\) \{(.*)\}#s', $code, $conditions);
if($conditions && isset($conditions[0])) $this->conditions_ifelse($conditions);
if($calls && isset($calls[0])) $this->calls($calls);
}
private function calls(array $calls) {
switch($calls[1]) {
case 'print': $this->func_print($calls[2]); break;
}
}
private function condition_ifelse(array $conditions) {
if(!preg_match('#(.*)(==|===|\<|\<=|\>|\>=|!=|!==|&&|\|\||AND|OR|XOR)(.*)#i', $conditions[1])) exit('Condition parsing error.');
}
}
abstract class lang {
const version = 0.1;
}
class console extends lang {
}
class out extends console {
public function println($arg) {
if(preg_match('#^("|\')(.*)("|\')$#', $arg)) $arg = preg_replace('#^("|\')(.*)("|\')$#', '$2', $arg);
echo($arg);
}
}
$code = <<<CODE
int var = 1;
if(var == 1) {
console.out.println("Hello World!");
}
else {
console.out.println("Hi!");
}
CODE;
$program = new interpreter($code);