用PHP写一个最简单的解释器Part1
生活随笔
收集整理的這篇文章主要介紹了
用PHP写一个最简单的解释器Part1
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
偶然間在朋友圈發(fā)現(xiàn)有人在看一本《兩周自制腳本語言》,覺得寫個腳本語言挺不錯的,方便自己對語言本身進一步了解。于是乎,買了下來看了看,寫的挺通俗易懂,但是不便的是,采用的語言是Java,PHP才是最好的語言么!為什么要采用Java。
這幾日,我也在網(wǎng)上搜索了一些資料,發(fā)現(xiàn)這個不錯。https://github.com/rspivak/ls...,不過同樣,該教程采用的也不是PHP。正如作者所言,選什么語言由你,解釋器并不依賴語言特性。
于是乎,我用PHP重寫了part1的部分,并在以后幾日,將會采用PHP重寫所有部分。
在這里寫出代碼方便自己查找,同時也希望一些對解釋器感興趣的朋友一同學(xué)習(xí)。
<?phpclass Token{private $type;private $value;public function __construct($type,$value){$this->type=$type;$this->value=$value;}public function __get($name){return $this->{$name};}public function __toString(){return 'type:'.$this->type.' value:'.$this->value;} }class Interpreter{private $current_char ;private $current_token ;private $text;private $pos=0;public function __construct($text){$this->text=trim($text);}public function error(){throw new \Exception('Lexer eroor');}public function get_next_token(){$text=$this->text;if ($this->pos > strlen($text)-1){return new Token('EOF', null);}$this->current_char = $text[$this->pos];if (is_numeric($this->current_char)){$token=new Token('INTEGER',intval($this->current_char));$this->pos++;return $token;}if ($this->current_char=="+"){$token = new Token('PLUS', $this->current_char);$this->pos ++;return $token;}$this->error();}public function eat($token_type){if ($this->current_token->type==$token_type){$this->current_token=$this->get_next_token();}else{$this->error();}}public function expr(){$this->current_token=$this->get_next_token();$left=$this->current_token;$this->eat('INTEGER');$op=$this->current_token;$this->eat('PLUS');$right=$this->current_token;$this->eat('INTEGER');$result=$left->value+$right->value;return $result;} }do{fwrite(STDOUT,'xav>');;$input=fgets(STDIN);$Interpreter=new Interpreter($input);echo $Interpreter->expr();unset($Interpreter);}while(true);
目前僅支持個位整數(shù)相加
總結(jié)
以上是生活随笔為你收集整理的用PHP写一个最简单的解释器Part1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【在线报表设计】提升报表外观的15个技巧
- 下一篇: 动态规划算法php,php算法学习之动态