日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > php >内容正文

php

用PHP写一个最简单的解释器Part1

發(fā)布時間:2023/12/20 php 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。