Skip to content

Instantly share code, notes, and snippets.

@RaVbaker
Created November 6, 2011 00:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save RaVbaker/1342255 to your computer and use it in GitHub Desktop.
Save RaVbaker/1342255 to your computer and use it in GitHub Desktop.
How to create new programming language in PHP?
// This is written in pseudo language
class Foo {
def bar() {
ret "Działa!";
}
}
$f = Foo.new();
print $f.bar();
$realTrue = true;
if($realTrue)
print "Real True!";
unless($realTrue != false)
print "unlessss....";
<?php
class NewLangParser {
private $_handler;
private $_path;
public function stream_open($path, $mode, $options, &$opened_path) {
stream_wrapper_restore('file');
$this->_handler = fopen($path, $mode);
$this->_path = $path;
self::registerLang();
return true;
}
public function stream_read($count) {
$content = fread($this->_handler, $count);
$content = $this->_parseCode($content);
if ($content)
return "<?php\n".$content;
return "";
}
private function _parseCode($content) {
$content = str_replace('def ', 'public function ', $content);
$content = str_replace('ret ', 'return ', $content);
$content = str_replace('print ', 'echo ', $content);
$content = preg_replace('/(\w+).new\((.*)\)/', 'new \\1(\\2)', $content);
$content = str_replace('.', '->', $content);
$content = preg_replace('/unless\s*\((.*)\)/', 'if(!(\\1))', $content);
return $content;
}
public function stream_eof() {
return true;
}
public function stream_stat() {
return fstat($this->_handler);
}
public function url_stat() {
return stat($this->_path);
}
public static function registerLang() {
stream_wrapper_unregister('file');
stream_wrapper_register('file', 'NewLangParser');
}
}
NewLangParser::registerLang();
include 'new-lang-code-file.php';
@RaVbaker
Copy link
Author

RaVbaker commented Nov 6, 2011

It's simple! Just use some StreamWrappers - http://www.php.net/manual/en/class.streamwrapper.php :)

@namankumar80510
Copy link

Thanks man... was looing for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment